From d7e81495215aab2a9b76f8e2ce20bc85ea1abb7a Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Fri, 20 Nov 2026 05:39:51 -0800 Subject: [PATCH] Validation: the executor runs every case on its own context, without the old runtime The old runtime goes at the cutover, so validation stops depending on it. What this removes: the engine executor's runtime path (candidate/engine/runtime_run, candidate/runtime_case, runtime_samples, the route between the two) and the code only it used: the runtime's bounded command-buffer waits, the library loader (air_library) and its scratch test, the imageblock helper test, and the runtime's degrade notices on a candidate row (observation's runtime_degrades and announced_degradations, c3's reading of them and its test). Every case now runs on the executor's own Vulkan context. What only the runtime path ran becomes an unsupported requirement in the one vocabulary: - mesh_render_pipeline: an object or mesh case. The executor-contract check raises it from the case's reflected stage, so classification and the checker see it. The requirement qualifies on Metal: the checker still admits the 15 committed object and mesh cases with no candidate (Metal-qualified, Vulkan side unsupported), so their Metal evidence stays. - replayed_template_resources: a replayed pipeline template that binds more than the context replays. The executor raises it as it prepares the case (replay_templates), as it raises depth_outside_unit_range, so no committed case is deleted. Moved into validation, as tooling: the VK_EXT_device_generated_commands entry points the device replay records (candidate/platform/generated_commands.rs; the commands layout is always made for explicit preprocessing, which runs right on every driver), the loader's ignored-driver reports (candidate/platform/ignored_drivers.rs), and makes_layouts_past_support (MoltenVK's driver id). program_instance_made and the profiles layer's runtime settings go. The runtime guard no longer hashes the old runtime's sources (build.rs walks the binder alone), and the product fingerprint no longer walks the old runtime's crate; their tests and the pinned runtime-sources.sha256 follow. The unused m2v_system_alloc cfg goes with the lanes that set it. Versions: RUNTIME_VERSION 2540, ENGINE_EXECUTOR_ABI vulkan-engine-v184, the structural-triage analyzer v83. The census is re-closed on development after the landing. Verified: the compile gate (fmt, clippy plain and under both device cfgs, workspace Rustdoc, validation's suite on lavapipe) runs on this commit; the landing note names its job and codes. --- crates/metal2vulkan-validation/Cargo.toml | 6 +- crates/metal2vulkan-validation/build.rs | 60 +- .../product_fingerprint.rs | 21 +- .../runtime-sources.sha256 | 2 +- .../src/air_library.rs | 29 - .../src/build_support_tests.rs | 8 +- crates/metal2vulkan-validation/src/c3.rs | 17 +- .../metal2vulkan-validation/src/c3/tests.rs | 75 - .../metal2vulkan-validation/src/candidate.rs | 59 - .../src/candidate/device_facts.rs | 2 +- .../src/candidate/engine.rs | 160 +- .../src/candidate/engine/artifact/tests.rs | 25 +- .../src/candidate/engine/graphics/tests.rs | 92 - .../src/candidate/engine/guards.rs | 5 +- .../src/candidate/engine/mesh.rs | 5 +- .../src/candidate/engine/runtime_run.rs | 1419 ------------ .../src/candidate/engine/runtime_run/tests.rs | 1056 --------- .../src/candidate/engine/tests.rs | 43 +- .../src/candidate/platform.rs | 3 +- .../compute/device_replay/generated.rs | 79 +- .../candidate/platform/compute/draw_replay.rs | 5 +- .../src/candidate/platform/compute/replay.rs | 15 +- .../src/candidate/platform/device.rs | 232 +- .../candidate/platform/generated_commands.rs | 440 ++++ .../src/candidate/platform/ignored_drivers.rs | 160 ++ .../src/candidate/platform/profiles.rs | 22 +- .../src/candidate/runtime_case.rs | 1942 ----------------- .../src/candidate/runtime_case/commands.rs | 599 ----- .../candidate/runtime_case/host_wait_gap.rs | 280 --- .../src/candidate/runtime_case/imageblock.rs | 416 ---- .../candidate/runtime_case/input_index_gap.rs | 295 --- .../src/candidate/runtime_case/layer_claim.rs | 801 ------- .../candidate/runtime_case/query_reset_gap.rs | 180 -- .../runtime_case/raster_order_gap.rs | 280 --- .../src/candidate/runtime_case/render.rs | 1369 ------------ .../src/candidate/runtime_case/render/mesh.rs | 232 -- .../src/candidate/runtime_case/sparse.rs | 177 -- .../src/candidate/runtime_case/tile.rs | 218 -- .../src/candidate/runtime_samples.rs | 484 ---- .../src/candidate/unadvertised_stage.rs | 8 +- .../src/candidate/unsupported_set.rs | 10 +- .../src/executor_contract.rs | 30 +- .../src/executor_contract/mesh.rs | 28 +- crates/metal2vulkan-validation/src/gpu.rs | 20 +- .../metal2vulkan-validation/src/gpu/wait.rs | 41 - crates/metal2vulkan-validation/src/lib.rs | 1 - .../metal2vulkan-validation/src/mesh_cases.rs | 6 +- .../src/observation.rs | 19 +- .../src/replay/tests.rs | 2 +- .../src/requirement.rs | 52 +- .../src/translation_audit.rs | 19 +- crates/metal2vulkan-validation/src/triage.rs | 21 +- .../src/worker/alloc.rs | 7 +- .../tests/integration/main.rs | 1 - .../tests/integration/swept_scratch.rs | 47 - crates/metal2vulkan/src/cache/mod.rs | 2 +- 56 files changed, 893 insertions(+), 10734 deletions(-) delete mode 100644 crates/metal2vulkan-validation/src/air_library.rs delete mode 100644 crates/metal2vulkan-validation/src/candidate/engine/runtime_run.rs delete mode 100644 crates/metal2vulkan-validation/src/candidate/engine/runtime_run/tests.rs create mode 100644 crates/metal2vulkan-validation/src/candidate/platform/generated_commands.rs create mode 100644 crates/metal2vulkan-validation/src/candidate/platform/ignored_drivers.rs delete mode 100644 crates/metal2vulkan-validation/src/candidate/runtime_case.rs delete mode 100644 crates/metal2vulkan-validation/src/candidate/runtime_case/commands.rs delete mode 100644 crates/metal2vulkan-validation/src/candidate/runtime_case/host_wait_gap.rs delete mode 100644 crates/metal2vulkan-validation/src/candidate/runtime_case/imageblock.rs delete mode 100644 crates/metal2vulkan-validation/src/candidate/runtime_case/input_index_gap.rs delete mode 100644 crates/metal2vulkan-validation/src/candidate/runtime_case/layer_claim.rs delete mode 100644 crates/metal2vulkan-validation/src/candidate/runtime_case/query_reset_gap.rs delete mode 100644 crates/metal2vulkan-validation/src/candidate/runtime_case/raster_order_gap.rs delete mode 100644 crates/metal2vulkan-validation/src/candidate/runtime_case/render.rs delete mode 100644 crates/metal2vulkan-validation/src/candidate/runtime_case/render/mesh.rs delete mode 100644 crates/metal2vulkan-validation/src/candidate/runtime_case/sparse.rs delete mode 100644 crates/metal2vulkan-validation/src/candidate/runtime_case/tile.rs delete mode 100644 crates/metal2vulkan-validation/src/candidate/runtime_samples.rs delete mode 100644 crates/metal2vulkan-validation/tests/integration/swept_scratch.rs diff --git a/crates/metal2vulkan-validation/Cargo.toml b/crates/metal2vulkan-validation/Cargo.toml index 631ce92a3..403293bb0 100644 --- a/crates/metal2vulkan-validation/Cargo.toml +++ b/crates/metal2vulkan-validation/Cargo.toml @@ -30,7 +30,6 @@ metal2vulkan = { path = "../metal2vulkan", features = ["serde", "ash", "cli"] } # The AIR front end the product pins exactly: the same crate the product # builds, which validation decodes, canonicalizes, and audits AIR through. metal2vulkan-air = { path = "../metal2vulkan-air" } -metal2vulkan-runtime = { path = "../metal2vulkan-runtime" } metal2vulkan-rt = { path = "../metal2vulkan-rt" } metal2vulkan-devtools = { path = "../metal2vulkan-devtools" } base64 = "0.22" @@ -55,10 +54,9 @@ ash = { workspace = true, features = ["loaded"] } # Device-executing tests are gated on non-default cfgs rather than features, because the ordinary # gate builds with `--all-features`: `--cfg m2v_gpu` (a real GPU) and `--cfg m2v_cpu_icd` (a CPU -# Vulkan ICD such as lavapipe). See docs/VALIDATION.md. `--cfg m2v_system_alloc` keeps the system -# allocator in the lib test binary for the runtime lanes' cost measurements (worker/alloc.rs). +# Vulkan ICD such as lavapipe). See docs/VALIDATION.md. [lints.rust] -unexpected_cfgs = { level = "warn", check-cfg = ["cfg(m2v_gpu)", "cfg(m2v_cpu_icd)", "cfg(m2v_gpu_hazards)", "cfg(m2v_system_alloc)"] } +unexpected_cfgs = { level = "warn", check-cfg = ["cfg(m2v_gpu)", "cfg(m2v_cpu_icd)", "cfg(m2v_gpu_hazards)"] } [build-dependencies] sha2.workspace = true diff --git a/crates/metal2vulkan-validation/build.rs b/crates/metal2vulkan-validation/build.rs index c72120471..a240ab628 100644 --- a/crates/metal2vulkan-validation/build.rs +++ b/crates/metal2vulkan-validation/build.rs @@ -7,9 +7,8 @@ use build_support::hash_files; use product_fingerprint::{collect_files, product_fingerprint}; fn main() { - // The product fingerprint (`product_fingerprint.rs`): the translator's, the runtime's, and the - // dev-tools crate's sources beside this crate in the workspace's crates/, and nothing of this - // crate. + // The product fingerprint (`product_fingerprint.rs`): the translator's and the dev-tools + // crate's sources beside this crate in the workspace's crates/, and nothing of this crate. println!( "cargo:rustc-env=METAL2VULKAN_PRODUCT_FINGERPRINT={}", product_fingerprint(Path::new("..")) @@ -106,17 +105,15 @@ fn main() { // the sRGB steps the ASTC and PVRTC decoders read (`src/lower/arith/srgb.rs`), the sRGB // transfer and half conversions the mipmap filter takes from `air.pack`'s lowering // (`src/lower/arith/pack.rs`), the blend color an - // extended-range blend reads (`src/lower/arith/extended_range/blend_color.rs`), half-float - // conversion, and the Metal-like runtime (`metal2vulkan-runtime/src`, with the measured answers - // it reads), through which the executor runs the families that have moved onto it. The - // translator's paths above are below its crate (`metal2vulkan/src/...`). Each path is a product - // file below the workspace's crates/ directory, this crate's parent: those listed here, the - // binder's Rust sources under `metal2vulkan/src/bind/`, and every file under - // `metal2vulkan-runtime/src/`, test modules aside (`runtime_files`, so a file added under - // either joins), all sorted as strings. The guard test in `candidate::engine::artifact` - // requires this hash to be the one validation pins (`runtime-sources.sha256`), and the inputs - // to be closed over the module files their non-test code reaches (each is an input, or listed - // there with why a run does not depend on it beyond the artifact digest). + // extended-range blend reads (`src/lower/arith/extended_range/blend_color.rs`), and half-float + // conversion. The translator's paths above are below its crate (`metal2vulkan/src/...`). Each + // path is a product file below the workspace's crates/ directory, this crate's parent: those + // listed here and the binder's Rust sources under `metal2vulkan/src/bind/`, test modules aside + // (`runtime_files`, so a file added there joins), all sorted as strings. The guard test in + // `candidate::engine::artifact` requires this hash to be the one validation pins + // (`runtime-sources.sha256`), and the inputs to be closed over the module files their non-test + // code reaches (each is an input, or listed there with why a run does not depend on it beyond + // the artifact digest). let listed = [ "metal2vulkan-air/src/canon/function_table.rs", "metal2vulkan-air/src/canon/rate_map_data.rs", @@ -183,13 +180,6 @@ fn main() { runtime_files( &product, Path::new("metal2vulkan/src/bind"), - Walk::Sources, - &mut runtime_inputs, - ); - runtime_files( - &product, - Path::new("metal2vulkan-runtime/src"), - Walk::Files, &mut runtime_inputs, ); runtime_inputs.sort(); @@ -223,21 +213,12 @@ fn crate_files(root: &Path) -> Vec { files } -/// What a walked directory gives the runtime's inputs. -#[derive(Clone, Copy, PartialEq)] -enum Walk { - /// Every file: the runtime crate's sources and the measured answers they read. - Files, - /// The Rust sources alone: the binder (`metal2vulkan/src/bind/`), whose non-test code reads no data file - /// (its `.txt` files are its tests' measured answers). - Sources, -} - -/// Every file below `relative` under `product` that `walk` takes, but test modules (a `tests` -/// directory, a `tests.rs` or `*_tests.rs` file) and hidden files, pushed as paths relative to -/// `product` with `/` separators. Cargo reruns this script when anything under the directory -/// changes, so a file added there joins the runtime's inputs. -fn runtime_files(product: &Path, relative: &Path, walk: Walk, output: &mut Vec) { +/// Every Rust source below `relative` under `product` but test modules (a `tests` directory, a +/// `tests.rs` or `*_tests.rs` file) and hidden files, pushed as paths relative to `product` with +/// `/` separators: the binder's (`metal2vulkan/src/bind/`), whose non-test code reads no data file +/// (its `.txt` files are its tests' measured answers). Cargo reruns this script when anything +/// under the directory changes, so a file added there joins the runtime's inputs. +fn runtime_files(product: &Path, relative: &Path, output: &mut Vec) { let directory = product.join(relative); println!("cargo:rerun-if-changed={}", directory.display()); let entries = fs::read_dir(&directory) @@ -251,12 +232,9 @@ fn runtime_files(product: &Path, relative: &Path, walk: Walk, output: &mut Vec String { let mut hash = product_hash(&crates.join("metal2vulkan")); - hash_files(&mut hash, crates, &runtime_crate_files(crates)); hash_files(&mut hash, crates, &devtools_files(crates)); hex(&hash.finalize()) } -/// The runtime crate's manifest and the files its module tree compiles or reads -/// (`build_support::product_files`), sorted. -fn runtime_crate_files(crates: &Path) -> Vec { - let runtime = crates.join("metal2vulkan-runtime"); - let mut files = vec![runtime.join("Cargo.toml")]; - files.extend(product_files(&runtime)); - files.sort(); - files -} - /// The dev-tools crate's manifest and every file under its `src/`, sorted. fn devtools_files(crates: &Path) -> Vec { let devtools = crates.join("metal2vulkan-devtools"); diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index bf3bb2897..66423e5dd 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -ada64eb2f6d77187192b5bca791f98607b1598bc6882c23b1b38f11ab32e1001 +a5d1cbcfba2baf815b6fab4a7eb44ec2c0468e4a39bee65d8fc86fa02903a58a diff --git a/crates/metal2vulkan-validation/src/air_library.rs b/crates/metal2vulkan-validation/src/air_library.rs deleted file mode 100644 index fd523506d..000000000 --- a/crates/metal2vulkan-validation/src/air_library.rs +++ /dev/null @@ -1,29 +0,0 @@ -//! Runtime libraries of the AIR bitcode the validation's cases and lanes hold. -//! -//! The runtime's `Device::new_library_with_data` takes a metallib alone, as Metal's -//! `newLibraryWithData:error:` does. The cases are AIR bitcode, which `llvm-as` assembles from -//! their LLVM text: the translator parses it, and the device takes the parsed library -//! (`Device::new_library_with_compile_library`). - -use metal2vulkan_runtime::{Device, Error, Library}; - -/// A device's library of AIR bitcode. -pub trait AirLibrary { - /// The library of `bytes`: AIR bitcode, raw or wrapped, as the translator parses it - /// (`metal2vulkan::library::Library::parse`, which takes a metallib too). A refusal is the - /// translator's, as the runtime reports it (`Error::Unsupported` or `Error::Compile`). - fn new_library_with_air(&self, bytes: &[u8]) -> Result; -} - -impl AirLibrary for Device { - fn new_library_with_air(&self, bytes: &[u8]) -> Result { - let library = - metal2vulkan::library::Library::parse(bytes).map_err(|error| match error { - metal2vulkan::error::Error::Unsupported(unsupported) => { - Error::Unsupported(unsupported) - } - other => Error::Compile(other), - })?; - Ok(self.new_library_with_compile_library(library)) - } -} diff --git a/crates/metal2vulkan-validation/src/build_support_tests.rs b/crates/metal2vulkan-validation/src/build_support_tests.rs index 766bcd663..4c304a930 100644 --- a/crates/metal2vulkan-validation/src/build_support_tests.rs +++ b/crates/metal2vulkan-validation/src/build_support_tests.rs @@ -418,8 +418,8 @@ fn the_product_fingerprint_covers_the_front_end_crate_by_path() { } /// This build's product fingerprint is the walk over this workspace's translator, then the -/// runtime's and the dev-tools crates (`product_fingerprint.rs`, which `build.rs` shares), each in -/// its directory beside this crate, and the walk leaves out each crate's test-only modules: no file +/// dev-tools crate (`product_fingerprint.rs`, which `build.rs` shares), each in its directory +/// beside this crate, and the walk leaves out each crate's test-only modules: no file /// it lists is declared only under `#[cfg(test)]`. #[test] fn this_builds_product_fingerprint_is_the_walk_over_the_product() { @@ -437,10 +437,6 @@ fn this_builds_product_fingerprint_is_the_walk_over_the_product() { assert!(product.contains(Path::new("src/indirect_commands/host.rs"))); assert!(!product.contains(Path::new("src/pipeline/testing.rs"))); assert!(!product.contains(Path::new("src/pipeline/api_tests.rs"))); - // The runtime's crate by its module tree, its tests left out. - let runtime = files(&crates.join("metal2vulkan-runtime")); - assert!(runtime.contains(Path::new("src/lib.rs"))); - assert!(!runtime.iter().any(|file| file.starts_with("src/tests"))); // The front end's crate by its module tree, its test-only modules left out, named through the // translator's manifest path (`../metal2vulkan-air`). let inputs = product_inputs(&root); diff --git a/crates/metal2vulkan-validation/src/c3.rs b/crates/metal2vulkan-validation/src/c3.rs index fdfd3748f..9063c5bd9 100644 --- a/crates/metal2vulkan-validation/src/c3.rs +++ b/crates/metal2vulkan-validation/src/c3.rs @@ -907,23 +907,14 @@ fn near_equivalent_bound(note: PrecisionNote) -> &'static str { } /// The deferred near-equivalent `row` ran, if it records one: in its comparison class, which its -/// executed modules' precision notes derive, or as a degradation its run announced whose kind is -/// the note's ([`CandidateObservation::announced_degradations`], `Degradation::precision_note`). A -/// rate-mapped pass the runtime draws records its map only so: the runtime makes the map and -/// announces `rasterization-rate-map`, and no executed module's notes name it. An announced kind -/// that is no deferred note's (a cost, or another precision note) notes nothing. +/// executed modules' precision notes derive. fn deferred_note(row: &CandidateObservation) -> Option { - let class = match &row.comparison { - ComparisonClass::Unbounded(notes) => Some(notes), - _ => None, + let ComparisonClass::Unbounded(notes) = &row.comparison else { + return None; }; - let announced = row - .announced_degradations() - .filter_map(|kind| kind.precision_note()) - .collect::>(); DEFERRED_NEAR_EQUIVALENTS .into_iter() - .find(|note| class.is_some_and(|notes| notes.contains(note)) || announced.contains(note)) + .find(|note| notes.contains(note)) } /// Why the product refuses one of `case`'s rasterization-rate maps (the render pass's, or a diff --git a/crates/metal2vulkan-validation/src/c3/tests.rs b/crates/metal2vulkan-validation/src/c3/tests.rs index 149fd3d28..13147168f 100644 --- a/crates/metal2vulkan-validation/src/c3/tests.rs +++ b/crates/metal2vulkan-validation/src/c3/tests.rs @@ -3577,81 +3577,6 @@ fn a_deferred_near_equivalent_stays_open_with_its_reason() { assert_eq!((row.verdict, row.reason.clone()), (Verdict::Reviewed, None)); } -/// A deferred near-equivalent the run announced as a degradation, which no executed module's notes -/// record (the runtime makes a rate-mapped pass's map and announces it), keeps the row open with -/// its reason, as a note its comparison class records does, even where the list holds a reading at -/// it; a cost, a note C3 judges word by word, or a code the vocabulary does not know leaves an -/// ordinary mismatch, which the list reviews. -#[test] -fn an_announced_deferred_near_equivalent_stays_open_with_its_reason() { - use crate::observation::RUNTIME_DEGRADES; - use metal2vulkan_runtime::Degradation; - let drawn = case(1, "drawn"); - let row = new_row(&drawn, Backend::Vulkan, LAVAPIPE, &DEVICE, &METAL); - assert_eq!( - (row.comparison.clone(), row.census.is_none()), - (ComparisonClass::Exact, true) - ); - let announcing = |member: &str, codes: &[&str]| { - let mut row = row.clone(); - row.environment[member] = serde_json::json!(codes); - row - }; - let judged = |row: CandidateObservation| { - let input = C3Input { - cases: vec![drawn.clone()], - metals: vec![metal(&drawn, &METAL)], - public_air: [drawn.air_sha256.clone()].into(), - vulkan: vec![row.clone()], - ..C3Input::default() - }; - let list = ReviewedList { - readings: vec![reading(&drawn, vec![reviewed(&row, &METAL)])], - old_mismatches: vec![], - reference_gaps: vec![], - answer_gaps: vec![], - }; - let report = report_of( - &input, - &list, - &C1List::default(), - &venues(), - &VenueKeys::default(), - ); - slot(&report, LAVAPIPE, Leg::Stated) - .rows - .iter() - .find(|judged| judged.case_id == drawn.case_id) - .map(|judged| (judged.verdict, judged.reason.clone())) - }; - let rate_map = Degradation::RasterizationRateMap.code(); - assert_eq!(rate_map, "metal2vulkan-degrade-rasterization-rate-map"); - let deferred = Some(( - Verdict::Mismatch, - Some(OpenReason::NearEquivalent( - PrecisionNote::RasterizationRateMap, - )), - )); - let cost = Degradation::ShadowedTexture.code(); - assert_eq!( - judged(announcing(RUNTIME_DEGRADES, &[cost, rate_map])), - deferred - ); - let ordinary = Some((Verdict::Reviewed, None)); - assert_eq!(judged(row.clone()), ordinary); - assert_eq!( - judged(announcing( - RUNTIME_DEGRADES, - &[ - cost, - Degradation::DeviceDenormals.code(), - "metal2vulkan-degrade-no-such-kind", - ], - )), - ordinary - ); -} - /// A run restricted to a profile the device cannot take is a current device-class refusal of the /// restricted slot (`not_supported{profile_exceeds_device}`, naming each member), judged by the /// rule a row is; C3 judges the venue's own slots, so it neither reads that slot's refusal as diff --git a/crates/metal2vulkan-validation/src/candidate.rs b/crates/metal2vulkan-validation/src/candidate.rs index 9c19414c2..082e02d47 100644 --- a/crates/metal2vulkan-validation/src/candidate.rs +++ b/crates/metal2vulkan-validation/src/candidate.rs @@ -141,7 +141,6 @@ pub fn requested_policy() -> DevicePolicy { /// this whole process (the engine device worker's setting). pub(crate) fn echo_validation_messages() { platform::echo_validation_messages(); - runtime_case::echo_messages(); } fn validate_backend_host(backend: Backend) -> Result<(), String> { @@ -159,26 +158,11 @@ fn validate_backend_host(backend: Backend) -> Result<(), String> { pub(crate) mod device_facts; pub mod engine; -pub mod runtime_case; -pub mod runtime_samples; pub(crate) mod unadvertised_stage; pub(crate) mod unsupported_set; #[cfg(any(target_os = "linux", target_os = "macos"))] mod platform; -pub(crate) use platform::{runtime_restriction, Restricting, RuntimeRestriction}; - -/// What the runtime path's second check of a profile restriction found on its device -/// (`RuntimeRestriction::check`): the description the executor's context translates for under the -/// profile, the members where the description the runtime read through the profiles layer differs -/// from it (the kept ones, which the layer reads from the device), and the environment's -/// `profiles_layer` record. -pub(crate) struct RestrictedDevice { - pub(crate) translated: metal2vulkan::device::DeviceDescription, - pub(crate) kept: Vec, - pub(crate) record: serde_json::Value, -} - #[cfg(test)] pub(crate) mod tests; @@ -289,47 +273,4 @@ mod platform { ) -> Result { Err("candidate execution is supported only on Linux and macOS".into()) } - - /// No restriction runs here ([`restrict_devices_to`] refuses one). - pub(crate) enum Restricting { - Takes(Box), - Refused(Box), - } - - /// No value: no restriction runs here. - pub(crate) enum RuntimeRestriction {} - - impl RuntimeRestriction { - pub(crate) fn stem(&self) -> &str { - match *self {} - } - - pub(crate) fn restrict( - &self, - _options: &mut metal2vulkan_runtime::DeviceOptions, - ) -> Result<(), String> { - match *self {} - } - - pub(crate) fn check( - &self, - _device: &metal2vulkan_runtime::Device, - ) -> Result { - match *self {} - } - - pub(crate) fn refused_on( - &self, - _executor: &str, - ) -> Result { - match *self {} - } - } - - pub(crate) fn runtime_restriction( - _device_type: DeviceType, - _executor: &str, - ) -> Result, String> { - Ok(None) - } } diff --git a/crates/metal2vulkan-validation/src/candidate/device_facts.rs b/crates/metal2vulkan-validation/src/candidate/device_facts.rs index 101101ed5..fb06c324d 100644 --- a/crates/metal2vulkan-validation/src/candidate/device_facts.rs +++ b/crates/metal2vulkan-validation/src/candidate/device_facts.rs @@ -1,7 +1,7 @@ //! What an engine row records of the Vulkan device that ran it: the device's identity and driver //! (`VkPhysicalDeviceProperties`, `VkPhysicalDeviceDriverProperties`), the tools active on it, and //! the facts the row's environment has always carried beside them. The executor's own context reads -//! its tools here, and the runtime path reads all of it through the runtime device's raw handles. +//! its tools here. use crate::coverage::ExecutionClass; use ash::vk; diff --git a/crates/metal2vulkan-validation/src/candidate/engine.rs b/crates/metal2vulkan-validation/src/candidate/engine.rs index b061d3daf..e1dd989dc 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine.rs @@ -73,7 +73,7 @@ use crate::observation::{ }; use crate::observation_contract::ComparisonClass; use crate::refusal::{Refusal, RefusalObservation}; -use crate::requirement::Executor; +use crate::requirement::{Executor, ToolingRequirement}; use crate::store::CorpusStore; use crate::worker::compile::{ compile_compute_request, compile_render_request, CompileWorker, NotCompiled, WorkerDevice, @@ -109,7 +109,6 @@ pub mod mesh; #[cfg(test)] mod public_cases; pub mod resources; -pub mod runtime_run; pub mod tables; #[cfg(test)] pub(crate) mod tests; @@ -124,7 +123,7 @@ use tables::{function_tables, table_buffers, FunctionTable, TableBuffers}; /// how it decides a match. A change no recorded row can observe (a case kind no earlier executor /// ran, or one it refused) needs no bump; its commit says why. The commit that bumps it says what /// changed; this comment keeps no history. -pub const ENGINE_EXECUTOR_ABI: &str = "vulkan-engine-v183"; +pub const ENGINE_EXECUTOR_ABI: &str = "vulkan-engine-v184"; /// One kernel case in the terms the binder takes: what this executor supports of an /// [`AuthoredCase`] (buffers, device buffer arrays, argument-buffer buffers and textures, command @@ -144,8 +143,7 @@ pub struct ComputeCase { pub buffers: BTreeMap>, /// Each bound buffer holding a rasterization-rate map's parameter data, by Metal buffer index: /// its bytes in [`ComputeCase::buffers`] are the product's data of the map, which the executor - /// binds; the runtime path makes the map with the runtime and copies its data into the buffer, - /// as the Metal oracle does with Metal's. + /// binds. pub rate_maps: BTreeMap, /// Initial bytes of each argument-buffer buffer, by `(owner Metal index, field offset)`: /// a buffer the owner's argument buffer points to (loaded pointers). The run writes its guest @@ -879,8 +877,7 @@ pub fn function_constants( /// slot ([`views_told_apart`]), so a uniform view's range starts at its bind offset in its plan /// (`SpecKey::RangeAtBindOffset`) on every device, as in the runtime's plan of the same binds: the /// runtime states its device's own alignment at the slots its pipeline reads through a uniform -/// view, and the plans of the two are the same, so the runtime path's artifact digest is the -/// executor's and the authored compile census's. +/// view, and the plans of the two are the same. pub const VIEW_BASE_ALIGNMENT: u32 = 256; /// `state` telling [`VIEW_BASE_ALIGNMENT`] apart at every buffer slot of each of its stages, and @@ -1223,9 +1220,8 @@ pub fn is_robustness_off_slot(environment_id: &str) -> bool { /// form and `profile`'s encodings) on a device that executes as `class`, or `None` for a case /// without targets: the run's out-of-bounds facts, before what its guards count /// (`TargetRun::escaped`, `TargetRun::past_end`). A target whose form the device leaves -/// uncontained under that encoding refuses the run, so it is decided before anything is submitted: -/// by the executor's own context before it executes, and by the runtime path before it commits -/// (`runtime_run`). +/// uncontained under that encoding refuses the run, so it is decided before anything is submitted, +/// before the executor's context executes. pub(crate) fn out_of_bounds_run( class: Option, profile: &DeviceProfile, @@ -1261,8 +1257,7 @@ pub(crate) fn out_of_bounds_run( /// [`out_of_bounds_run`] for a render case's draw: how `pipeline`'s module that runs the Metal /// vertex function (`graphics::vertex_module`) contains each of `case`'s targets, its attributes -/// fetched from `case`'s vertex buffers. The one decision the executor's own context and the -/// runtime path (`runtime_run`) take for a draw. +/// fetched from `case`'s vertex buffers. pub(crate) fn draw_out_of_bounds_run( class: Option, profile: &DeviceProfile, @@ -1291,9 +1286,8 @@ pub(crate) fn draw_out_of_bounds_run( /// Whether a draw that read `padding` index positions past where Metal's fetch stops reading its /// index buffer from a zero-padded copy of its indices contains them as `run`'s index buffer -/// target states: the padded copy, of at least one such position. The executor's context and the -/// runtime path (the draw's execution record) both hold the draw to it; a run without that target -/// agrees with any draw. +/// target states: the padded copy, of at least one such position. The executor's context holds +/// the draw to it; a run without that target agrees with any draw. pub(crate) fn index_padding_agrees( run: Option<&OutOfBoundsRun>, padding: Option, @@ -2008,17 +2002,8 @@ pub struct PreparedCase { /// The libraries the case's own function links ([`linked_modules`]). linked: Vec, /// The template of each pipeline token the case's executed commands may run, as the - /// executor's own context replays them ([`replay_templates`]), or why that context cannot: its - /// refusal of the case, which the runtime's replay does not share. - templates: Result, ExecutorError>, -} - -impl PreparedCase { - /// The templates the executor's own context replays, or its refusal of the case: a case the - /// runtime hands back to that context fails there. - fn templates(&self) -> Result<&BTreeMap, ExecutorError> { - self.templates.as_ref().map_err(Clone::clone) - } + /// executor's context replays them ([`replay_templates`]). + templates: BTreeMap, } /// A pipeline template an executed command may run: its checked case (by id in @@ -2072,10 +2057,10 @@ pub enum TemplateCase { /// family, so such a literal is no template here. A replayed compute template binds buffers and /// threadgroup memory only, and runs no stage input; a replayed render template is a /// rasterization-disabled vertex function (which the checker requires) that binds buffers only, -/// with no vertex input. Every other resource of its own, and an object or mesh template, whose -/// mesh draws only the runtime replays (`runtime_run::template_states`), is the refusal of the -/// executor's context, before any device: of the case itself where it runs there, and kept for a -/// run the runtime hands back where the runtime runs it (`PreparedCase::templates`). +/// with no vertex input. A template with any other resource of its own refuses the case, before +/// any device ([`ToolingRequirement::ReplayedTemplateResources`]), and so does an object or mesh +/// template, whose mesh draw the executor does not draw +/// ([`ToolingRequirement::MeshRenderPipeline`]). pub fn replay_templates( checked: &CheckedCase, ) -> Result, ExecutorError> { @@ -2123,10 +2108,9 @@ pub fn replay_templates( && mapped.imageblock.is_none() && mapped.stage_input.is_none(); if !replayable { - return Err(NotSupported::NotImplemented(format!( - "engine candidate: the replayed template {case_id} binds more than \ - buffers and threadgroup memory" - )) + return Err(NotSupported::Requirements( + [ToolingRequirement::ReplayedTemplateResources].into(), + ) .into()); } TemplateCase::Compute(Box::new(mapped)) @@ -2159,19 +2143,17 @@ pub fn replay_templates( && resources.objects.is_empty() && resources.command_buffers.is_empty(); if !replayable { - return Err(NotSupported::NotImplemented(format!( - "engine candidate: the replayed template {case_id} is not a \ - rasterization-disabled vertex function that binds buffers only" - )) + return Err(NotSupported::Requirements( + [ToolingRequirement::ReplayedTemplateResources].into(), + ) .into()); } TemplateCase::Render(Box::new(mapped)) } Stage::Object | Stage::Mesh => { - return Err(NotSupported::NotImplemented(format!( - "engine candidate: the replayed template {case_id} is an object or mesh \ - function, whose mesh draws only the runtime replays" - )) + return Err(NotSupported::Requirements( + [ToolingRequirement::MeshRenderPipeline].into(), + ) .into()) } }; @@ -2418,23 +2400,14 @@ pub fn prepare_case( )?)), }; let linked = linked_modules(&checked.primary.linked_functions)?; - let templates = replay_templates(&checked); - let prepared = PreparedCase { + let templates = replay_templates(&checked)?; + Ok(PreparedCase { device, checked, mapped, linked, templates, - }; - // The runtime replays every template through its own pipeline states, so a template the - // executor's context cannot replay refuses device-free only a case that runs on that context; a - // case the runtime runs meets the refusal only if the runtime hands it back. - if let (Err(refused), runtime_run::Route::Executor(_)) = - (&prepared.templates, runtime_run::route(&prepared)) - { - return Err(refused.clone()); - } - Ok(prepared) + }) } /// What one compile of [`case_compiles`] builds. @@ -2556,10 +2529,8 @@ pub struct CaseCompiles<'a> { /// device-free compile builds on this device: a render command buffer, whose host replay /// compiles each command's pipeline for the bind shape of the records the producer writes on /// the device, and whose draw replay (`platform::compute::draw_replay`) compiles its - /// template's variant for the bind state of the execution's encoder, as the runtime path's - /// record leaves both uncovered; and a compute one the host replay runs, where the product sets - /// no device replay up or the case registers no variant (a case the runtime runs whose - /// templates the executor's context does not replay registers none). + /// template's variant for the bind state of the execution's encoder; and a compute one the host + /// replay runs, where the product sets no device replay up or the case registers no variant. pub host_replayed: usize, } @@ -2592,14 +2563,7 @@ pub fn case_compiles<'a>( let mut host_replayed = 0; match &prepared.mapped { Mapped::Compute(compute) => { - // A case the runtime runs replays its templates through the runtime's own pipeline - // states (`prepare_case`), so the executor's context's refusal of them is not that - // run's: it registers no variant here, and each executed command buffer is uncovered. - let registered = match prepared.templates() { - Ok(templates) => replay_variants(compute, templates)?, - Err(_) if runtime_run::route(prepared) == runtime_run::Route::Runtime => Vec::new(), - Err(refused) => return Err(refused), - }; + let registered = replay_variants(compute, &prepared.templates)?; let shape = compute_shape(compute, addressed, ranges).map_err(ExecutorError::Failed)?; let (request, libraries) = compute_request(&library, linked, compute, &shape); compiles.push(CaseCompile { @@ -2698,8 +2662,6 @@ pub fn case_compiles<'a>( .filter(|(_, command)| executed(command)) .count(); } - // The pipeline the runtime compiles in the run itself (`runtime_run`), for its own - // stage's resources. Mapped::Mesh(mesh) => { let shape = mesh::mesh_shape(mesh, addressed, ranges)?; let companion = mesh @@ -2757,7 +2719,7 @@ pub(crate) fn run_on_device(input: &DeviceInput) -> DeviceOutcome { match prepare_on_device(input) { Ok((prepared, worker)) => { let clock = crate::budgets::CreationClock::start(); - let attempt = run_prepared(&prepared, input.backend, &worker); + let attempt = run_on_context(&prepared, input.backend, &worker); let timing = CaseTiming::of_one(clock.read()); DeviceOutcome { result: attempt.result.map(|run| DeviceRun { @@ -2838,54 +2800,12 @@ fn prepare_on_device(input: &DeviceInput) -> Result<(PreparedCase, CompileWorker Ok((prepared, CompileWorker::current()?)) } -/// Run one prepared case on its device by the path [`runtime_run::route`] gives it: through the -/// runtime ([`runtime_run::run`]), or on the executor's own context ([`run_on_context`]) while the -/// runtime path waits for prerequisites of the case's family, or when the runtime raised a typed -/// gap before it committed (the bridge). A row or refusal of the executor's context records why the -/// runtime did not run it. -fn run_prepared(prepared: &PreparedCase, backend: Backend, worker: &CompileWorker) -> RunAttempt { - let why = match runtime_run::route(prepared) { - runtime_run::Route::Runtime => match runtime_run::run(prepared, backend) { - runtime_run::RuntimeOutcome::Ran(attempt) => return *attempt, - runtime_run::RuntimeOutcome::Gap(gap) => runtime_run::ExecutorRun::Gap(gap), - }, - runtime_run::Route::Executor(prerequisites) => { - runtime_run::ExecutorRun::WaitsFor(prerequisites) - } - }; - let mut attempt = run_on_context(prepared, backend, worker); - let environments = attempt - .result - .as_mut() - .ok() - .map(|run| &mut run.environment) - .into_iter() - .chain( - attempt - .refused_on - .as_mut() - .map(|opened| &mut opened.environment), - ); - for environment in environments { - if let Some(object) = environment.as_object_mut() { - for (key, value) in runtime_run::executor_members(&why) { - object.insert(key.into(), value); - } - } - } - attempt -} - -/// Compile (in `worker`), bind, and execute one prepared case on the executor's own context: a +/// Compile (in `worker`), bind, and execute one prepared case on the executor's context: a /// kernel case as one dispatch, a vertex or fragment case as one draw. The run's row or refusal /// records what it compiled, by content ([`artifact::CaseArtifact`]). fn run_on_context(prepared: &PreparedCase, backend: Backend, worker: &CompileWorker) -> RunAttempt { let case = &prepared.checked.primary.case; - // A template this context cannot replay refuses the case here, before any device work. - let templates = match prepared.templates() { - Ok(templates) => templates, - Err(refused) => return RunAttempt::of(Err(refused)), - }; + let templates = &prepared.templates; // The worker assembles a row that retains no bitcode (a public fixture), and a companion. let library = RowSource::of_row(&prepared.checked.primary.source); let linked = &prepared.linked; @@ -2958,10 +2878,9 @@ fn run_on_context(prepared: &PreparedCase, backend: Backend, worker: &CompileWor backend, ) } - // Only the runtime path draws a mesh render pipeline; the executor's context runs a - // mesh case only when the runtime handed it back (the bridge). - Mapped::Mesh(_) => RunAttempt::of(Err(NotSupported::NotImplemented( - "engine candidate: the executor's own context draws no mesh render pipeline".into(), + // The checker's requirements refuse a mesh case before it maps (`prepare_case`). + Mapped::Mesh(_) => RunAttempt::of(Err(NotSupported::Requirements( + [ToolingRequirement::MeshRenderPipeline].into(), ) .into())), }; @@ -2978,8 +2897,7 @@ fn run_on_context(prepared: &PreparedCase, backend: Backend, worker: &CompileWor /// Record a compiled child in the run's artifact: a device-replay variant by its subject, with the /// preprocess module the device replay runs it under; a host replay's pipeline (for a record a /// producer wrote on the device) and a draw replay's variant (for the bind state of the execution's -/// encoder) as ones the census cannot compile, as the runtime path records every pipeline its -/// executed commands ran. +/// encoder) as ones the census cannot compile. fn record_child( artifact: &mut artifact::CaseArtifact, target: &WorkerDevice, @@ -3018,7 +2936,7 @@ fn compile_child( target: &WorkerDevice, (token, shape, command): (u64, &BindShape, &ChildCommand), ) -> Result { - let template = prepared.templates()?.get(&token).ok_or_else(|| { + let template = prepared.templates.get(&token).ok_or_else(|| { ExecutorError::Failed(format!( "an executed command's pipeline token {token} names no template" )) @@ -3108,7 +3026,7 @@ fn replay_variant_request<'a>( threads_per_group: [u32; 3], shape: &BindShape, ) -> Result, ExecutorError> { - let template = prepared.templates()?.get(&token).ok_or_else(|| { + let template = prepared.templates.get(&token).ok_or_else(|| { ExecutorError::Failed(format!( "an executed command's pipeline token {token} names no template" )) diff --git a/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs b/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs index 123c20efd..db905b3f9 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs @@ -201,10 +201,9 @@ fn the_runtime_sources_are_the_committed_ones() { ("metal2vulkan/src/spirv/verify/mod.rs", spirv), ("metal2vulkan/src/spv.rs", "the SPIR-V grammar's opcodes and enumerants with their values, generated from Khronos's grammar: a value is fixed by the specification, and regenerating only adds or drops names, which no run can observe"), ]); - // The resolver the classifier's key test holds its inputs closed with, across the product, - // the AIR front end's crate, which the product imports as `crate::air`, and the runtime's - // crate, whose inputs reach the product through `metal2vulkan::`, each by its directory in the - // workspace's crates/. + // The resolver the classifier's key test holds its inputs closed with, across the product and + // the AIR front end's crate, which the product imports as `crate::air`, each by its directory + // in the workspace's crates/. let members = [ crate::triage::classifier_inputs::Member { name: "metal2vulkan_air", @@ -214,10 +213,6 @@ fn the_runtime_sources_are_the_committed_ones() { name: "metal2vulkan", dir: "metal2vulkan", }, - crate::triage::classifier_inputs::Member { - name: "metal2vulkan_runtime", - dir: "metal2vulkan-runtime", - }, ]; let dependencies = crate::triage::classifier_inputs::dependencies(&product, &members, &inputs).unwrap(); @@ -231,10 +226,12 @@ fn the_runtime_sources_are_the_committed_ones() { unlisted.is_empty(), "the runtime inputs reach files that are neither inputs nor listed: {unlisted:#?}" ); - for file in not_runtime.keys() { - assert!( - dependencies.contains_key(*file), - "{file} is listed but no runtime input reaches it" - ); - } + let unreached = not_runtime + .keys() + .filter(|file| !dependencies.contains_key(**file)) + .collect::>(); + assert!( + unreached.is_empty(), + "listed, but no runtime input reaches them: {unreached:#?}" + ); } diff --git a/crates/metal2vulkan-validation/src/candidate/engine/graphics/tests.rs b/crates/metal2vulkan-validation/src/candidate/engine/graphics/tests.rs index 3540dcedd..5c18d6eab 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/graphics/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/graphics/tests.rs @@ -2753,98 +2753,6 @@ fn a_render_case_of_one_sample_draws_as_it_always_did() { assert!(text.contains("\"raster_sample_count\":4"), "{text}"); } -/// The runtime path's generated initializer and resolver of each committed public fragment -/// imageblock case (`runtime_case::imageblock::helpers_text`, from the checked reflection's master -/// and the case's cells), each drawn as the oracle draws its own helpers (the case's vertex -/// function, no vertex buffer, the case's attachments, three vertices), compile on lavapipe and -/// moltenvk-m3 to the case pipeline's fragment imageblock: its master's fingerprint, its data size -/// and its alignment. So the runtime draws them in one pass with the case, and their imageblock -/// sample lengths are the case pipeline's, as the oracle requires of its helpers. -#[test] -fn the_imageblock_helpers_view_each_public_cases_master() { - use crate::candidate::runtime_case::imageblock::{ - helpers_text, INITIALIZE_ENTRY, RESOLVE_ENTRY, - }; - let root = metal2vulkan_devtools::validation_dir().join("corpus"); - let sources = public_sources().unwrap(); - let mut compared = 0; - for case in CorpusStore::new(&root).read_all_cases().unwrap() { - if case.fragment_imageblock.is_none() { - continue; - } - let Some(row) = sources - .iter() - .find(|row| row.air_sha256 == case.air_sha256 && row.entry == case.entry) - else { - continue; - }; - let scratch = crate::ScratchDir::new("public-imageblock-helpers").unwrap(); - let ll = scratch.path().join("case.ll"); - std::fs::write(&ll, &row.air_ll).unwrap(); - let Some(bitcode) = assembled(&ll) else { - return; - }; - let name = &case.name; - let checked = crate::check::check_case_against_source(&root, case.clone(), row) - .unwrap_or_else(|errors| panic!("{name}: {errors:?}")); - let master = checked.primary.reflection.fragment_imageblock.as_ref(); - let render = render_case( - &case, - &checked.primary.interface, - &row.air_ll, - checked.primary.companion.as_ref(), - master, - ) - .unwrap_or_else(|error| panic!("{name}: {error:?}")); - let cells = render.imageblock.as_ref().expect("the case's cells"); - let text = helpers_text(master.expect("the reflected master"), cells) - .unwrap_or_else(|error| panic!("{name}: {error}")); - let helpers = crate::check::loop_free::assemble(&text) - .unwrap_or_else(|error| panic!("{name}: {error}\n{text}")); - let companion = render.companion.as_ref().unwrap().opaque_bitcode().unwrap(); - let imageblock = |pipeline: &metal2vulkan::pipeline::RenderPipeline| { - pipeline - .graphics - .fragment_imageblock - .map(|state| (state.master, state.data_size, state.alignment)) - }; - for stem in ["lavapipe", "moltenvk-m3"] { - let device = device(stem); - let libraries = RenderLibraries { - vertex: &companion, - fragment: Some(&bitcode), - }; - let shape = render_shape(&render, true, BufferRanges::default()).unwrap(); - let own = compile_in_process(&device, &render, libraries, &shape) - .unwrap_or_else(|error| panic!("{name} on {stem}: {error}")); - let expected = imageblock(&own); - assert!(expected.is_some(), "{name} on {stem}: no imageblock state"); - for entry in [INITIALIZE_ENTRY, RESOLVE_ENTRY] { - let mut helper = two_stage_case( - &render.vertex.entry, - entry, - Vec::new(), - render.color_targets.clone(), - 3, - ); - helper.depth_stencil = render.depth_stencil.clone(); - let libraries = RenderLibraries { - vertex: &companion, - fragment: Some(&helpers), - }; - let shape = render_shape(&helper, true, BufferRanges::default()).unwrap(); - let pipeline = compile_in_process(&device, &helper, libraries, &shape) - .unwrap_or_else(|error| panic!("{name} {entry} on {stem}: {error}")); - assert_eq!(imageblock(&pipeline), expected, "{name} {entry} on {stem}"); - } - compared += 1; - } - } - // As `public_fragment_imageblock_cases_plan_their_storage_image` plans them: twenty cases, - // each on both profiles. - assert_eq!(compared, 40); -} - /// A vertex buffer of a dynamic layout: its layout's stride is `MTLBufferLayoutStrideDynamic`, so /// the fetch reads the stride the buffer is bound with; a fixed layout's is its stride. #[test] diff --git a/crates/metal2vulkan-validation/src/candidate/engine/guards.rs b/crates/metal2vulkan-validation/src/candidate/engine/guards.rs index 4f0b06cda..c541de1fa 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/guards.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/guards.rs @@ -1,8 +1,7 @@ //! The guards a candidate keeps around a case's out-of-bounds targets: where each guarded target //! ([`out_of_bounds::guarded`]) lies, how far its guard reaches, what a run changed there, and how -//! those counts join the run's out-of-bounds facts. One copy, which the executor's own context -//! (`platform`, each target in an allocation of its own) and the runtime path (`runtime_case`, each -//! target in a heap of its own) share. +//! those counts join the run's out-of-bounds facts, for the executor's own context (`platform`, +//! each target in an allocation of its own). use super::ComputeCase; use crate::case::out_of_bounds::{ContainmentForm, OutOfBoundsResource, OutOfBoundsTarget}; diff --git a/crates/metal2vulkan-validation/src/candidate/engine/mesh.rs b/crates/metal2vulkan-validation/src/candidate/engine/mesh.rs index 4b7ba3faa..fc01f3830 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/mesh.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/mesh.rs @@ -1,6 +1,5 @@ -//! Mesh cases of the engine candidate: an object or mesh case's draw (`case::MeshDraw`) mapped for -//! the runtime's mesh path (`runtime_case::encoded_mesh`), as the Metal oracle draws it -//! (`metal::platform`). +//! Mesh cases of the engine candidate: an object or mesh case's draw (`case::MeshDraw`) mapped as +//! the Metal oracle draws it (`metal::platform`). //! //! The case's own function binds the case's resources, mapped as a render case's own stage's are //! ([`graphics::stage_resources`]); each partner its draw names is a function of the case's own diff --git a/crates/metal2vulkan-validation/src/candidate/engine/runtime_run.rs b/crates/metal2vulkan-validation/src/candidate/engine/runtime_run.rs deleted file mode 100644 index 8d71c5b9e..000000000 --- a/crates/metal2vulkan-validation/src/candidate/engine/runtime_run.rs +++ /dev/null @@ -1,1419 +0,0 @@ -//! The engine executor's runtime path: a case of a family the runtime runs goes through -//! `metal2vulkan_runtime` as a Metal program would run it, by the case runner the runtime lane -//! shares ([`crate::candidate::runtime_case`]). -//! -//! [`route`] decides by the case's own inputs, device-free, which path runs it: the runtime, or the -//! executor's own context while the runtime path waits for the [`Prerequisite`]s later steps add. A -//! run the runtime takes opens a device of its own behind the hang tripwire -//! (`runtime_case::open_device`) among the physical devices of the run's device type, the -//! validation layer reporting to a sink that fails the row (with the executor's settings: every -//! occurrence of a message reported, synchronization validation on), a shader cache directory of -//! the run's own, empty when made, so no warm cache stands in for a translation, the robustness -//! features withheld in the robustness-off leg, and this process's policy. A run this process -//! restricts to a committed profile (`--profiles-layer`) opens it as the executor's restricted -//! context opens its own: a device without the profile's capabilities refused, typed, before it -//! opens; the profiles layer below the validation layer with the context's settings, the instance -//! at the profile's version (`DeviceOptions::instance_api_version`); the context's second check -//! made on the opened device through its raw handles, and the row stored in the profile's slot. -//! Where the runtime would compile for the device's own kept members rather than the profile's, the -//! case goes to the executor's context (`translation`, the bridge), but for a patch draw the -//! profile emulates, whose emulation only the runtime runs: the runtime runs it on those members, -//! and the row records them (`kept_members`). A kernel case's AIR becomes a -//! library, its entry a function, the function with the functions it links (each linked module a -//! library of its own) a pipeline state, which makes the case's visible-function tables (each entry -//! the handle the state gives the function it holds, `runtime_case::visible_function_tables`), and -//! its resources, its tables, one compute encoder, and one dispatch a command buffer, committed -//! once what the dispatch executed has decided how it contains the case's out-of-bounds targets -//! (`kernel_out_of_bounds`, the executor's own decision; a target the device leaves uncontained -//! refuses the case uncommitted, the refusal recording what the dispatch compiled; a buffer target -//! lies in a heap of its own between guards, `runtime_case::guarded_buffer`), and each indirect -//! command buffer the case executes, in key order, a command buffer of its own committed after it -//! on its queue (`runtime_case::encoded_execution`, the case's command buffers made as the Metal -//! oracle makes them, a command buffer of render commands included, its host commands encoded, its -//! templates' states, compute or render, made with `support_indirect_command_buffers`, -//! `template_states`); a tile kernel's function a tile pipeline state, which makes its tables for -//! the tile stage (`runtime_case::tile_tables`), and its resources, its argument buffers, its -//! tables, its pass's attachments, one render encoder of the pass and one tile dispatch a command -//! buffer, committed (`runtime_case::encoded_tile`); a render case draws once as the Metal oracle -//! draws it (`runtime_case::encoded_render`: its functions and its generated companion's, the -//! case's own linking its functions, a render pipeline state of the oracle's descriptor, which -//! makes each stage's tables for that stage, its attachments, state, resources, argument buffers -//! (with the pipeline states they hold, each its template's, `template_states`) and tables, and one -//! draw), committed once what the draw executed has decided how it contains the case's vertex and -//! index buffer targets as the executor decides it (`draw_out_of_bounds`; each target in a heap of -//! its own between guards, and an index buffer target's draw holding its index positions past the -//! buffer to that containment, `engine::index_padding_agrees`). The wait for the command buffer -//! is bounded under the hang protocol (`gpu::wait::runtime`), the status is its execution report, -//! and the output is read back after it completed. The runtime compiles in this process, the device -//! worker (the compile boundary, for these runs, is the device worker's, with the runtime's own -//! compile budget). -//! -//! What the row records comes from what the runtime executed (its execution record): the census -//! of the compiled pipeline's modules, the artifact digest of the pipeline planned for the bind -//! shape it ran with the bytes of the tables it bound, the SPIR-V hash (a render pipeline's stages' -//! words in order, as the executor hashes them), the pipeline-creation ceiling of each `VkPipeline` -//! the dispatch or draw recorded, and its out-of-bounds facts, with what the run changed around -//! each target it placed between guards (`guards::with_escaped`, the heap's cause recorded where -//! one explains an escape or a read past a target). The device's identity, driver, and active tools -//! are read through the device's raw handles (`candidate::device_facts`). -//! -//! The bridge (temporary): a typed runtime gap (`Error::NotImplemented`) raised before the command -//! buffer commits (the device's creation's among them), so nothing ran, sends the case to the -//! executor's own context, and the row records the gap. So do two refusals that are not the case's -//! own, each keyed on the error's origin and type: a refusal of a mechanism of the runtime's own -//! that the device's driver runs wrong (`Needs::RuntimeDriverDefect`; the gap `: driver -//! defect ()`), and the runtime's refusal of a helper's pipeline, the runner's -//! own work around the case's pass (`CaseError::Helper`: a sample fill's, a sample readback's; the -//! gap `: helper refused `). Both are the runtime path's limitations, not the -//! device's lack: the executor's context does that work its own way. - -use super::artifact::CaseArtifact; -use super::artifact::Planned; -use super::graphics::{self, RenderCase}; -use super::guards::{with_escaped, Placement}; -use super::tables::TableBuffers; -use super::RefusedOn; -use super::{ - bind_refusal, companion_source, compute_case, draw_out_of_bounds_run, engine_fingerprint, - index_padding_agrees, linked_modules, out_of_bounds_run, product_refusal, report_verdict, - CompileSubject, ComputeCase, ComputeRun, Mapped, PreparedCase, RunAttempt, -}; -use crate::air_library::AirLibrary; -use crate::candidate::device_facts::{DeviceFacts, RECORDED_LAYERS}; -use crate::candidate::runtime_case::{ - argument_texture_usage, compute_descriptor, encoded_case, encoded_execution, encoded_mesh, - encoded_render, encoded_tile, executor_layer_settings, linked_functions, mesh_pipeline_state, - open_device, render_pipeline_descriptor, texture_usage, tile_descriptor, tile_tables, - validated_options, visible_function_tables, CaseError, MeshInputs, Messages, RenderInputs, - ScratchCache, TemplateState, -}; -use crate::candidate::{runtime_restriction, RestrictedDevice, Restricting, RuntimeRestriction}; -use crate::case::out_of_bounds::ContainmentForm; -use crate::case::{AuthoredCase, Stage}; -use crate::check::admission::ExecutorError; -use crate::companion::Spelling; -use crate::coverage::{ExecutedCensus, Leg, ModuleCensus, ROBUSTNESS_FEATURES}; -use crate::engine::RowSource; -use crate::executor_contract::out_of_bounds::{self, OutOfBoundsRun}; -use crate::gpu::wait::{with_submission_label, SubmissionBackend, SubmissionLabel}; -use crate::hash::sha256_bytes; -use crate::observation::{Backend, TRANSLATOR_FINGERPRINT}; -use metal2vulkan::device::VkFeature; -use metal2vulkan::error::{Needs, Unsupported}; -use metal2vulkan::pipeline::{Stage as ShaderStage, StageModule}; -use metal2vulkan_runtime::{ - Buffer, CommandBuffer, Device, Error, ExecutedPipeline, Execution, Function, PipelineOptions, -}; -use std::borrow::Cow; -use std::collections::{BTreeMap, BTreeSet}; - -/// What a case needs that the runtime path does not run yet: the steps that add a case's -/// prerequisites decide when its family moves. Until then the executor's own context runs the case, -/// and its row records them (`runtime_waits_for`). -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub enum Prerequisite { - /// A layered pass's multisampled color targets, which the render runner does not make: - /// step 6's multisample arrays. - LayeredMultisampledTargets, - /// Acceleration structures and intersection function tables: they stay on the executor in - /// this phase. - RayTracing, - /// A tile dispatch's command buffers and the pipeline states its argument buffers hold: the - /// tile runner (`runtime_case::encoded_tile`) makes none. A kernel's and a draw's run on the - /// indirect render commands, executed in a render encoder. - IndirectRenderCommands, - /// A draw's out-of-bounds target the runtime path does not place between guards yet: a stage - /// buffer's, or a tile dispatch's out-of-bounds target. Vertex and index buffer targets run on - /// the runtime, and so do a patch draw's control point and patch input buffers, - /// vertex buffers its post-tessellation vertex function fetches. - DrawOutOfBoundsTargets, -} - -impl Prerequisite { - /// The name a row records. - pub fn name(self) -> &'static str { - match self { - Prerequisite::LayeredMultisampledTargets => "layered-multisampled-targets", - Prerequisite::RayTracing => "ray-tracing", - Prerequisite::IndirectRenderCommands => "indirect-render-commands", - Prerequisite::DrawOutOfBoundsTargets => "draw-out-of-bounds-targets", - } - } -} - -/// Which path runs a prepared case. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Route { - /// The runtime ([`run`]). - Runtime, - /// The executor's own context, while the runtime path waits for these prerequisites (one or - /// more). - Executor(BTreeSet), -} - -/// The path that runs `prepared`: the runtime, unless the case needs a [`Prerequisite`]: a kernel -/// case's own inputs ([`kernel_prerequisites`]) or a render case's ([`render_prerequisites`]). -/// The functions a case links run on the runtime too (its pipeline state's descriptor links -/// them), and so do its compute commands and the pipeline states its argument buffers hold, a -/// render template's included (their templates' states made with -/// `support_indirect_command_buffers`, `template_states`). -pub fn route(prepared: &PreparedCase) -> Route { - let authored = &prepared.checked.primary.case; - let needs = match &prepared.mapped { - Mapped::Compute(compute) => kernel_prerequisites(compute), - Mapped::Render(render) => render_prerequisites(authored, render), - // Only the runtime draws a mesh render pipeline (`runtime_case::encoded_mesh`). - Mapped::Mesh(_) => BTreeSet::new(), - }; - if needs.is_empty() { - Route::Runtime - } else { - Route::Executor(needs) - } -} - -/// The prerequisites whose condition holds. -fn needed(conditions: [(bool, Prerequisite); N]) -> BTreeSet { - conditions - .into_iter() - .filter_map(|(needed, prerequisite)| needed.then_some(prerequisite)) - .collect() -} - -/// The [`Prerequisite`]s the inputs of a kernel case, mapped as `compute`, need: none for a case -/// of the runtime's families. -pub fn kernel_prerequisites(compute: &ComputeCase) -> BTreeSet { - needed([ - ( - !compute.acceleration_structures.is_empty(), - Prerequisite::RayTracing, - ), - // A tile kernel dispatches on a render encoder (`runtime_case::encoded_tile`), which - // makes no command buffer or pipeline state. - ( - compute.tile.is_some() - && (!compute.command_buffers.is_empty() || !compute.objects.is_empty()), - Prerequisite::IndirectRenderCommands, - ), - ( - compute.tile.is_some() && !compute.out_of_bounds.is_empty(), - Prerequisite::DrawOutOfBoundsTargets, - ), - ]) -} - -/// The [`Prerequisite`]s the inputs of render case `case`, mapped as `render`, need: none for a -/// case the render runner draws (`runtime_case::encoded_render`): one draw of primitives, direct -/// or indexed, or of a tessellation pipeline's patches with their factor buffer, of a pipeline its -/// functions and their linked functions make, with its attachments, vertex buffers (a vertex -/// input's, a control point's or a patch input's target between guards), each stage's buffers, -/// textures (multisampled and sparse ones included), samplers, argument buffers of buffers, -/// textures, samplers, pipeline states and command buffers (the commands each executes run -/// after the draw), and visible-function tables, a fragment case's explicit imageblock (between the -/// oracle's helpers' draws), and a rasterization-rate map, the pass's or a buffer's. -pub fn render_prerequisites(case: &AuthoredCase, render: &RenderCase) -> BTreeSet { - needed([ - ( - !case.acceleration_structures.is_empty() - || !case.intersection_function_tables.is_empty() - || !case.argument_buffer_intersection_function_tables.is_empty(), - Prerequisite::RayTracing, - ), - ( - render.out_of_bounds.iter().any(|target| { - !matches!( - target.form, - ContainmentForm::VertexInput - | ContainmentForm::IndexBuffer - | ContainmentForm::ControlPoint - ) - }), - Prerequisite::DrawOutOfBoundsTargets, - ), - ( - render.render_target_array_length > 0 - && render - .color_targets - .values() - .any(|target| target.samples != 1), - Prerequisite::LayeredMultisampledTargets, - ), - ]) -} - -/// What the runtime path came to: an attempt, or a typed runtime gap (or a refusal of a runtime -/// mechanism the driver runs wrong, or of a helper's pipeline) raised before anything was -/// committed, which sends the case to the executor (the bridge). -pub enum RuntimeOutcome { - Ran(Box), - Gap(String), -} - -impl RuntimeOutcome { - /// The attempt `result` came to, with no device a refusal names. - fn of(result: Result) -> RuntimeOutcome { - RuntimeOutcome::Ran(Box::new(RunAttempt::of(result))) - } - - /// The failed attempt `message` describes. - fn failed(message: String) -> RuntimeOutcome { - RuntimeOutcome::of(Err(ExecutorError::Failed(message))) - } -} - -/// Why a run on the runtime's device produced no row. -enum Stop { - /// A typed runtime gap before the command buffer committed. - Gap(String), - /// A typed refusal after the dispatch or draw took its pipeline, before anything was - /// committed. - Refused(Box), - /// The run's error. - Error(ExecutorError), -} - -/// A typed refusal after the dispatch or draw took its pipeline, before anything was committed (a -/// target the device leaves uncontained), with what it had compiled, which the refusal records as -/// the executor's does. -struct Refused { - error: ExecutorError, - artifact: CaseArtifact, -} - -impl From for Stop { - fn from(error: ExecutorError) -> Stop { - Stop::Error(error) - } -} - -impl From<&str> for Stop { - fn from(error: &str) -> Stop { - Stop::Error(ExecutorError::Failed(error.into())) - } -} - -impl From for Stop { - fn from(error: String) -> Stop { - Stop::Error(ExecutorError::Failed(error)) - } -} - -/// A runtime call's refusal as the executor reports it. Before the command buffer committed, a -/// typed runtime gap, a refusal of a runtime mechanism the driver runs wrong -/// (`Needs::RuntimeDriverDefect`), and a refusal of a helper's pipeline ([`CaseError::Helper`]) -/// are the bridge's; a compile or device refusal is the product's -/// ([`product_refusal`]), the binder's refusal of the bind state is [`bind_refusal`]'s, and -/// anything else, or a literal the case runner cannot run, fails the run. -fn stop(error: CaseError, committed: bool) -> Stop { - match error { - CaseError::Runtime { call, error } => match *error { - Error::NotImplemented(gap) if !committed => Stop::Gap(format!("{call}: {gap:?}")), - Error::Unsupported(Unsupported { - feature, - needs: Needs::RuntimeDriverDefect(defect), - .. - }) if !committed => { - Stop::Gap(format!("{call}: driver defect {defect:?} ({feature:?})")) - } - Error::Compile(error) => Stop::Error(product_refusal(&error)), - Error::Unsupported(unsupported) => Stop::Error(product_refusal( - &metal2vulkan::error::Error::Unsupported(unsupported), - )), - Error::Bind(error) => Stop::Error(bind_refusal(&error)), - other => Stop::Error(ExecutorError::Failed(format!( - "the runtime's {call}: {other}" - ))), - }, - CaseError::Helper { call, error } if !committed => match *error { - Error::Unsupported(unsupported) - | Error::Compile(metal2vulkan::error::Error::Unsupported(unsupported)) => { - Stop::Gap(format!("{call}: helper refused {unsupported}")) - } - other => stop( - CaseError::Runtime { - call, - error: Box::new(other), - }, - committed, - ), - }, - CaseError::Helper { call, error } => stop(CaseError::Runtime { call, error }, committed), - CaseError::Case(why) => { - Stop::Error(ExecutorError::Failed(format!("the runtime path: {why}"))) - } - } -} - -/// What a completed run read: the output, the execution report's verdict, and the execution -/// record, with the device's facts. Holds no runtime object. -struct Ran { - output: Vec, - status: metal2vulkan::bind::StatusReport, - executions: Vec, - /// The bytes of the visible-function tables the dispatch bound, as the artifact records them - /// (`runtime_case::CaseTables::words`); none for a draw. - tables: TableBuffers, - /// How the dispatch or draw contained the case's out-of-bounds targets - /// ([`kernel_out_of_bounds`], [`draw_out_of_bounds`]), with what the run changed around them; - /// `None` for a case without targets, and for a tile dispatch (whose targets wait, - /// [`Prerequisite::DrawOutOfBoundsTargets`]). - out_of_bounds: Option, - /// What the commands of the case's executed indirect command buffers ran - /// (`runtime_case::encoded_execution`), in execution order: none for a case that executes - /// none. - children: Vec, -} - -/// Run `prepared`, a case [`route`] gives the runtime, on a runtime device of its device type, in -/// this process's leg and policy: the attempt, or the bridge's gap. A typed refusal after the -/// device opened names that device ([`RunAttempt::refused_on`]). -pub fn run(prepared: &PreparedCase, backend: Backend) -> RuntimeOutcome { - let leg = crate::candidate::requested_leg(); - // A run this process restricts to a committed profile (`--profiles-layer`) opens the runtime's - // device under the profiles layer as the executor's context opens its own: a device that lacks - // capabilities the profile states is refused, typed, before any device opens. - let executor = Kind::of(&prepared.mapped).executor(); - let restriction = match runtime_restriction(prepared.device, executor) { - Ok(None) => None, - Ok(Some(Restricting::Takes(restriction))) => Some(restriction), - Ok(Some(Restricting::Refused(mut attempt))) => { - let environment = attempt - .refused_on - .as_mut() - .and_then(|opened| opened.environment.as_object_mut()); - if let Some(object) = environment { - object.insert("executed_by".into(), serde_json::json!("runtime")); - } - return RuntimeOutcome::Ran(attempt); - } - Err(error) => return RuntimeOutcome::failed(format!("the profile restriction: {error}")), - }; - let messages = Messages::default(); - let cache = match ScratchCache::new() { - Ok(cache) => cache, - Err(error) => { - return RuntimeOutcome::failed(format!("the runtime's shader cache directory: {error}")) - } - }; - let mut options = validated_options(&messages, cache.path()); - options.layer_settings = executor_layer_settings(); - options.policy = crate::candidate::requested_policy(); - // A run without generated commands (`--without-generated-commands`) opens the runtime's device - // without `VK_EXT_device_generated_commands`, as the executor's context opens its own. - options.withhold_generated_commands = !crate::candidate::requested_generated_commands(); - if leg == Leg::RobustnessOff { - options.withheld_features = ROBUSTNESS_FEATURES.into_iter().collect(); - } - if let Some(restriction) = &restriction { - if let Err(error) = restriction.restrict(&mut options) { - return RuntimeOutcome::failed(format!("the profile restriction: {error}")); - } - } - let device = match open_device(prepared.device, options) { - Ok(device) => device, - Err(error) => { - let failed = format!( - "the runtime opened no {} device: {error}", - prepared.device.as_str() - ); - // A typed runtime gap at the device's creation ran nothing: the bridge's, once the - // sink holds no message. A typed refusal of the device itself (one below Vulkan's - // timeline-semaphore minimum, say) is the device's lack: under a restriction it is - // recorded with the device as it is and the restriction, as a refusal of the - // restriction is; unrestricted, it names no device. - return match (stop(error, false), messages_check(&messages)) { - (Stop::Gap(gap), Ok(())) => RuntimeOutcome::Gap(gap), - (_, Err(messages)) => RuntimeOutcome::failed(format!("{messages} ({failed})")), - (Stop::Error(error @ ExecutorError::NotSupported(_)), Ok(())) => { - match restriction.as_deref().map(|r| r.refused_on(executor)) { - Some(Err(why)) => RuntimeOutcome::failed(format!("{failed}, and {why}")), - refused_on => { - let mut refused_on = refused_on.and_then(Result::ok); - let environment = refused_on - .as_mut() - .and_then(|opened| opened.environment.as_object_mut()); - if let Some(object) = environment { - object.insert("executed_by".into(), serde_json::json!("runtime")); - } - RuntimeOutcome::Ran(Box::new(RunAttempt { - result: Err(error), - refused_on, - })) - } - } - } - (Stop::Refused(_) | Stop::Error(_), Ok(())) => RuntimeOutcome::failed(failed), - }; - } - }; - let opened = Opened::of(&device, leg, &prepared.mapped, restriction.as_deref()); - let ran = match &opened { - Ok(Opened { - untranslated: Some(gap), - .. - }) => Err(Stop::Gap(gap.clone())), - Ok(opened) => run_on(&device, opened, prepared, backend), - Err(error) => Err(Stop::Error(ExecutorError::Failed(error.clone()))), - }; - // Every object of the run is destroyed with the device, whose instance reports its - // destruction to the sink too; then the sink has no other holder. The teardown may run after - // this last handle goes, on the runtime's thread that lets go of the device's last share - // (`messages_check`). - drop(device); - let checked = messages_check(&messages); - let degrades = degrades(&messages); - let opened = match opened { - Ok(opened) => opened, - Err(error) => return RuntimeOutcome::failed(error), - }; - let ran = match (ran, checked) { - (Err(Stop::Gap(gap)), Ok(())) => return RuntimeOutcome::Gap(gap), - (ran, Err(messages)) => { - let also = match &ran { - Ok(_) => String::new(), - Err(Stop::Gap(gap)) => format!(" (the runtime also raised the gap {gap})"), - Err(Stop::Refused(refused)) => format!(" (the run also failed: {})", refused.error), - Err(Stop::Error(error)) => format!(" (the run also failed: {error})"), - }; - return RuntimeOutcome::failed(format!("{messages}{also}")); - } - (Ok(ran), Ok(())) => Ok(ran), - (Err(Stop::Refused(refused)), Ok(())) => Err((refused.error, refused.artifact)), - (Err(Stop::Error(error)), Ok(())) => Err((error, CaseArtifact::default())), - }; - match ran { - Ok(ran) => RuntimeOutcome::of(opened.row(ran, degrades)), - Err((error @ ExecutorError::NotSupported(_), artifact)) => { - RuntimeOutcome::Ran(Box::new(RunAttempt { - result: Err(error), - refused_on: Some(opened.refused_on(&artifact)), - })) - } - Err((error, _)) => RuntimeOutcome::of(Err(error)), - } -} - -/// The codes of the degrade notices the run's device delivered to `messages`: each kind the runtime -/// announced, once, for this case on this device, in code order. -fn degrades(messages: &Messages) -> Vec<&'static str> { - let codes: BTreeSet<&'static str> = messages - .take_notices() - .iter() - .filter_map(|message| message.degradation.as_ref()) - .map(|notice| notice.degradation.code()) - .collect(); - codes.into_iter().collect() -} - -/// The failure of a run whose validation layer reported a message, or whose device's teardown -/// did not end within the wait bound after its last handle dropped (its messages may be -/// incomplete). The teardown may end on another of the runtime's threads a little after the last -/// handle goes: one that held the device's last share as the handle dropped (a pipeline making -/// still running) runs it once it lets go, as the runtime's teardown lane waits for -/// (`runtime_lane::teardown_holders`). -fn messages_check(messages: &Messages) -> Result<(), String> { - if !messages.unshared_within(crate::gpu::wait::wait_timeout()) { - return Err(format!( - "the runtime's device was not torn down within {:?} of its last handle's drop; its \ - validation messages are incomplete, so the run is not evidence", - crate::gpu::wait::wait_timeout() - )); - } - let reported = messages.take(); - if reported.is_empty() { - return Ok(()); - } - Err(format!( - "VK_LAYER_KHRONOS_validation reported {} message(s); the run is not evidence: {}", - reported.len(), - reported - .iter() - .map(|message| format!("{} ({}): {}", message.id_name, message.id, message.text)) - .collect::>() - .join(" | ") - )) -} - -/// Which of the runtime's paths runs a case: a kernel's dispatch or a render case's draw. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Kind { - Compute, - Render, -} - -impl Kind { - /// The path of a case mapped as `mapped`. - fn of(mapped: &Mapped) -> Kind { - match mapped { - Mapped::Compute(_) => Kind::Compute, - // A mesh draw is a render encoder's draw of a render pipeline state. - Mapped::Render(_) | Mapped::Mesh(_) => Kind::Render, - } - } - - /// The executor a row of this path names. - fn executor(self) -> &'static str { - match self { - Kind::Compute => "engine-runtime-compute", - Kind::Render => "engine-runtime-render", - } - } -} - -/// What a row or refusal records of the runtime's opened device: its facts, its environment, and -/// what it compiles for. -struct Opened { - facts: DeviceFacts, - kind: Kind, - environment: serde_json::Value, - translator_fingerprint: String, - profile: metal2vulkan::device::DeviceProfile, - compile: metal2vulkan::device::Device, - leg: Leg, - /// The committed profile the device is restricted to, which the census names. - restricted_to: Option, - /// Under a restriction, why the device's compile device does not translate for the profile - /// as the executor's context does ([`translation`]): the bridge's gap. - untranslated: Option, - /// The bound the case's own pipeline's creation is held to: a kernel case's - /// (`ComputeCase::creation_bound`), the shared ceiling for a render or mesh case. - creation_bound: std::time::Duration, -} - -impl Opened { - /// The facts of `device`, opened in `leg` for a case mapped as `mapped` (restricted to - /// `restriction`'s profile, whose second check it makes), read through its raw handles. - fn of( - device: &Device, - leg: Leg, - mapped: &Mapped, - restriction: Option<&RuntimeRestriction>, - ) -> Result { - let kind = Kind::of(mapped); - let restricted = restriction - .map(|restriction| restriction.check(device)) - .transpose()?; - let translation = restricted - .as_ref() - .map(|restricted| translation(device, restricted, mapped)) - .transpose()?; - let untranslated = match &translation { - Some(Translation::Bridged(gap)) => Some(gap.clone()), - Some(Translation::Profile | Translation::Kept(_)) | None => None, - }; - // SAFETY: only physical-device queries of the device's own instance; nothing is created, - // destroyed, or submitted, and the handles are not kept past the borrow. - let facts = unsafe { - let handles = device.raw(); - DeviceFacts::query(handles.entry, handles.instance, handles.physical_device) - }?; - let compile = device.compile_device().clone(); - let profile = compile.profile().clone(); - let enabled = &device.enabled().features; - let mut environment = facts.environment(enabled.contains(&VkFeature::SamplerAnisotropy)); - let fingerprint: String = profile - .fingerprint() - .iter() - .map(|byte| format!("{byte:02x}")) - .collect(); - if let Some(object) = environment.as_object_mut() { - for (key, value) in [ - ("executor", serde_json::json!(kind.executor())), - ("executed_by", serde_json::json!("runtime")), - ("layers", serde_json::json!(RECORDED_LAYERS)), - ("synchronization_validation", serde_json::json!(true)), - ( - "profiles_layer", - restricted - .as_ref() - .map_or(serde_json::Value::Null, |restricted| { - restricted.record.clone() - }), - ), - ( - "robustness", - serde_json::json!({ - "leg": leg, - "enabled": ROBUSTNESS_FEATURES - .iter() - .filter(|feature| enabled.contains(feature)) - .map(|feature| format!("{feature:?}")) - .collect::>(), - }), - ), - ("profile_fingerprint", serde_json::json!(fingerprint)), - ("profile", serde_json::json!(format!("{profile:?}"))), - ] { - object.insert(key.into(), value); - } - if let Some(Translation::Kept(kept)) = &translation { - object.insert("kept_members".into(), serde_json::json!(kept)); - } - } - Ok(Opened { - facts, - kind, - environment, - translator_fingerprint: engine_fingerprint(&profile), - profile, - compile, - leg, - restricted_to: restriction.map(|restriction| restriction.stem().to_owned()), - untranslated, - creation_bound: match mapped { - Mapped::Compute(case) => case.creation_bound, - Mapped::Render(_) | Mapped::Mesh(_) => crate::budgets::PIPELINE_CREATION_CEILING, - }, - }) - } - - /// The opened device a typed refusal names, with what the run had compiled when it refused - /// (`artifact`: empty for a refusal before the dispatch took its pipeline, which compiled - /// nothing the census can cover). - fn refused_on(&self, artifact: &CaseArtifact) -> RefusedOn { - RefusedOn { - environment: self.environment.clone(), - translator_fingerprint: self.translator_fingerprint.clone(), - artifact: Some(artifact.executed()), - } - } - - /// The one pipeline `execution` (the case's one dispatch or draw) executed, of this run's - /// kind: what a row names it, its stage modules in pipeline order, and its plan. - fn executed<'a>( - &self, - execution: &'a Execution, - ) -> Result<(&'static str, &'a [StageModule], &'a dyn Planned), ExecutorError> { - match (execution.pipeline(), self.kind) { - (ExecutedPipeline::Compute(pipeline), Kind::Compute) => Ok(( - "the compute pipeline", - std::slice::from_ref(&pipeline.stage), - pipeline.as_ref(), - )), - (ExecutedPipeline::Render(pipeline), Kind::Render) => { - Ok(("the render pipeline", &pipeline.stages, pipeline.as_ref())) - } - (_, kind) => Err(ExecutorError::Failed(format!( - "the case's {} run executed a pipeline of the other kind", - kind.executor() - ))), - } - } - - /// The artifact of `execution`'s pipeline, planned for the bind shape it ran with, with the - /// bytes of the visible-function `tables` it bound. - fn artifact( - &self, - execution: &Execution, - tables: &TableBuffers, - ) -> Result { - let (_, _, planned) = self.executed(execution)?; - let mut artifact = CaseArtifact::default(); - artifact.record( - CompileSubject::Case, - planned, - tables, - &self.compile, - execution.shape(), - )?; - Ok(artifact) - } - - /// The out-of-bounds facts a dispatch's or draw's containment decision came to (`decision`, - /// taken before anything was committed), or the refusal of a target the device leaves - /// uncontained, recording what `execution` compiled with the bytes of the `tables` it binds. - fn decided( - &self, - execution: &Execution, - tables: &TableBuffers, - decision: Result, ExecutorError>, - ) -> Result, Stop> { - match decision { - Err(error @ ExecutorError::NotSupported(_)) => { - let artifact = self.artifact(execution, tables)?; - Err(Stop::Refused(Box::new(Refused { error, artifact }))) - } - decided => decided.map_err(Stop::from), - } - } - - /// The row of `ran`: the one dispatch's or draw's compiled pipeline, its census, artifact (with - /// the bytes of the tables it bound), and SPIR-V hash (a render pipeline's stage words in - /// pipeline order, as the executor hashes them), each `VkPipeline` it recorded held to the - /// creation ceiling, and the codes of the degrade notices the run's device delivered - /// (`runtime_degrades`, [`degrades`]). - fn row(&self, ran: Ran, degrades: Vec<&'static str>) -> Result { - let [execution] = ran.executions.as_slice() else { - return Err(ExecutorError::Failed(format!( - "the runtime recorded {} executions of the case's one dispatch or draw", - ran.executions.len() - ))); - }; - let (what, stages, planned) = self.executed(execution)?; - for &created in execution.pipeline_creation() { - crate::budgets::creation_within(what, created, self.creation_bound) - .map_err(ExecutorError::Failed)?; - } - let mut artifact = self.artifact(execution, &ran.tables)?; - // The pipeline's notes under the specialization its plan for the bind shape it ran with - // gives: the bound formats' classes and samplers' words. - let plan = planned.plan_for(&self.compile, execution.shape()).ok(); - let mut modules = - ModuleCensus::of_pipeline_modules_under(stages, &self.profile, plan.as_ref()) - .map_err(ExecutorError::Failed)?; - // The census covers every module the run executed, the producer's and each executed - // command's, as the executor's does. The authored compile census cannot compile what the - // runtime ran for those commands (its own execution of the records), so the row has no - // artifact digest and stays on its build (`uncovered`). - for child in &ran.children { - let stages = match child.pipeline() { - ExecutedPipeline::Compute(pipeline) => std::slice::from_ref(&pipeline.stage), - ExecutedPipeline::Render(pipeline) => &pipeline.stages[..], - }; - for &created in child.pipeline_creation() { - crate::budgets::creation_within_ceiling("an executed command's pipeline", created) - .map_err(ExecutorError::Failed)?; - } - modules.extend( - ModuleCensus::of_pipeline_modules(stages, &self.profile) - .map_err(ExecutorError::Failed)?, - ); - artifact.record_uncovered(); - } - let census = ExecutedCensus { - device: Some(self.facts.execution_class()), - product: TRANSLATOR_FINGERPRINT.into(), - restricted_to: self.restricted_to.clone(), - leg: Some(self.leg), - modules, - out_of_bounds: ran.out_of_bounds, - rate_map_pass: None, - artifact: Some(artifact.executed()), - }; - let mut environment = self.environment.clone(); - environment[crate::observation::RUNTIME_DEGRADES] = serde_json::json!(degrades); - Ok(ComputeRun { - output: ran.output, - spv_sha256: spirv_sha256(stages), - translator_fingerprint: self.translator_fingerprint.clone(), - environment, - status: ran.status, - comparison: census.comparison_class(), - census, - }) - } -} - -/// The SHA-256 of `stages`' SPIR-V words in pipeline order: a compute pipeline's one stage's, and -/// every stage of a render pipeline, as the executor hashes them. -fn spirv_sha256(stages: &[StageModule]) -> String { - sha256_bytes( - &stages - .iter() - .flat_map(StageModule::spirv_bytes) - .collect::>(), - ) -} - -/// The run of `prepared` on `device`: a kernel case's library, function and pipeline state and -/// its committed dispatch, or a render case's committed draw (`runtime_case::encoded_render`); the -/// bounded wait for it under the hang protocol (its hang record names the case and the modules it -/// executed), the execution report's verdict, and the output. -fn run_on( - device: &Device, - opened: &Opened, - prepared: &PreparedCase, - backend: Backend, -) -> Result { - let moltenvk = opened.facts.is_moltenvk(); - match backend { - Backend::Moltenvk if !moltenvk => { - return Err(format!( - "the moltenvk backend opened {} (driver id {}), not MoltenVK", - opened.facts.driver_name, opened.facts.driver_id - ) - .into()) - } - Backend::Vulkan if moltenvk => { - return Err( - "the native vulkan backend opened MoltenVK; use the moltenvk backend" - .to_owned() - .into(), - ) - } - Backend::Moltenvk | Backend::Vulkan => {} - } - let primary = &prepared.checked.primary; - let bitcode = RowSource::of_row(&primary.source) - .bitcode() - .map_err(|error| format!("the case's AIR: {error:?}"))?; - let usage = texture_usage(&primary.case, &primary.interface)?; - match &prepared.mapped { - Mapped::Compute(compute) if compute.tile.is_some() => { - let argument_usage = - argument_texture_usage(&compute.argument_buffer_textures, &primary.interface)?; - // A tile kernel's tile pipeline state, then its visible-function tables for the tile - // stage, dispatched on a render encoder of its pass (`runtime_case::encoded_tile`). - let (pipeline, tables) = (|| { - let function = function(device, &bitcode, compute)?; - let linked = linked_functions(device, &prepared.linked, &compute.constants)?; - let pass = compute - .tile - .as_ref() - .ok_or("the case runs in no tile pass")?; - let pipeline = device - .new_tile_render_pipeline_state( - &tile_descriptor(&function, linked.functions.clone(), pass), - &PipelineOptions::default(), - ) - .map_err(CaseError::runtime("new_tile_render_pipeline_state"))?; - let tables = tile_tables(&pipeline, compute, &linked)?; - Ok((pipeline, tables)) - })() - .map_err(|error| stop(error, false))?; - let committed = encoded_tile( - device, - compute, - &usage, - &argument_usage, - &pipeline, - tables.tables, - ) - .and_then(|encoded| encoded.commit()) - .map_err(|error| stop(error, false))?; - let status = completed(prepared, &committed.command_buffer, &committed.executions)?; - let output = committed - .output(compute) - .map_err(|error| stop(error, true))?; - Ok(Ran { - output, - status, - executions: committed.executions, - tables: tables.words, - out_of_bounds: None, - children: Vec::new(), - }) - } - Mapped::Compute(compute) => { - let argument_usage = - argument_texture_usage(&compute.argument_buffer_textures, &primary.interface)?; - // The pipeline state, then its visible-function tables, each entry the handle the - // state gives the function it holds; and the state of each template its commands and - // argument buffers name. - let templates = template_states(device, prepared)?; - let (pipeline, tables) = (|| { - let function = function(device, &bitcode, compute)?; - let linked = linked_functions(device, &prepared.linked, &compute.constants)?; - let pipeline = device - .new_compute_pipeline_state( - &compute_descriptor(&function, linked.functions.clone(), compute), - &PipelineOptions::default(), - ) - .map_err(CaseError::runtime("new_compute_pipeline_state"))?; - let tables = visible_function_tables(&pipeline, compute, &linked)?; - Ok((pipeline, tables)) - })() - .map_err(|error| stop(error, false))?; - let encoded = encoded_case( - device, - compute, - &usage, - &argument_usage, - &pipeline, - (tables.tables, &templates), - ) - .map_err(|error| stop(error, false))?; - // How the dispatch's module contains each out-of-bounds target on this device, from - // what the dispatch executed, before anything runs: a target the device leaves - // uncontained refuses the case uncommitted, recording what the dispatch compiled. - let [execution] = encoded.executions.as_slice() else { - return Err(format!( - "the case's one dispatch recorded {} executions", - encoded.executions.len() - ) - .into()); - }; - let out_of_bounds = opened.decided( - execution, - &tables.words, - kernel_out_of_bounds(opened, compute, execution), - )?; - // Each command buffer the case executes, in key order, encoded before anything is - // committed and committed after the producer on its queue. - let resident: Vec<_> = encoded - .buffers - .values() - .chain(encoded.resources.argument_buffers.values()) - .map(Buffer::as_resource) - .collect(); - let executions = compute - .command_buffers - .iter() - .filter(|(_, resource)| resource.execute.is_some()) - .map(|(&key, resource)| { - encoded_execution( - encoded.command_buffer.command_queue(), - (&encoded.buffers, &resident), - &encoded.resources.commands, - (key, resource), - &templates, - ) - }) - .collect::, _>>() - .map_err(|error| stop(error, false))?; - let committed = encoded.commit().map_err(|error| stop(error, false))?; - for execution in &executions { - execution - .commit() - .map_err(|error| stop(CaseError::runtime("commit")(error), true))?; - } - let status = completed(prepared, &committed.command_buffer, &committed.executions)?; - // The commands the producer left, read back, then what each execution ran. - committed - .resources - .commands - .check_commands() - .map_err(|error| stop(error, true))?; - let mut children = Vec::new(); - for execution in &executions { - completed(prepared, execution, &execution.executions())?; - children.extend(execution.executions()); - } - let output = committed - .output(compute) - .map_err(|error| stop(error, true))?; - // What the run changed around each target placed between guards, read once it - // completed. - let guards = committed - .guard_counts(compute) - .map_err(|error| stop(error, true))?; - let out_of_bounds = - out_of_bounds.map(|run| with_escaped(run, &guards, Placement::Heap)); - Ok(Ran { - output, - status, - executions: committed.executions, - tables: tables.words, - out_of_bounds, - children, - }) - } - Mapped::Render(render) => { - let companion = companion_source(render) - .map(|source| source.bitcode()) - .transpose() - .map_err(|error| format!("the generated companion's AIR: {error:?}"))?; - // The state of each template its argument buffers name. - let templates = template_states(device, prepared)?; - let inputs = RenderInputs { - case: &primary.case, - render, - bitcode: &bitcode, - companion: companion.as_deref(), - linked: &prepared.linked, - texture_usage: &usage, - interface: &primary.interface, - imageblock: primary.reflection.fragment_imageblock.as_ref(), - templates: &templates, - }; - let encoded = encoded_render(device, &inputs).map_err(|error| stop(error, false))?; - // How the draw's vertex module contains each out-of-bounds target on this device, - // from what the draw executed, before anything runs: a target the device leaves - // uncontained refuses the case uncommitted, recording what the draw compiled. - let [execution] = encoded.executions.as_slice() else { - return Err(format!( - "the case's one draw recorded {} executions", - encoded.executions.len() - ) - .into()); - }; - let out_of_bounds = opened.decided( - execution, - &encoded.tables, - draw_out_of_bounds(opened, render, execution), - )?; - // Each command buffer the draw executes, encoded before anything is committed and - // committed after the draw on its queue. - let executions = encoded - .executions(render, &templates) - .map_err(|error| stop(error, false))?; - let committed = encoded.commit().map_err(|error| stop(error, false))?; - for execution in &executions { - execution - .commit() - .map_err(|error| stop(CaseError::runtime("commit")(error), true))?; - } - let status = completed(prepared, &committed.command_buffer, &committed.executions)?; - // The commands the draw left, read back, then what each execution ran. - committed - .check_commands() - .map_err(|error| stop(error, true))?; - let mut children = Vec::new(); - for execution in &executions { - completed(prepared, execution, &execution.executions())?; - children.extend(execution.executions()); - } - let output = committed - .output(&inputs) - .map_err(|error| stop(error, true))?; - // What the draw changed around each vertex and index buffer target, read once it - // completed. - let guards = committed - .guard_counts() - .map_err(|error| stop(error, true))?; - let out_of_bounds = - out_of_bounds.map(|run| with_escaped(run, &guards, Placement::Heap)); - Ok(Ran { - output, - status, - executions: committed.executions, - tables: committed.tables, - out_of_bounds, - children, - }) - } - Mapped::Mesh(mesh) => { - let companion = mesh - .companion - .as_ref() - .map(|generated| { - RowSource::Text(Cow::Owned(generated.air_text(Spelling::Opaque))).bitcode() - }) - .transpose() - .map_err(|error| format!("the generated companion's AIR: {error:?}"))?; - let inputs = MeshInputs { - case: &primary.case, - mesh, - bitcode: &bitcode, - companion: companion.as_deref(), - texture_usage: &usage, - interface: &primary.interface, - }; - let encoded = encoded_mesh(device, &inputs).map_err(|error| stop(error, false))?; - let committed = encoded.commit().map_err(|error| stop(error, false))?; - let status = completed(prepared, &committed.command_buffer, &committed.executions)?; - let output = committed - .mesh_output(mesh) - .map_err(|error| stop(error, true))?; - Ok(Ran { - output, - status, - executions: committed.executions, - tables: committed.tables, - out_of_bounds: None, - children: Vec::new(), - }) - } - } -} - -/// How the module `compute`'s one dispatch executed (`execution`, its encoded command buffer's) -/// contains each of the case's out-of-bounds targets on `opened`'s device, as the executor's own -/// context decides it (`engine::out_of_bounds_run`: the module's slots, stage-input fetches -/// and strategies, the device's profile and execution class), or `None` for a case without -/// targets: the facts before what the targets' guards count (`guards::with_escaped`). -fn kernel_out_of_bounds( - opened: &Opened, - compute: &ComputeCase, - execution: &Execution, -) -> Result, ExecutorError> { - if compute.out_of_bounds.is_empty() { - return Ok(None); - } - let ExecutedPipeline::Compute(pipeline) = execution.pipeline() else { - return Err("the case's dispatch executed a render pipeline".into()); - }; - let attributes = out_of_bounds::Fetch::of_stage_input(compute.stage_input.as_ref()); - out_of_bounds_run( - Some(opened.facts.execution_class()), - &opened.profile, - &out_of_bounds::ModuleFacts { - stage: ShaderStage::Kernel, - slots: &pipeline.interface.slots, - attributes: &attributes, - resident_roots: pipeline.interface.needs_pointer_translation, - handle_table: pipeline.interface.needs_handle_translation, - strategies: &pipeline.stage.strategies, - }, - &compute.out_of_bounds, - ) -} - -/// The pipeline state of each pipeline token `prepared`'s case names: each pipeline state's an -/// argument buffer holds and each execution's parent pipeline's, made from its template's AIR as -/// the template's own case makes it (its constant values, the functions it links), with -/// `support_indirect_command_buffers`, as the Metal oracle makes the template states its commands -/// name: a kernel template's compute state, a vertex or fragment template's render state of the -/// oracle's descriptor, as the render runner makes its own case's -/// (`runtime_case::render_pipeline_descriptor`), and an object or mesh template's mesh render -/// state, as the mesh runner makes its own case's (`runtime_case::mesh_pipeline_state`). -fn template_states( - device: &Device, - prepared: &PreparedCase, -) -> Result, Stop> { - let checked = &prepared.checked; - let case = &checked.primary.case; - let parents = case - .command_buffers - .iter() - .filter_map(|resource| resource.execute.as_ref()?.pipeline.as_ref()) - .map(|template| (template.token, &template.case_id)); - let mut states = BTreeMap::new(); - for (token, case_id) in case - .pipeline_states - .iter() - .map(|state| (state.token, &state.case_id)) - .chain(parents) - { - if states.contains_key(&token) { - continue; - } - let template = checked - .pipeline_templates - .get(case_id) - .ok_or_else(|| format!("pipeline template {case_id} was not checked"))?; - let bitcode = RowSource::of_row(&template.source) - .bitcode() - .map_err(|error| format!("pipeline template {case_id}'s AIR: {error:?}"))?; - let linked = linked_modules(&template.linked_functions)?; - let state = match template.case.stage { - Stage::Kernel => { - let mapped = compute_case(&template.case, &template.interface) - .map_err(|refused| Stop::Error(refused.into()))?; - (|| { - let function = function(device, &bitcode, &mapped)?; - let linked = linked_functions(device, &linked, &mapped.constants)?; - let mut descriptor = compute_descriptor(&function, linked.functions, &mapped); - descriptor.support_indirect_command_buffers = true; - device - .new_compute_pipeline_state(&descriptor, &PipelineOptions::default()) - .map(TemplateState::Compute) - .map_err(CaseError::runtime(format!( - "pipeline template {case_id}: new_compute_pipeline_state" - ))) - })() - } - Stage::Vertex | Stage::Fragment => { - let render = graphics::render_case( - &template.case, - &template.interface, - template.entry_ll(), - template.companion.as_ref(), - template.reflection.fragment_imageblock.as_ref(), - )?; - let companion = companion_source(&render) - .map(|source| source.bitcode()) - .transpose() - .map_err(|error| { - format!("pipeline template {case_id}'s generated companion: {error:?}") - })?; - let usage = texture_usage(&template.case, &template.interface)?; - let inputs = RenderInputs { - case: &template.case, - render: &render, - bitcode: &bitcode, - companion: companion.as_deref(), - linked: &linked, - texture_usage: &usage, - interface: &template.interface, - imageblock: template.reflection.fragment_imageblock.as_ref(), - templates: &BTreeMap::new(), - }; - (|| { - let mut descriptor = render_pipeline_descriptor(device, &inputs)?; - descriptor.support_indirect_command_buffers = true; - device - .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) - .map(TemplateState::Render) - .map_err(CaseError::runtime(format!( - "pipeline template {case_id}: new_render_pipeline_state" - ))) - })() - } - Stage::Object | Stage::Mesh => { - let mesh = super::mesh::mesh_case(&template.case, template.companion.as_ref()) - .map_err(Stop::Error)?; - let companion = mesh - .companion - .as_ref() - .map(|generated| { - RowSource::Text(Cow::Owned(generated.air_text(Spelling::Opaque))).bitcode() - }) - .transpose() - .map_err(|error| { - format!("pipeline template {case_id}'s generated companion: {error:?}") - })?; - mesh_pipeline_state(device, &mesh, (&bitcode, companion.as_deref()), true) - .map(TemplateState::Render) - } - } - .map_err(|error| stop(error, false))?; - states.insert(token, state); - } - Ok(states) -} - -/// The function of kernel case `compute`'s entry, made with its constant values, from a library -/// of `bitcode`, its AIR, on `device`. -fn function(device: &Device, bitcode: &[u8], compute: &ComputeCase) -> Result { - device - .new_library_with_air(bitcode) - .map_err(CaseError::runtime("new_library_with_air"))? - .new_function_with_name_constant_values(&compute.entry, &compute.constants) - .map_err(CaseError::runtime("new_function_with_name_constant_values")) -} - -/// How the render pipeline `render`'s one draw executed (`execution`, its encoded command -/// buffer's) contains each of the case's out-of-bounds targets on `opened`'s device, as the -/// executor's own context decides it (`engine::draw_out_of_bounds_run`: the module that runs -/// the vertex function, its attributes' fetches, the device's profile and execution class), or -/// `None` for a case without targets: the facts before what the targets' guards count -/// (`guards::with_escaped`). The draw contains its index positions past an index buffer target as -/// that containment states (its execution record's `index_padding`), or the run fails, as the -/// executor's context fails its draw (`engine::index_padding_agrees`). -fn draw_out_of_bounds( - opened: &Opened, - render: &RenderCase, - execution: &Execution, -) -> Result, ExecutorError> { - if render.out_of_bounds.is_empty() { - return Ok(None); - } - let ExecutedPipeline::Render(pipeline) = execution.pipeline() else { - return Err("the case's draw executed a compute pipeline".into()); - }; - let run = draw_out_of_bounds_run( - Some(opened.facts.execution_class()), - &opened.profile, - pipeline, - render, - )?; - index_padding_agrees(run.as_ref(), execution.index_padding())?; - Ok(run) -} - -/// What a device restricted to a profile translates a case for. -enum Translation { - /// The profile: the device's kept members (`profiles::KEPT`, read as the device's own through - /// the layer) are the profile's values. - Profile, - /// The profile's members but the kept ones, `kept`, which are the device's: the case is a - /// patch draw the profile emulates ([`emulated_patches`]), which the runtime runs on them. - Kept(Vec), - /// The same, for any other case, which the bridge sends to the executor's context: the gap. - Bridged(String), -} - -/// What a device restricted to a profile translates `mapped` for: the runtime compiles for the -/// description it read through the profiles layer, whose kept members (`profiles::KEPT`) are the -/// device's own, where the executor's context translates for the profile's (`check_restricted`). -/// [`Translation::Profile`] where the two make the same profile (the profile states the device's -/// own values there), so the runtime translates for the profile; else the bridge sends the case to -/// the executor's context (item 3), whose restricted row means what it always has, but for a patch -/// draw the profile emulates, whose emulation that context does not run: the runtime runs it on the -/// kept members, which its row records. -fn translation( - device: &Device, - restricted: &RestrictedDevice, - mapped: &Mapped, -) -> Result { - let translated = restricted - .translated - .clone() - .with_enabled(device.enabled()) - .and_then(|description| { - metal2vulkan::device::Device::new(description, crate::candidate::requested_policy()) - }) - .map_err(|error| format!("the profile's description on the enabled set: {error}"))?; - if translated.profile().fingerprint() == device.compile_device().profile().fingerprint() { - return Ok(Translation::Profile); - } - if emulated_patches(mapped, translated.profile()) { - return Ok(Translation::Kept(restricted.kept.clone())); - } - Ok(Translation::Bridged(format!( - "profile restriction: the runtime compiles for the device's kept members ({}), not the \ - profile's", - restricted.kept.join(", ") - ))) -} - -/// Whether `mapped` is a patch draw (`graphics::Assembly::Patches`) that `profile`, without -/// `tessellationShader`, compiles emulated (`metal2vulkan`'s `lower::tessellation`): its pipeline -/// binds the emulation's work and records, which the runtime makes and the executor's context -/// does not (it refuses their descriptor source, `NotImplemented`). -fn emulated_patches(mapped: &Mapped, profile: &metal2vulkan::device::DeviceProfile) -> bool { - let Mapped::Render(render) = mapped else { - return false; - }; - matches!(render.assembly, graphics::Assembly::Patches { .. }) - && !profile - .enabled() - .features - .contains(&VkFeature::TessellationShader) -} - -/// Wait for `command_buffer`, which runs `prepared`'s `executions`, bounded under the hang -/// protocol (its hang record names the case and the SPIR-V the first execution ran), then its -/// execution report's verdict. -fn completed( - prepared: &PreparedCase, - command_buffer: &CommandBuffer, - executions: &[Execution], -) -> Result { - let module_sha256 = executions - .first() - .map(|execution| match execution.pipeline() { - ExecutedPipeline::Compute(pipeline) => { - spirv_sha256(std::slice::from_ref(&pipeline.stage)) - } - ExecutedPipeline::Render(pipeline) => spirv_sha256(&pipeline.stages), - }) - .unwrap_or_default(); - let label = SubmissionLabel { - case_id: prepared.checked.primary.case.case_id.clone(), - module_sha256, - }; - let waited = with_submission_label(label, || { - crate::gpu::wait::runtime::wait_for_command_buffer( - command_buffer, - SubmissionBackend::vulkan(prepared.device), - "the runtime's command buffer", - ) - }); - // A read of an argument the function constants removed completes the command buffer, its - // report stating the read: `report_verdict` gives the translation's typed refusal. - waited?; - let report = command_buffer - .execution_report() - .ok_or("the completed command buffer has no execution report")?; - Ok(report_verdict(report)?) -} - -/// The members a row or refusal of the executor's own context records of the runtime path: -/// that the executor ran it, and why the runtime did not: the prerequisites its family waits for, -/// or the gap the runtime raised before it committed (the bridge). -pub fn executor_members(why: &ExecutorRun) -> [(&'static str, serde_json::Value); 2] { - let reason = match why { - ExecutorRun::WaitsFor(prerequisites) => ( - "runtime_waits_for", - serde_json::json!(prerequisites - .iter() - .map(|prerequisite| prerequisite.name()) - .collect::>()), - ), - ExecutorRun::Gap(gap) => ("runtime_gap", serde_json::json!(gap)), - }; - [("executed_by", serde_json::json!("executor")), reason] -} - -/// Why the executor's own context ran a case. -pub enum ExecutorRun { - /// The runtime path waits for the prerequisites of the case's family. - WaitsFor(BTreeSet), - /// The runtime raised a typed gap before it committed (the bridge). - Gap(String), -} - -#[cfg(test)] -mod tests; diff --git a/crates/metal2vulkan-validation/src/candidate/engine/runtime_run/tests.rs b/crates/metal2vulkan-validation/src/candidate/engine/runtime_run/tests.rs deleted file mode 100644 index 4b825df75..000000000 --- a/crates/metal2vulkan-validation/src/candidate/engine/runtime_run/tests.rs +++ /dev/null @@ -1,1056 +0,0 @@ -//! The runtime path's routing, device-free, over the committed public cases. - -use super::*; -#[cfg(any(m2v_gpu, m2v_cpu_icd))] -use crate::candidate::runtime_case::layer_reported_nothing_at_all; -use crate::check::admission::{admit, ExecutionRequest}; -use crate::gpu::DeviceType; -use crate::store::CorpusStore; -use std::collections::BTreeMap; -use std::collections::BTreeSet; - -/// The output of `case`'s current Metal observation in the oracle's environment, from `store`. -#[cfg(any(m2v_gpu, m2v_cpu_icd))] -fn metal_output(store: &CorpusStore, case: &crate::case::AuthoredCase) -> Result, String> { - use base64::Engine as _; - let name = &case.name; - let metal = crate::observation::MetalObservation::current( - store.read_metal_of_case(case)?, - case, - "apple-m3-max-macos27.0.1", - crate::metal::ORACLE_ABI, - ) - .map_err(|error| format!("{name}: {error:?}"))?; - let output = (metal.observed_output()).ok_or_else(|| format!("{name}: no output"))?; - (base64::engine::general_purpose::STANDARD.decode(output)).map_err(|error| error.to_string()) -} - -/// The route of each committed public case `names` names, prepared for the CPU device. -fn routes(names: &[&str]) -> BTreeMap { - prepared(names) - .into_iter() - .map(|(name, prepared)| (name, route(&prepared))) - .collect() -} - -/// Each committed public case `names` names, prepared for the CPU device. -fn prepared(names: &[&str]) -> BTreeMap { - let root = metal2vulkan_devtools::validation_dir().join("corpus"); - let device = DeviceType::Cpu; - let cases = CorpusStore::new(&root).read_all_cases().unwrap(); - names - .iter() - .map(|&name| { - let case = cases - .iter() - .find(|case| case.name == name) - .unwrap_or_else(|| panic!("the committed public case {name}")) - .clone(); - let admitted = admit(&root, case, ExecutionRequest::EngineCandidate { device }) - .unwrap_or_else(|error| panic!("{name}: {error}")); - let prepared = super::super::prepare_case(device, admitted) - .unwrap_or_else(|error| panic!("{name}: {error}")); - (name.to_owned(), prepared) - }) - .collect() -} - -/// Under a restriction whose kept members the device holds otherwise, a patch draw of a profile -/// without `tessellationShader` (which compiles it emulated) runs on the runtime, the only path -/// that runs the emulation; one of a profile with the feature, and a draw of primitives, go to -/// the executor's context as before. -#[test] -fn a_patch_draw_a_profile_emulates_runs_on_the_runtime() { - let patches = "back-culled-clockwise-quad-output-of-a-patch-and-its-mirror"; - let primitives = "authored-fragment-constant-color"; - let cases = prepared(&[patches, primitives]); - let floor = crate::engine::load_profile("vk12-floor").unwrap(); - let lavapipe = crate::engine::load_profile("lavapipe").unwrap(); - assert!(emulated_patches(&cases[patches].mapped, &floor)); - assert!(!emulated_patches(&cases[patches].mapped, &lavapipe)); - assert!(!emulated_patches(&cases[primitives].mapped, &floor)); -} - -/// The runtime runs a kernel case of buffers, of textures (sparse and multisampled ones included) -/// and samplers, of threadgroup memory, of an explicit imageblock, of a tile pass, of -/// argument-buffer buffers, textures and samplers, of indirect command buffers of compute commands -/// and the compute pipeline states its argument buffers hold, of rasterization-rate maps, of -/// function constant values, of stage inputs, of visible-function tables, and of out-of-bounds -/// targets (buffers and stage inputs a guard holds, textures, thread and threadgroup memory, a -/// handle array), and a render case of one direct or indexed draw (single-sampled or multisampled, -/// with its vertex inputs and attachments, its argument buffers, a fragment case's explicit -/// imageblock, and a rasterization-rate map); every other case waits on the executor's context for the steps that -/// add each prerequisite it needs. (No committed public case links functions without a -/// visible-function table: the linked kernels the runtime runs are private, and `runtime_lane`'s -/// `a_kernel_runs_the_functions_its_descriptor_links` runs the owned linking fixtures.) -#[test] -fn committed_cases_route_by_their_own_inputs() { - use Prerequisite as P; - let expected = [ - ( - "saturating-halving-and-wide-product-integers-at-their-edges", - Route::Runtime, - ), - ( - "sample-each-of-three-textures-through-one-dynamic-array-index", - Route::Runtime, - ), - ("threadgroup-scratch-of-eighty-byte-elements", Route::Runtime), - ("imageblock-word", Route::Runtime), - ( - "map-a-physical-coordinate-through-a-uniform-rate-map", - Route::Runtime, - ), - ( - "map-physical-coordinates-through-rate-maps-an-argument-buffer-holds", - Route::Runtime, - ), - ("walk-a-device-pointer-chain-through-a-loop-phi", Route::Runtime), - ("gated-bias-on", Route::Runtime), - ("fold-a-zero-function-constant-gate", Route::Runtime), - ("fragment-custom-imageblock-depth", Route::Runtime), - ( - "primitive-acceleration-structure-intersection", - Route::Executor(BTreeSet::from([P::RayTracing])), - ), - ("pipeline-states-beside-the-data-of-two-stages", Route::Runtime), - ("pipeline-states-beside-the-data-a-vertex-reads", Route::Runtime), - ("gpu-encoded-draws-run-the-inherited-vertex-buffers", Route::Runtime), - ("gpu-encoded-draws-run-the-host-encoded-vertex-buffers", Route::Runtime), - ("execute-two-gpu-encoded-template-dispatches", Route::Runtime), - ("encode-compute-commands-beside-output", Route::Runtime), - ( - "host-encoded-over-limit-and-ragged-dispatches-in-two-command-buffers", - Route::Runtime, - ), - ("encode-render-commands-beside-output", Route::Runtime), - ("imageblock-three-widths-load", Route::Runtime), - ("tile-grid-float-attachment-doubles-each-pixel-once", Route::Runtime), - ( - "two-bound-visible-tables-answer-null-and-size", - Route::Runtime, - ), - ("kernel-stage-input-word", Route::Runtime), - ("kernel-stage-input-fetches-past-its-buffer", Route::Runtime), - ( - "sample-a-cube-with-explicit-gradients-through-a-sampler-held-beside-it-in-an-argument-buffer", - Route::Runtime, - ), - ("loads-and-stores-past-a-device-buffer", Route::Runtime), - ("reads-and-writes-past-a-texture", Route::Runtime), - ("loads-and-stores-past-a-thread-local-array", Route::Runtime), - ("loads-and-stores-past-a-threadgroup-allocation", Route::Runtime), - ("reads-through-an-index-past-a-top-level-texture-array", Route::Runtime), - ( - "a-write-to-an-unmapped-texel-read-back-after-a-texture-barrier", - Route::Runtime, - ), - ( - "four-multisample-reads-at-two-samples", - Route::Runtime, - ), - ("authored-fragment-constant-color", Route::Runtime), - ("three-color-inputs-color-attachment", Route::Runtime), - ( - "color-of-a-sample-rate-fragment-only-where-its-stencil-passes", - Route::Runtime, - ), - ("pass-on-a-vertex-attribute-the-pipeline-declares", Route::Runtime), - ( - "zero-negative-and-nan-factors-cull-or-clamp-triangle-patches", - Route::Runtime, - ), - ( - "control-point-and-patch-input-fetches-past-their-buffers", - Route::Runtime, - ), - ( - "fragment-positions-in-a-half-quality-rate-mapped-pass", - Route::Runtime, - ), - ( - "sample-in-a-fragment-through-a-sampler-held-beside-its-texture-in-an-argument-buffer", - Route::Runtime, - ), - ( - "sixteen-overlapping-triangles-update-a-raster-ordered-argument-buffer-member", - Route::Runtime, - ), - ("indexed-draw-reads-past-its-uint32-index-buffer", Route::Runtime), - ( - "indexed-draw-reads-past-its-uint16-index-buffer-from-an-offset", - Route::Runtime, - ), - ("vertex-attribute-fetches-past-its-vertex-buffer", Route::Runtime), - ("gpu-encoded-vertex-buffers-run-the-host-encoded-draws", Route::Runtime), - ]; - let names: Vec<&str> = expected.iter().map(|(name, _)| *name).collect(); - let routes = routes(&names); - for (name, route) in expected { - assert_eq!(routes[name], route, "{name}"); - } -} - -/// A case the runtime runs replays its templates through the runtime's own pipeline states, so the -/// executor's context's refusal of them (a compute template with a stage input or an imageblock, a -/// render template with vertex inputs or a post-tessellation stage) is not that run's: the pipelines -/// the authored compile census lists for it are its own, and each command buffer it executes is -/// uncovered, never the context's refusal. -#[test] -fn a_runtime_case_compiles_its_own_pipeline_where_the_context_refuses_its_templates() { - use super::super::{case_compiles, CompileSubject}; - use crate::worker::compile::WorkerDevice; - let root = metal2vulkan_devtools::validation_dir().join("corpus"); - let device = DeviceType::Cpu; - let cases = CorpusStore::new(&root).read_all_cases().unwrap(); - let profile = WorkerDevice::new( - crate::engine::load_description("lavapipe").unwrap(), - metal2vulkan::device::DevicePolicy::default(), - ) - .unwrap(); - for name in [ - "a-kernel-encodes-the-stage-in-regions-of-its-dispatches", - "host-encoded-stage-in-regions-and-attribute-strides-of-executed-commands", - "a-kernel-encodes-the-imageblock-sizes-of-its-dispatches", - "host-encoded-vertex-attribute-strides-of-executed-draws", - "patch-draws-a-kernel-encodes-at-factor-scales-and-the-host-encodes", - "indexed-patch-draws-a-kernel-encodes-on-a-template-without-control-point-indices", - ] { - let case = cases - .iter() - .find(|case| case.name == name) - .unwrap_or_else(|| panic!("the committed public case {name}")) - .clone(); - let admitted = admit(&root, case, ExecutionRequest::EngineCandidate { device }) - .unwrap_or_else(|error| panic!("{name}: {error}")); - let prepared = super::super::prepare_case(device, admitted) - .unwrap_or_else(|error| panic!("{name}: {error}")); - assert_eq!(route(&prepared), Route::Runtime, "{name}"); - assert!( - matches!( - prepared.templates(), - Err(ExecutorError::NotSupported( - crate::check::admission::NotSupported::NotImplemented(_) - )) - ), - "{name}: the executor's context replays its templates" - ); - let planned = - case_compiles(&prepared, &profile).unwrap_or_else(|error| panic!("{name}: {error}")); - assert_eq!( - planned - .compiles - .iter() - .map(|compile| compile.subject) - .collect::>(), - [CompileSubject::Case], - "{name}" - ); - assert_eq!(planned.host_replayed, 1, "{name}"); - } -} - -/// An object or mesh case compiles device-free as the runtime compiles its draw: the authored -/// compile census plans one mesh draw request (`PipelineRequest::MeshDraw`) of its functions, its -/// generated stages from its companion's source, for its own stage's bind shape, and that request -/// compiles on a profile with mesh shaders and on one that emulates them, with no table handles. -#[test] -fn a_mesh_case_compiles_its_draw_device_free() { - use super::super::{case_compiles, CompileSubject, PlannedPipeline}; - use crate::acceptance::{compile_pipeline, AcceptancePipeline, PipelineRequest}; - use crate::worker::compile::WorkerDevice; - let root = metal2vulkan_devtools::validation_dir().join("corpus"); - let device = DeviceType::Cpu; - let profiles = ["lavapipe", "moltenvk-m3"].map(|stem| { - let worker = WorkerDevice::new( - crate::engine::load_description(stem).unwrap(), - metal2vulkan::device::DevicePolicy::default(), - ) - .unwrap(); - (stem, worker) - }); - for fixture in [ - crate::mesh_cases::grid(), - crate::mesh_cases::object(), - crate::mesh_cases::device_write(), - crate::mesh_cases::observed(), - crate::mesh_cases::launched(), - crate::mesh_cases::payload(), - crate::mesh_cases::payload_barrier(), - crate::mesh_cases::payload_outputs(), - ] { - let name = fixture.case.name.clone(); - let admitted = admit( - &root, - fixture.case, - ExecutionRequest::EngineCandidate { device }, - ) - .unwrap_or_else(|error| panic!("{name}: {error}")); - let prepared = super::super::prepare_case(device, admitted) - .unwrap_or_else(|error| panic!("{name}: {error}")); - for (stem, worker) in &profiles { - let planned = case_compiles(&prepared, worker) - .unwrap_or_else(|error| panic!("{name} {stem}: {error}")); - assert_eq!(planned.host_replayed, 0, "{name} {stem}"); - let [compile] = planned.compiles.as_slice() else { - panic!("{name} {stem}: {} compiles", planned.compiles.len()); - }; - assert_eq!(compile.subject, CompileSubject::Case, "{name} {stem}"); - let PlannedPipeline::Mesh { - request, libraries, .. - } = &compile.pipeline - else { - panic!("{name} {stem}: not a mesh draw's compile"); - }; - assert!( - matches!(request, PipelineRequest::MeshDraw { .. }), - "{name} {stem}" - ); - let bitcode = libraries - .iter() - .map(|library| library.bitcode().unwrap()) - .collect::>(); - let bitcode = bitcode.iter().map(Vec::as_slice).collect::>(); - match compile_pipeline(&bitcode, request, worker.device(), None) { - Ok(compiled) => { - assert!( - matches!(compiled.pipeline, AcceptancePipeline::Render(_)), - "{name} {stem}" - ); - request.check_handles(&compiled.handles).unwrap(); - } - Err(error) => panic!("{name} {stem}: {error:?}"), - } - } - } -} - -/// A row or refusal of the executor's context names the executor and why the runtime did not run -/// the case: the prerequisite its family waits for, or the gap the runtime raised. -#[test] -fn executor_rows_say_why_the_runtime_did_not_run_them() { - assert_eq!( - executor_members(&ExecutorRun::WaitsFor(BTreeSet::from([ - Prerequisite::DrawOutOfBoundsTargets, - Prerequisite::RayTracing, - ]))), - [ - ("executed_by", serde_json::json!("executor")), - ( - "runtime_waits_for", - serde_json::json!(["ray-tracing", "draw-out-of-bounds-targets"]) - ), - ] - ); - assert_eq!( - executor_members(&ExecutorRun::Gap("dispatch: Textures".into())), - [ - ("executed_by", serde_json::json!("executor")), - ("runtime_gap", serde_json::json!("dispatch: Textures")), - ] - ); -} - -/// Before the command buffer commits, a refusal of a runtime mechanism the driver runs wrong -/// (`Needs::RuntimeDriverDefect`) sends the case to the executor, as a typed gap does, keyed on -/// the refusal's type; after it commits, or for any other refusal, the run reports the refusal. -#[test] -fn a_runtime_driver_defect_sends_the_case_back_before_it_commits() { - use metal2vulkan::error::{Capability, Feature, RuntimeDriverDefect}; - let refusal = |unsupported: Unsupported| CaseError::Runtime { - call: "make_render_command_encoder".into(), - error: Box::new(Error::Unsupported(unsupported)), - }; - let defect = || { - refusal(Unsupported::runtime_driver_defect( - Feature::SeparateMultisampledDepthStencil, - RuntimeDriverDefect::MultisampledDepthStencilColourCopies, - )) - }; - match stop(defect(), false) { - Stop::Gap(gap) => assert_eq!( - gap, - "make_render_command_encoder: driver defect MultisampledDepthStencilColourCopies \ - (SeparateMultisampledDepthStencil)" - ), - Stop::Refused(refused) => panic!("not sent back: {}", refused.error), - Stop::Error(error) => panic!("not sent back: {error}"), - } - assert!(matches!( - stop(defect(), true), - Stop::Error(ExecutorError::NotSupported(_)) - )); - let lacking = refusal(Unsupported::needs( - Feature::SeparateMultisampledDepthStencil, - Capability::Feature(VkFeature::Maintenance8), - )); - assert!(matches!( - stop(lacking, false), - Stop::Error(ExecutorError::NotSupported(_)) - )); -} - -/// Before the command buffer commits, the runtime's refusal of a helper's pipeline (a sample -/// fill's, a sample readback's: the runner's own work around the case's pass) sends the case to -/// the executor, keyed on the error's origin and type; the same refusal of the case's own -/// pipeline, or one after the commit, is the run's refusal. -#[test] -fn a_refused_helper_pipeline_sends_the_case_back_before_it_commits() { - use metal2vulkan::device::VkProperty; - use metal2vulkan::error::{Capability, Feature}; - let unsupported = || { - Unsupported::needs( - Feature::RasterSampleCount, - Capability::Property(VkProperty::FramebufferIntegerColorSampleCount(4)), - ) - }; - let helper = |error: Error| CaseError::Helper { - call: "rt6_fill_uint4: new_render_pipeline_state".into(), - error: Box::new(error), - }; - let sent_back = "rt6_fill_uint4: new_render_pipeline_state: helper refused RasterSampleCount; \ - needs AnyOf([[Property(FramebufferIntegerColorSampleCount(4))]])"; - for error in [ - Error::Unsupported(unsupported()), - Error::Compile(metal2vulkan::error::Error::Unsupported(unsupported())), - ] { - match stop(helper(error), false) { - Stop::Gap(gap) => assert_eq!(gap, sent_back), - Stop::Refused(refused) => panic!("not sent back: {}", refused.error), - Stop::Error(error) => panic!("not sent back: {error}"), - } - } - assert!(matches!( - stop(helper(Error::Unsupported(unsupported())), true), - Stop::Error(ExecutorError::NotSupported(_)) - )); - let own = CaseError::Runtime { - call: "new_render_pipeline_state".into(), - error: Box::new(Error::Unsupported(unsupported())), - }; - assert!(matches!( - stop(own, false), - Stop::Error(ExecutorError::NotSupported(_)) - )); -} - -/// A public kernel case of the runtime's families runs through the runtime path on the device the -/// cfg selects, under the validation layer with the executor's settings: its output is Metal's, -/// its row records the runtime and the device's identity, and what it executed is what the -/// executor's own context compiles and runs for it: the same artifact digest, the same SPIR-V, -/// census, and comparison class, and the same output. -#[cfg(any(m2v_gpu, m2v_cpu_icd))] -#[test] -fn a_public_kernel_case_runs_through_the_runtime_as_the_executor_compiles_it() { - runs_as_the_executor_compiles_it("saturating-halving-and-wide-product-integers-at-their-edges"); -} - -/// A public kernel case of function constant values runs through the runtime path, its function -/// specialized with the case's values, as -/// [`a_public_kernel_case_runs_through_the_runtime_as_the_executor_compiles_it`] runs its case. -#[cfg(any(m2v_gpu, m2v_cpu_icd))] -#[test] -fn a_kernel_of_function_constants_runs_through_the_runtime_as_the_executor_compiles_it() { - runs_as_the_executor_compiles_it("fold-a-zero-function-constant-gate"); -} - -/// A public kernel case of visible-function tables runs through the runtime path, two tables of -/// its authored sizes bound at their buffer indices, each entry null, as -/// [`a_public_kernel_case_runs_through_the_runtime_as_the_executor_compiles_it`] runs its case. -#[cfg(any(m2v_gpu, m2v_cpu_icd))] -#[test] -fn a_kernel_of_function_tables_runs_through_the_runtime_as_the_executor_compiles_it() { - runs_as_the_executor_compiles_it("two-bound-visible-tables-answer-null-and-size"); -} - -/// A public kernel case of stage inputs runs through the runtime path, its pipeline state of the -/// oracle's stage-input descriptor and its encoder's stage-in region the oracle's, as -/// [`a_public_kernel_case_runs_through_the_runtime_as_the_executor_compiles_it`] runs its case. -#[cfg(any(m2v_gpu, m2v_cpu_icd))] -#[test] -fn a_kernel_of_stage_inputs_runs_through_the_runtime_as_the_executor_compiles_it() { - runs_as_the_executor_compiles_it("kernel-stage-input-word"); -} - -/// Public kernel cases of out-of-bounds targets no guard holds run through the runtime path: reads -/// and writes past a texture, and loads and stores past a threadgroup allocation, as -/// [`a_public_kernel_case_runs_through_the_runtime_as_the_executor_compiles_it`] runs its case, -/// each target's containment decided before the commit as the executor's own context decides it. -#[cfg(any(m2v_gpu, m2v_cpu_icd))] -#[test] -fn unguarded_out_of_bounds_kernels_run_as_the_executor_compiles_them() { - runs_as_the_executor_compiles_it("reads-and-writes-past-a-texture"); - runs_as_the_executor_compiles_it("loads-and-stores-past-a-threadgroup-allocation"); -} - -/// Public kernel cases of guarded out-of-bounds targets run through the runtime path, each target -/// placed in a heap of its own between guards: a storage buffer, a buffer reached by its address, a -/// loaded pointer's buffer with a reach before it, a stage input's buffer, and a texture buffer, as -/// [`a_public_kernel_case_runs_through_the_runtime_as_the_executor_compiles_it`] runs its case: the -/// guard counts and their verdict are the executor's. A device that leaves a target uncontained -/// (MoltenVK's robust buffer forms) refuses the case on both paths, each refusal recording the same -/// compile. -#[cfg(any(m2v_gpu, m2v_cpu_icd))] -#[test] -fn guarded_out_of_bounds_kernels_run_as_the_executor_compiles_them() { - for name in [ - "loads-and-stores-past-a-device-buffer", - "loads-and-stores-past-a-device-buffer-by-its-address", - "loads-and-stores-past-a-loaded-pointers-buffer-with-a-reach-before-it", - "kernel-stage-input-fetches-past-its-buffer", - "reads-and-writes-past-a-texture-buffer", - ] { - runs_as_the_executor_compiles_it(name); - } -} - -/// A public tile kernel runs through the runtime path, dispatched on a render encoder of its pass -/// as the case runner dispatches it (`runtime_case::encoded_tile`), its output an attachment over -/// two rows of 16x16 tiles whose last column and row are partial, as -/// [`a_public_kernel_case_runs_through_the_runtime_as_the_executor_compiles_it`] runs its case. -#[cfg(any(m2v_gpu, m2v_cpu_icd))] -#[test] -fn a_tile_kernel_runs_through_the_runtime_as_the_executor_compiles_it() { - runs_as_the_executor_compiles_it("tile-grid-float-attachment-doubles-each-pixel-once"); -} - -/// A public vertex case fetching an attribute past its vertex buffer runs through the runtime -/// path, the buffer placed in a heap of its own between guards, as -/// [`a_public_kernel_case_runs_through_the_runtime_as_the_executor_compiles_it`] runs its case: the -/// draw's containment is decided before the commit as the executor decides it, its guard counts are -/// the executor's, and its reads past the buffer, which reach the heap's bytes, match Metal's under -/// the cause the row records. A device that leaves the fetch uncontained (MoltenVK's vertex input) -/// refuses the case on both paths, each refusal recording the same compile. -#[cfg(any(m2v_gpu, m2v_cpu_icd))] -#[test] -fn a_vertex_buffer_target_runs_as_the_executor_compiles_it() { - runs_as_the_executor_compiles_it("vertex-attribute-fetches-past-its-vertex-buffer"); -} - -/// The public indexed draws whose indices run past their index buffer run through the runtime -/// path, each buffer placed in a heap of its own between guards, as -/// [`a_public_kernel_case_runs_through_the_runtime_as_the_executor_compiles_it`] runs its case: the -/// draw contains its positions past the buffer as the executor's containment states (its execution -/// record's `index_padding`: a copy of its indices padded with zeros, on every device), its facts -/// and guard counts are the executor's, and its output is the executor's, which matches Metal's. -#[cfg(any(m2v_gpu, m2v_cpu_icd))] -#[test] -fn index_buffer_targets_run_as_the_executor_compiles_them() { - for name in [ - "indexed-draw-reads-past-its-uint32-index-buffer", - "indexed-draw-reads-past-its-uint16-index-buffer-from-an-offset", - ] { - runs_as_the_executor_compiles_it(name); - } -} - -/// Public cases of indirect render commands run through the runtime path, as -/// [`a_public_kernel_case_runs_through_the_runtime_as_the_executor_compiles_it`] runs its case: a -/// kernel that encodes render commands into a command buffer of the oracle's render descriptor -/// (`DRAW`), read back as the runtime decodes them; a kernel's and a vertex function's argument -/// buffers holding a render template's state beside a compute template's, each made with -/// `support_indirect_command_buffers` (`template_states`); and render commands a kernel or a -/// vertex function wrote, with the host's, executed after it in a render encoder of the oracle's -/// pass, their buffers the host's or inherited. -#[cfg(any(m2v_gpu, m2v_cpu_icd))] -#[test] -fn render_commands_and_render_states_run_as_the_executor_compiles_them() { - for name in [ - "encode-render-commands-beside-output", - "pipeline-states-beside-the-data-of-two-stages", - "pipeline-states-beside-the-data-a-vertex-reads", - "gpu-encoded-draws-run-the-host-encoded-vertex-buffers", - "gpu-encoded-draws-run-the-inherited-vertex-buffers", - "gpu-encoded-vertex-buffers-run-the-host-encoded-draws", - ] { - runs_as_the_executor_compiles_it(name); - } -} - -/// The executor's own context runs an execution of render commands the GPU may write where the -/// runtime does, by the draw replay rules both share: on the device, one indirect draw per command -/// of the parent template's draw replay variant (`compute::draw_replay`; its vertex function -/// writes memory, so the commands' points do not merge), where a kernel or a vertex function writes -/// the draws or their buffers, the commands' own or the encoder's where they inherit them (the -/// preprocess reads the parent's buffers). The environment names the path each execution took -/// (`command_replay`), each output Metal's; the census of each is held to the runtime path's by -/// `render_commands_and_render_states_run_as_the_executor_compiles_them`. -#[cfg(any(m2v_gpu, m2v_cpu_icd))] -#[test] -fn the_executor_draws_gpu_written_render_commands_where_the_runtime_does() { - use crate::candidate::tests::compile_worker; - use crate::candidate::tests::engine_compute::BACKEND; - let root = metal2vulkan_devtools::validation_dir().join("corpus"); - let device = crate::gpu::TEST_DEVICE; - let store = CorpusStore::new(&root); - let cases = store.read_all_cases().unwrap(); - for (name, path) in [ - ( - "gpu-encoded-draws-run-the-host-encoded-vertex-buffers", - "device-draws", - ), - ( - "gpu-encoded-vertex-buffers-run-the-host-encoded-draws", - "device-draws", - ), - ( - "gpu-encoded-draws-run-the-inherited-vertex-buffers", - "device-draws", - ), - ] { - let case = cases - .iter() - .find(|case| case.name == name) - .expect("the committed public case") - .clone(); - let metal = metal_output(&store, &case).unwrap(); - let admitted = admit(&root, case, ExecutionRequest::EngineCandidate { device }).unwrap(); - let prepared = super::super::prepare_case(device, admitted).unwrap(); - let on_context = super::super::run_on_context(&prepared, BACKEND, compile_worker()) - .result - .unwrap_or_else(|error| panic!("{name}: {error}")); - assert_eq!(on_context.output, metal, "{name}: the executor's output"); - assert_eq!( - on_context.environment["command_replay"], - serde_json::json!([path]), - "{name}" - ); - } -} - -/// Public cases whose command buffers execute ranges of two or more compute commands, a kernel's -/// and the host's, run through the runtime path and on the executor's own context (its device -/// replay), each output Metal's. Where the context enables `VK_EXT_device_generated_commands`, the -/// executor runs each range as one command buffer's executions, one after another, as the runtime -/// does: on RADV before 26.2 the driver's own preprocessing of every execution after the first ran -/// the shader the one before bound last, and the device faulted -/// (`RuntimeDriverDefect::ImplicitPreprocessAfterExecutionSet`), so both preprocess the -/// executions apart there. The rows' artifacts are not compared: the executor's digests what it -/// compiled for the commands, and the runtime path's records no digest (as -/// [`runs_as_the_executor_compiles_it`] states). -#[cfg(any(m2v_gpu, m2v_cpu_icd))] -#[test] -fn compute_command_ranges_run_on_both_paths_as_metal_ran_them() { - use crate::candidate::tests::compile_worker; - use crate::candidate::tests::engine_compute::BACKEND; - let root = metal2vulkan_devtools::validation_dir().join("corpus"); - let device = crate::gpu::TEST_DEVICE; - let store = CorpusStore::new(&root); - let cases = store.read_all_cases().unwrap(); - for name in [ - "execute-two-gpu-encoded-template-dispatches", - "gpu-encoded-buffers-keep-the-host-encoded-dispatches", - "gpu-encoded-ragged-grids-replay-with-the-inherited-pipeline-and-buffers", - "host-encoded-over-limit-and-ragged-dispatches-in-two-command-buffers", - ] { - let case = cases - .iter() - .find(|case| case.name == name) - .expect("the committed public case") - .clone(); - assert!(case.out_of_bounds.is_none(), "{name}"); - let metal = metal_output(&store, &case).unwrap(); - let admitted = admit(&root, case, ExecutionRequest::EngineCandidate { device }).unwrap(); - let prepared = super::super::prepare_case(device, admitted).unwrap(); - assert_eq!(route(&prepared), Route::Runtime, "{name}"); - let RuntimeOutcome::Ran(attempt) = run(&prepared, BACKEND) else { - panic!("{name}: the runtime raised a gap"); - }; - let ran = attempt - .result - .unwrap_or_else(|error| panic!("{name}: {error}")); - assert_eq!(ran.output, metal, "{name}: the runtime path's output"); - let on_context = super::super::run_on_context(&prepared, BACKEND, compile_worker()) - .result - .unwrap_or_else(|error| panic!("{name}: {error}")); - // Which replay ran each command buffer the case executes, for the lane's record. - eprintln!( - "{name}: the executor's command replay {}", - on_context.environment["command_replay"] - ); - assert_eq!(on_context.output, metal, "{name}: the executor's output"); - } -} - -/// A public render case runs through the runtime path, drawn as the case runner draws it -/// (`runtime_case::encoded_render`), as -/// [`a_public_kernel_case_runs_through_the_runtime_as_the_executor_compiles_it`] runs its case: -/// the artifact digest and the SPIR-V of every stage are the executor's. -#[cfg(any(m2v_gpu, m2v_cpu_icd))] -#[test] -fn a_render_case_runs_through_the_runtime_as_the_executor_compiles_it() { - runs_as_the_executor_compiles_it("authored-fragment-constant-color"); -} - -/// A public multisampled render case runs through the runtime path, its target filled and its -/// output read sample by sample, in a pass every venue runs on the runtime (`RGBA8Unorm` at 4x -/// without stencil: an integer target's 4x is one RADV lacks, and the runtime sends a -/// stencil-tested pass back to the executor on NVIDIA), as -/// [`a_public_kernel_case_runs_through_the_runtime_as_the_executor_compiles_it`] runs its case. -#[cfg(any(m2v_gpu, m2v_cpu_icd))] -#[test] -fn a_multisampled_render_case_runs_through_the_runtime_as_the_executor_compiles_it() { - runs_as_the_executor_compiles_it("sample-mask-out-4x"); -} - -/// The committed public case `name` through the runtime path and through the executor's own -/// context, compared (the tests above). -#[cfg(any(m2v_gpu, m2v_cpu_icd))] -fn runs_as_the_executor_compiles_it(name: &str) { - use crate::candidate::engine::RefusedOn; - use crate::candidate::tests::compile_worker; - use crate::candidate::tests::engine_compute::BACKEND; - let root = metal2vulkan_devtools::validation_dir().join("corpus"); - let device = crate::gpu::TEST_DEVICE; - let store = CorpusStore::new(&root); - let case = store - .read_all_cases() - .unwrap() - .into_iter() - .find(|case| case.name == name) - .expect("the committed public case"); - let metal = metal_output(&store, &case).unwrap(); - let authored = case.clone(); - let executor = match case.stage { - crate::case::Stage::Kernel => "engine-runtime-compute", - // A mesh draw is a render encoder's draw (`runtime_case::encoded_mesh`). - crate::case::Stage::Vertex - | crate::case::Stage::Fragment - | crate::case::Stage::Object - | crate::case::Stage::Mesh => "engine-runtime-render", - }; - let admitted = admit(&root, case, ExecutionRequest::EngineCandidate { device }).unwrap(); - let prepared = super::super::prepare_case(device, admitted).unwrap(); - assert_eq!(route(&prepared), Route::Runtime); - let RuntimeOutcome::Ran(attempt) = run(&prepared, BACKEND) else { - panic!("{name}: the runtime raised a gap"); - }; - let on_context = super::super::run_on_context(&prepared, BACKEND, compile_worker()); - let run = match attempt.result { - Ok(run) => run, - // A refusal after the dispatch took its pipeline (a target the device leaves - // uncontained) is the executor's, and records the same compile. - Err( - error @ ExecutorError::NotSupported(crate::check::admission::NotSupported::Uncontained( - _, - )), - ) => { - assert_eq!(on_context.result.err(), Some(error), "{name}"); - let artifact = |refused_on: Option| { - refused_on - .and_then(|opened| opened.artifact) - .unwrap_or_else(|| panic!("{name}: the refusal records no artifact")) - }; - let recorded = artifact(attempt.refused_on); - assert!(recorded.sha256.is_some(), "{name}: the refusal's digest"); - assert_eq!(recorded, artifact(on_context.refused_on), "{name}"); - return; - } - Err(error) => panic!("{name}: {error}"), - }; - match &authored.out_of_bounds { - None => assert_eq!(run.output, metal), - // A case of out-of-bounds targets is judged by their containment. - Some(_) => assert!( - crate::executor_contract::out_of_bounds::matches( - &authored, - &run.comparison, - &metal, - &run.output, - Some( - run.census - .out_of_bounds - .as_ref() - .expect("the run's containment facts") - ), - ), - "the run's output and containment match Metal's" - ), - } - assert_eq!(run.environment["executed_by"], "runtime"); - assert_eq!(run.environment["executor"], executor); - assert!( - run.environment["runtime_degrades"].is_array(), - "the row records the run's degrade notices" - ); - assert!(crate::c3::DeviceIdentity::recorded(&run.environment).is_some()); - assert_eq!( - run.census.leg, - Some(crate::candidate::requested_leg()), - "the census records the process's leg" - ); - // A case whose command buffers execute has no digest: the authored compile census cannot - // compile what the runtime ran for their commands (`record_uncovered`). - let artifact = run.census.artifact.clone().expect("the run's artifact"); - let executes = authored - .command_buffers - .iter() - .any(|resource| resource.execute.is_some()); - assert_eq!( - artifact.sha256.is_some(), - !executes, - "{name}: the run's artifact has a digest exactly when no command buffer executes" - ); - - let on_context = on_context - .result - .unwrap_or_else(|error| panic!("{name}: {error}")); - assert_eq!(run.census.artifact, on_context.census.artifact); - assert_eq!(run.spv_sha256, on_context.spv_sha256); - assert_eq!(run.census.modules, on_context.census.modules); - assert_eq!(run.census.device, on_context.census.device); - assert_eq!(run.comparison, on_context.comparison); - match (&run.census.out_of_bounds, &on_context.census.out_of_bounds) { - // A fixed-function fetch past a vertex buffer in a heap of its own reads the heap's - // bytes where the executor's allocation of its own reads zero: the facts are the executor's - // but for the cause the runtime path records, and each output matches Metal's under its own - // facts. - (Some(ran), Some(executor)) if ran.targets.iter().any(|t| t.read_cause.is_some()) => { - use crate::executor_contract::out_of_bounds::{Medium, ReadCause, TargetRun}; - for target in &ran.targets { - let fetched = target.mechanism.medium == Medium::VertexInput; - assert_eq!( - target.read_cause, - fetched.then_some(ReadCause::HeapBoundRange), - "{name}: {target:?}" - ); - } - let uncaused = OutOfBoundsRun { - targets: ran - .targets - .iter() - .map(|target| TargetRun { - read_cause: None, - ..target.clone() - }) - .collect(), - }; - assert_eq!(&uncaused, executor, "{name}"); - // What the fetch past the buffer read on this device, for the lane's record. - eprintln!( - "{name}: the runtime path's output {:02x?}, the executor's {:02x?}", - run.output, on_context.output - ); - assert!( - crate::executor_contract::out_of_bounds::matches( - &authored, - &on_context.comparison, - &metal, - &on_context.output, - Some(executor), - ), - "{name}: the executor's output matches Metal's" - ); - } - (ran, executor) => { - assert_eq!(ran, executor, "{name}"); - assert_eq!(run.output, on_context.output, "{name}"); - } - } -} - -/// The runtime path's case runner calls through a kernel case's visible-function tables: each -/// table of its authored size, each authored entry the handle the pipeline state gives the -/// function it holds among the case's linked modules, every other entry null, with the kernel, -/// table and words of the executor context's own check (`engine_compute`'s -/// `a_kernel_calls_through_its_visible_function_table`): no committed public case holds a function -/// in a table. The tables' bytes the row's artifact records are the executor's: its compile's -/// handles of the same linked functions, encoded. An entry whose function no linked module holds -/// cannot run. -#[cfg(any(m2v_gpu, m2v_cpu_icd))] -#[test] -fn the_runtime_path_calls_the_functions_its_tables_hold() { - use crate::acceptance::compile_pipeline; - use crate::acceptance::LinkedLibrary; - use crate::candidate::engine::tables::{FunctionTable, TableFunction}; - use crate::candidate::engine::{compute_request, compute_tables, LinkedModule}; - use crate::candidate::runtime_case::{ - commit_case, compute_descriptor, linked_functions, open_device, validated_options, - visible_function_tables, Messages, ScratchCache, - }; - use crate::candidate::tests::engine_compute::case; - use metal2vulkan::bind::Dispatch; - use metal2vulkan_devtools::{engine_dir, llvm_assemble}; - use metal2vulkan_runtime::{CommandBufferStatus, PipelineOptions}; - use std::time::Duration; - let caller = llvm_assemble(&engine_dir().join("visible_table_caller.ll")).unwrap(); - let functions = llvm_assemble(&engine_dir().join("visible_table_functions.ll")).unwrap(); - let modules = [LinkedModule { - module_sha256: "functions".into(), - bitcode: functions, - library: LinkedLibrary { - functions: ["table_add", "table_mul", "table_sub"] - .map(str::to_owned) - .to_vec(), - }, - }]; - const THREADS: u32 = 12; - let mut kernel = case( - "visible_table_dispatch", - vec![0; 4 * THREADS as usize], - Dispatch::Threads { - threads: [THREADS, 1, 1], - threads_per_group: [THREADS, 1, 1], - }, - ); - let entry = |function: &str| TableFunction { - module_sha256: "functions".into(), - function: function.into(), - }; - kernel.function_tables = BTreeMap::from([( - 1, - FunctionTable { - size: 4, - entries: BTreeMap::from([ - (0, entry("table_add")), - (1, entry("table_mul")), - (3, entry("table_sub")), - ]), - }, - )]); - let expected = (0..THREADS) - .flat_map(|tid| { - match tid % 4 { - 0 => tid + 3, - 1 => tid * 3, - 2 => 0xffff_fffd, - _ => tid.wrapping_sub(3), - } - .to_le_bytes() - }) - .collect::>(); - let messages = Messages::default(); - let cache = ScratchCache::new().unwrap(); - { - let options = validated_options(&messages, cache.path()); - let device = open_device(crate::gpu::TEST_DEVICE, options).unwrap(); - let function = device - .new_library_with_air(&caller) - .unwrap() - .new_function_with_name_constant_values("visible_table_dispatch", &kernel.constants) - .unwrap(); - let linked = linked_functions(&device, &modules, &kernel.constants).unwrap(); - let descriptor = compute_descriptor(&function, linked.functions.clone(), &kernel); - let pipeline = device - .new_compute_pipeline_state(&descriptor, &PipelineOptions::default()) - .unwrap(); - let tables = visible_function_tables(&pipeline, &kernel, &linked).unwrap(); - let words = tables.words; - let none = BTreeMap::new(); - let committed = commit_case( - &device, - &kernel, - &none, - &BTreeMap::new(), - &pipeline, - tables.tables, - ) - .unwrap(); - committed - .command_buffer - .wait_until_completed_for(Duration::from_secs(60)) - .unwrap(); - assert_eq!( - committed.command_buffer.status(), - CommandBufferStatus::Completed - ); - assert_eq!(committed.output(&kernel).unwrap(), expected); - - // The words the artifact records are the executor's: its compile's handles, encoded. - let [execution] = committed.executions.as_slice() else { - panic!("one dispatch"); - }; - let (request, libraries) = compute_request( - &crate::acceptance::retained(&caller), - &modules, - &kernel, - execution.shape(), - ); - let libraries = libraries - .iter() - .map(|library| library.bitcode().unwrap()) - .collect::>(); - let libraries = libraries.iter().map(Vec::as_slice).collect::>(); - let compiled = compile_pipeline(&libraries, &request, device.compile_device(), None) - .unwrap_or_else(|error| panic!("{error:?}")); - assert_eq!( - words, - compute_tables(&kernel, &modules, &compiled.handles).unwrap() - ); - - let table = kernel.function_tables.get_mut(&1).unwrap(); - table.entries.insert(2, entry("table_half")); - let unlinked = match visible_function_tables(&pipeline, &kernel, &linked) { - Ok(_) => panic!("a table of an entry no linked module holds"), - Err(error) => error, - }; - assert!(matches!(unlinked, CaseError::Case(_)), "{unlinked}"); - } - layer_reported_nothing_at_all(&messages); -} - -/// The engine's candidate draws each owned object and mesh case through the runtime's mesh path -/// (`runtime_case::encoded_mesh`) and reads what Metal drew ([`crate::mesh_cases`]): a mesh grid -/// through its fragment partner, an object function's payload and grid through its mesh and -/// fragment partners, a mesh function's device write with rasterization off, a mesh grid through -/// the generated observer fragment in its fragment partner's place, an object function's launch -/// through the generated launch observer and its observer fragment, and a mesh function's payload -/// through the generated object function that writes it (the four payload cases the Metal -/// executor's test draws, one of them on a GPU only, for the reason the list states), one read past -/// the mesh function's own payload type within the object function's. A device without -/// `VK_EXT_mesh_shader` draws through the runtime's emulation, whose notice the row records, and -/// a device with it records none. -#[cfg(any(m2v_gpu, m2v_cpu_icd))] -#[test] -fn mesh_cases_draw_through_the_runtime_as_metal_drew_them() { - use crate::candidate::tests::engine_compute::BACKEND; - let root = metal2vulkan_devtools::validation_dir().join("corpus"); - let device = crate::gpu::TEST_DEVICE; - let mut emulated = BTreeSet::new(); - for fixture in [ - crate::mesh_cases::grid(), - crate::mesh_cases::object(), - crate::mesh_cases::device_write(), - crate::mesh_cases::observed(), - crate::mesh_cases::launched(), - crate::mesh_cases::payload(), - crate::mesh_cases::payload_barrier(), - crate::mesh_cases::payload_outputs(), - // On a GPU only: its mesh function (`mesh_order_mesh`, and `mesh_order_solo` without an - // object stage alike) aborts the CPU ICD's compiler ("Cannot emit physreg copy - // instruction"), docs/FAST-PATHS.md's known gaps. - #[cfg(m2v_gpu)] - crate::mesh_cases::payload_order(), - ] { - let name = fixture.case.name.clone(); - let admitted = admit( - &root, - fixture.case, - ExecutionRequest::EngineCandidate { device }, - ) - .unwrap_or_else(|error| panic!("{name}: {error}")); - let prepared = super::super::prepare_case(device, admitted) - .unwrap_or_else(|error| panic!("{name}: {error}")); - assert_eq!(route(&prepared), Route::Runtime, "{name}"); - let RuntimeOutcome::Ran(attempt) = run(&prepared, BACKEND) else { - panic!("{name}: the runtime raised a gap"); - }; - let run = attempt - .result - .unwrap_or_else(|error| panic!("{name}: {error}")); - assert_eq!(run.output, fixture.metal, "{name}"); - assert_eq!(run.environment["executed_by"], "runtime", "{name}"); - assert_eq!( - run.environment["executor"], "engine-runtime-render", - "{name}" - ); - let notices = run.environment["runtime_degrades"] - .as_array() - .unwrap_or_else(|| panic!("{name}: the row records the run's degrade notices")); - eprintln!("{name}: degrade notices {notices:?}"); - let emulation = metal2vulkan_runtime::Degradation::EmulatedMeshDraws.code(); - emulated.insert(notices.iter().any(|code| code == emulation)); - } - // One device draws every case alike: natively, or through the emulation each time. - assert_eq!(emulated.len(), 1, "{emulated:?}"); -} diff --git a/crates/metal2vulkan-validation/src/candidate/engine/tests.rs b/crates/metal2vulkan-validation/src/candidate/engine/tests.rs index be07ad45f..28dfc05fb 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/tests.rs @@ -1954,16 +1954,11 @@ fn checked_render_replay_cases_prepare_their_render_template() { "{name}" ); assert_eq!( - prepared - .templates() - .unwrap() - .keys() - .copied() - .collect::>(), + prepared.templates.keys().copied().collect::>(), [1], "{name}" ); - let TemplateCase::Render(template) = &prepared.templates().unwrap()[&1].mapped else { + let TemplateCase::Render(template) = &prepared.templates[&1].mapped else { panic!("{name}: the parent pipeline is a render template"); }; assert!(template.fragment.is_none(), "{name}"); @@ -2039,7 +2034,7 @@ fn committed_compute_replay_cases_register_their_templates_variant() { panic!("a kernel case"); }; assert_eq!( - replay_variants(compute, prepared_gpu.templates().unwrap()).unwrap(), + replay_variants(compute, &prepared_gpu.templates).unwrap(), edges(1) ); let name = "gpu-encoded-buffers-keep-the-host-encoded-dispatches"; @@ -2048,7 +2043,7 @@ fn committed_compute_replay_cases_register_their_templates_variant() { panic!("{name}: a kernel case"); }; assert_eq!( - replay_variants(compute, host.templates().unwrap()).unwrap(), + replay_variants(compute, &host.templates).unwrap(), [variant(2, [8, 1, 1])], "{name}" ); @@ -2075,7 +2070,7 @@ fn committed_compute_replay_cases_register_their_templates_variant() { expected.extend(edges(2)); expected.sort_by_key(|v| v.threads_per_threadgroup); assert_eq!( - replay_variants(&compute, prepared.templates.as_ref().unwrap()).unwrap(), + replay_variants(&compute, &prepared.templates).unwrap(), expected, "a command whose action the producer encodes registers the template's edges" ); @@ -2101,17 +2096,16 @@ fn committed_compute_replay_cases_register_their_templates_variant() { ]; expected.sort_by_key(|v| v.threads_per_threadgroup); assert_eq!( - replay_variants(&compute, prepared.templates.as_ref().unwrap()).unwrap(), + replay_variants(&compute, &prepared.templates).unwrap(), expected ); } -/// A template the executor's own context cannot replay refuses a case only on that context. The -/// committed kernel case whose patch draws run a post-tessellation template prepares, routes to the -/// runtime, which replays every template through its own pipeline states, and keeps the context's -/// refusal for a run the runtime hands back. +/// A template the executor's context cannot replay refuses its case as it is prepared, by the +/// requirement the vocabulary names: the committed kernel case whose patch draws run a +/// post-tessellation template. #[test] -fn a_template_only_the_runtime_replays_refuses_only_on_the_executors_context() { +fn a_template_the_context_cannot_replay_refuses_its_case_by_its_requirement() { let root = metal2vulkan_devtools::validation_dir().join("corpus"); let name = "patch-draws-a-kernel-encodes-at-factor-scales-and-the-host-encodes"; let case = CorpusStore::new(&root) @@ -2123,12 +2117,12 @@ fn a_template_only_the_runtime_replays_refuses_only_on_the_executors_context() { let device = DeviceType::Cpu; let admitted = admit(&root, case, ExecutionRequest::EngineCandidate { device }) .unwrap_or_else(|error| panic!("{name}: {error}")); - let prepared = prepare_case(device, admitted).unwrap_or_else(|error| panic!("{name}: {error}")); - assert_eq!(runtime_run::route(&prepared), runtime_run::Route::Runtime); - let refused = prepared.templates().err().expect("the context's refusal"); + let refused = prepare_case(device, admitted) + .err() + .expect("the context's refusal"); assert!( - matches!(&refused, ExecutorError::NotSupported(NotSupported::NotImplemented(why)) - if why.contains("is not a rasterization-disabled vertex function")), + matches!(&refused, ExecutorError::NotSupported(NotSupported::Requirements(requirements)) + if requirements.contains(&ToolingRequirement::ReplayedTemplateResources)), "{refused}" ); } @@ -2210,7 +2204,7 @@ fn k14d_replay_cases_register_their_regions_variants() { let Mapped::Compute(compute) = &prepared.mapped else { panic!("{name}: a kernel case"); }; - replay_variants(compute, prepared.templates().unwrap()).unwrap() + replay_variants(compute, &prepared.templates).unwrap() }; let variants = |length: u32, sizes: &[[u32; 3]]| -> Vec { let mut lengths = [0u32; 31]; @@ -2398,9 +2392,10 @@ fn replay_templates_map_only_the_families_executed_commands_run() { max_mesh_buffer_bind_count: 0, support_dynamic_attribute_stride: false, }); - let error = replay_templates(&checked).err().unwrap().to_string(); + let error = replay_templates(&checked).err().unwrap(); assert!( - error.contains("is not a rasterization-disabled vertex function"), + matches!(&error, ExecutorError::NotSupported(NotSupported::Requirements(requirements)) + if requirements.contains(&ToolingRequirement::ReplayedTemplateResources)), "{error}" ); } diff --git a/crates/metal2vulkan-validation/src/candidate/platform.rs b/crates/metal2vulkan-validation/src/candidate/platform.rs index 810a34a54..0e0b909c8 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform.rs @@ -6,7 +6,9 @@ mod buffers; mod compute; mod device; mod enables; +mod generated_commands; mod graphics_pipeline; +mod ignored_drivers; mod loader_word; mod multisample; mod pipeline; @@ -21,7 +23,6 @@ pub use compute::execute_engine; pub use compute::opened_worker_device; pub use device::{capture_formats, echo_validation_messages, venue_check}; pub use device::{requested_leg, run_robustness_off}; -pub(crate) use device::{runtime_restriction, Restricting, RuntimeRestriction}; pub use profiles::{requested_restriction, restrict_devices_to}; pub use render::execute_engine_render; pub use runtime_probe::probe_runtime; diff --git a/crates/metal2vulkan-validation/src/candidate/platform/compute/device_replay/generated.rs b/crates/metal2vulkan-validation/src/candidate/platform/compute/device_replay/generated.rs index 2ce5e5c44..cf6a395d3 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/compute/device_replay/generated.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/compute/device_replay/generated.rs @@ -15,22 +15,22 @@ //! barrier (as K14c's between commands), the initial pipeline, zeroed push constants (the tokens //! write every byte), and `vkCmdExecuteGeneratedCommandsEXT` over its sequences with the count //! the preprocess wrote ([`record_executions`]); -//! - where the driver's own preprocessing of an execution recorded after another runs the wrong -//! shader, as the runtime decides it (`generated_commands::preprocess_apart`, -//! `RuntimeDriverDefect::ImplicitPreprocessAfterExecutionSet`), the commands layout is made for -//! explicit preprocessing, every command's execution is preprocessed -//! (`vkCmdPreprocessGeneratedCommandsEXT`) before the first runs, a barrier orders those writes -//! before the executions, and each runs preprocessed: no preprocessing follows an execution. +//! - the commands layout is made for explicit preprocessing, every command's execution is +//! preprocessed (`vkCmdPreprocessGeneratedCommandsEXT`) before the first runs, a barrier orders +//! those writes before the executions, and each runs preprocessed: no preprocessing follows an +//! execution, a form that runs right on every driver. use super::*; -use metal2vulkan::bind::GeneratedReplay; -use metal2vulkan_runtime::generated_commands::{ +use crate::candidate::platform::generated_commands::{ Commands, Execution, ExecutionSetCreateInfo, ExecutionSetPipelineInfo, ExecutionSetToken, GeneratedCommandsInfo, Handle, LayoutCreateInfo, LayoutToken, MemoryRequirementsInfo, PushConstantToken, WriteExecutionSetPipeline, EXECUTION_SET_PIPELINES, INDIRECT_BINDABLE, PREPROCESS_BUFFER, PREPROCESS_WRITE, TOKEN_DISPATCH, TOKEN_EXECUTION_SET, TOKEN_PUSH_CONSTANT, }; -pub(super) use metal2vulkan_runtime::generated_commands::{PREPROCESS_READ, PREPROCESS_STAGE}; +pub(super) use crate::candidate::platform::generated_commands::{ + PREPROCESS_READ, PREPROCESS_STAGE, +}; +use metal2vulkan::bind::GeneratedReplay; use std::collections::btree_map::Entry; use std::time::Duration; @@ -46,9 +46,6 @@ pub(super) struct Generated<'c> { pipelines: Vec, execution_set: Handle, commands_layout: Handle, - /// Whether the commands layout is made for explicit preprocessing: every command's execution - /// is preprocessed apart before the first runs ([`record_executions`]). - explicit: bool, /// The preprocess memory's buffer and allocation ([`Generated::reserve_preprocess`]). preprocess: Option<(vk::Buffer, vk::DeviceMemory)>, /// Each command's preprocess memory, by slot: its address and size (`(0, 0)` where the @@ -117,7 +114,6 @@ impl<'c> Generated<'c> { pipelines: Vec::with_capacity(prepared.len()), execution_set: 0, commands_layout: 0, - explicit: context.preprocesses_generated_commands_apart(), preprocess: None, reserved: Vec::new(), sets: Vec::new(), @@ -184,10 +180,6 @@ impl<'c> Generated<'c> { LayoutToken::new(TOKEN_DISPATCH, std::ptr::null(), layout.dispatch_offset()), ]; let info = LayoutCreateInfo::new(layout.stride, generated.layout.pipeline_layout, &tokens); - let info = match generated.explicit { - true => info.explicitly_preprocessed(), - false => info, - }; // SAFETY: `info`, its tokens, and their data are live for the call. generated.commands_layout = unsafe { commands.create_commands_layout(&info) } .map_err(|error| fail(format!("create the indirect commands layout: {error}")))?; @@ -351,9 +343,9 @@ fn bindable_pipeline( /// initial pipeline, zeroed push constants (the tokens write every byte of them), and the /// command's `vkCmdExecuteGeneratedCommandsEXT` over its sequences in the scratch at /// `scratch_address`, with the count the preprocess wrote and its own preprocess memory. A -/// command that starts no segment has the count 0: its execution runs nothing. Where the layout -/// is made for explicit preprocessing ([`Generated::explicit`]), the initial pipeline and zeroed -/// push constants are bound first, every command's execution is preprocessed +/// command that starts no segment has the count 0: its execution runs nothing. The layout is made +/// for explicit preprocessing: the initial pipeline and zeroed push constants are bound first, +/// every command's execution is preprocessed /// (`vkCmdPreprocessGeneratedCommandsEXT`) with that state, a barrier orders the preprocessing's /// writes before the executions' preprocess and indirect reads, and each execution runs /// preprocessed. A range whose preprocess memory was not reserved for every command records @@ -425,30 +417,28 @@ pub(super) unsafe fn record_executions( &[], ); } - if generated.explicit { - bind(); - for slot in 0..layout.slots { - let execution = execution(slot); - let info = GeneratedCommandsInfo::new( - generated.execution_set, - generated.commands_layout, - &execution, - ); - generated.commands.preprocess(command, &info); - } - let preprocessed = vk::MemoryBarrier::default() - .src_access_mask(PREPROCESS_WRITE) - .dst_access_mask(vk::AccessFlags::INDIRECT_COMMAND_READ | PREPROCESS_READ); - device.cmd_pipeline_barrier( - command, - PREPROCESS_STAGE, - vk::PipelineStageFlags::DRAW_INDIRECT | PREPROCESS_STAGE, - vk::DependencyFlags::empty(), - &[preprocessed], - &[], - &[], + bind(); + for slot in 0..layout.slots { + let execution = execution(slot); + let info = GeneratedCommandsInfo::new( + generated.execution_set, + generated.commands_layout, + &execution, ); + generated.commands.preprocess(command, &info); } + let preprocessed = vk::MemoryBarrier::default() + .src_access_mask(PREPROCESS_WRITE) + .dst_access_mask(vk::AccessFlags::INDIRECT_COMMAND_READ | PREPROCESS_READ); + device.cmd_pipeline_barrier( + command, + PREPROCESS_STAGE, + vk::PipelineStageFlags::DRAW_INDIRECT | PREPROCESS_STAGE, + vk::DependencyFlags::empty(), + &[preprocessed], + &[], + &[], + ); for slot in 0..layout.slots { if slot > 0 { device.cmd_pipeline_barrier( @@ -468,10 +458,7 @@ pub(super) unsafe fn record_executions( generated.commands_layout, &execution, ); - match generated.explicit { - true => generated.commands.execute_preprocessed(command, &info), - false => generated.commands.execute(command, &info), - } + generated.commands.execute_preprocessed(command, &info); } } Ok(()) diff --git a/crates/metal2vulkan-validation/src/candidate/platform/compute/draw_replay.rs b/crates/metal2vulkan-validation/src/candidate/platform/compute/draw_replay.rs index 5f5c101a1..05625780c 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/compute/draw_replay.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/compute/draw_replay.rs @@ -33,9 +33,8 @@ //! variant's root-table holes, or the merged draw's two (`render::submit_replayed_draws`). //! - **After the wait**, the status: a replay fault refuses the row for the product's typed limits //! and fails it otherwise (`engine::replay_fault_verdict`), then the status verdict. The census -//! holds the variant once per execution: the one draw of it the runtime's execution record holds. -//! The artifact holds it as a pipeline the authored compile census does not compile, as the -//! runtime path's holds every pipeline its executed commands ran. +//! holds the variant once per execution. The artifact holds it as a pipeline the authored +//! compile census does not compile. use super::device_replay::{preprocess_objects, ReplayPath}; use super::replay::{bound_table, require_enabled, Executed}; diff --git a/crates/metal2vulkan-validation/src/candidate/platform/compute/replay.rs b/crates/metal2vulkan-validation/src/candidate/platform/compute/replay.rs index a541216a6..72d22c2df 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/compute/replay.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/compute/replay.rs @@ -146,19 +146,16 @@ pub(in crate::candidate::platform) fn execute_commands<'c, K: Ord + Copy + std:: )) })?, }, - // The runtime path executes them (`runtime_case::encoded_execution`); the - // executor's own context, which runs a case only where the runtime path has a gap, - // draws no index or patch buffer a record names. + // The executor's context draws no index or patch buffer a record names, and no + // mesh draw. Action::DrawIndexedPrimitives { .. } | Action::DrawPatches { .. } | Action::DrawIndexedPatches { .. } | Action::DrawMeshThreadgroups { .. } - | Action::DrawMeshThreads { .. } => { - return Err(fail( - "an indexed, patch or mesh draw, which only the runtime path executes" - .into(), - )) - } + | Action::DrawMeshThreads { .. } => return Err(fail( + "an indexed, patch or mesh draw, which the executor's context does not replay" + .into(), + )), }; let token = resolved .pipeline diff --git a/crates/metal2vulkan-validation/src/candidate/platform/device.rs b/crates/metal2vulkan-validation/src/candidate/platform/device.rs index 4bf262297..28e6f2fea 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/device.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/device.rs @@ -1,12 +1,12 @@ //! Vulkan device creation, enabled capabilities, and per-thread context lifetime. use super::enables::{self, Available, FeatureChain}; +use super::ignored_drivers::IgnoredDrivers; use super::loader_word::LoaderWord; use super::profiles::{ self, ActiveTool, ProfileRestriction, ProfilesLayer, ProfilesSettings, RestrictionError, PROFILES_LAYER, }; -use crate::candidate::runtime_case::IgnoredDrivers; use crate::coverage::{ExecutionClass, Leg}; use crate::gpu::wait::{self, SubmissionBackend}; use crate::gpu::DeviceType; @@ -460,8 +460,7 @@ pub fn echo_validation_messages() { /// What the validation layer reported that fails a row: every `ERROR` message, and every /// `WARNING` of the validation type. Bounded so a flood cannot grow without limit. The loader's /// own reports, at `vkCreateInstance`, of the driver manifests it ignored are the host's listing -/// of its drivers, not the run's work: they pass as the runtime lane's `Messages` passes them -/// ([`MessageSink::take`]). +/// of its drivers, not the run's work: they pass ([`MessageSink::take`]). /// /// But for one message about the driver: on a context whose opened profile takes /// `DriverDeviation::MetalVertexSimdgroups` ([`MessageSink::unadvertised_vertex`]), the layer's @@ -485,12 +484,19 @@ pub(super) struct MessageSink { /// one of them fails no row; set once the opened description is known. making: OnceLock>, /// Whether the opened device's driver runs the descriptor set layouts its - /// `vkGetDescriptorSetLayoutSupport` refuses, as the runtime makes them there - /// (`metal2vulkan_runtime::makes_layouts_past_support`: a heap's set 1 on MoltenVK), set once - /// the opened description is known. + /// `vkGetDescriptorSetLayoutSupport` refuses ([`makes_layouts_past_support`]: a heap's set 1 + /// on MoltenVK), set once the opened description is known. unsupported_sets: AtomicBool, } +/// Whether the driver of the device `description` names runs a descriptor set layout its +/// `vkGetDescriptorSetLayoutSupport` refuses: MoltenVK's, which runs a heap's set 1 its query +/// refuses. The executor makes its own heap sets so there, and its sink passes the validation +/// layer's report of such a layout ([`MessageSink::unsupported_sets`]). +fn makes_layouts_past_support(description: &DeviceDescription) -> bool { + description.driver_id == Some(vk::DriverId::MOLTENVK) +} + /// One message the sink kept: its id name and text, which tell the loader's reports apart /// ([`MessageSink::take`]), and the line a row reports. struct Recorded { @@ -531,7 +537,7 @@ impl MessageSink { /// The lines kept since the last call, removed: all but the loader's own reports of the /// driver manifests it ignored (`IgnoredDrivers`), each printed as a line of its own - /// (`LOADER-DRIVER`), as the runtime lane's `Messages` passes them. + /// (`LOADER-DRIVER`). fn take(&self) -> Vec { let recorded: Vec = { let mut messages = self.messages.lock().unwrap_or_else(|p| p.into_inner()); @@ -1251,11 +1257,7 @@ fn create_instance( // SAFETY: every pointer in `info` outlives the call. A validated context's layer provides // the extensions it enables through it (`require_validation_layer`), and so does the // profiles layer of a restricted context or a probe (`require_profiles_layer`). - let instance = unsafe { entry.create_instance(info, None) }; - // A layer registered an exit handler as the call began: the runtime's, where a runtime - // device lives in this process (a lane's), registers again after it. - metal2vulkan_runtime::program_instance_made(); - instance + unsafe { entry.create_instance(info, None) } }) } @@ -1359,186 +1361,6 @@ pub(super) fn refused_restriction( } } -/// This process's restriction as the runtime path opens its device under it: the restricted -/// context's steps before its device, on the device `device_type` selects. -pub(crate) enum Restricting { - /// The device takes P: what the runtime device's options and its second check need. - Takes(Box), - /// The device lacks capabilities P states: the typed refusal, recorded as the executor's - /// context records it ([`restriction_refusal`](super::compute::restriction_refusal)). - Refused(Box), -} - -/// What a runtime device restricted to P is made with: P, the device as it is (read through the -/// layer with its emulation off, which the second check compares the layer's kept members with) -/// and its identity, and the extensions the layer presents for P that P does not list, which it -/// hides. -pub(crate) struct RuntimeRestriction { - restriction: &'static ProfileRestriction, - native: DeviceDescription, - identity: serde_json::Value, - hidden: BTreeSet, -} - -/// The restricted context's steps before its device, for the runtime path's `executor`: `None` -/// when this process runs unrestricted; else the first check ([`profiles::check_within`]) -/// decides between a typed refusal and a restriction the device takes, whose hidden extensions -/// are read as a context reads them. Every other failure is an error, as in the context. -pub(crate) fn runtime_restriction( - device_type: DeviceType, - executor: &str, -) -> Result, String> { - let Some(restriction) = profiles::current_restriction() else { - return Ok(None); - }; - restricting(restriction, device_type, executor).map(Some) -} - -/// [`runtime_restriction`]'s steps for `restriction`: the first check decides between a typed -/// refusal, recorded as `executor`'s context records it, and a restriction the device takes. -fn restricting( - restriction: &'static ProfileRestriction, - device_type: DeviceType, - executor: &str, -) -> Result { - Ok(match first_check(restriction, device_type)? { - FirstCheck::Takes(restriction) => Restricting::Takes(restriction), - FirstCheck::Lacks(refused) => Restricting::Refused(Box::new( - super::compute::restriction_refusal(&refused, executor), - )), - }) -} - -/// The first check's ([`profiles::check_within`]) verdict on a restriction. -enum FirstCheck { - /// The device takes P. - Takes(Box), - /// The device lacks capabilities P states: what a typed refusal of it records. - Lacks(Box), -} - -/// The restricted context's steps before its device for `restriction`, on the device -/// `device_type` selects: the first check ([`profiles::check_within`]) decides between a refusal -/// and a restriction the device takes, whose hidden extensions are read as a context reads them. -/// Every other failure is an error, as in the context. -fn first_check( - restriction: &'static ProfileRestriction, - device_type: DeviceType, -) -> Result { - if device_type == DeviceType::Gpu { - crate::gpu::tripwire::refuse_if_tripped()?; - } - let entry = load_entry()?; - // SAFETY: a global command of a loaded entry. - let available = unsafe { entry.enumerate_instance_extension_properties(None) } - .map_err(|error| format!("enumerate Vulkan instance extensions: {error}"))?; - let portability = available.iter().any(|extension| { - extension_name(&extension.extension_name) == ash::khr::portability_enumeration::NAME - }); - require_profiles_layer(&entry)?; - let version = restriction.context_version(); - let (native, identity) = native_probe(&entry, device_type, portability, version)?; - match profiles::check_within(restriction, &native, version) { - Ok(()) => {} - Err(RestrictionError::Exceeds { gaps, .. }) => { - return Ok(FirstCheck::Lacks(Box::new(RefusedRestriction { - restriction, - gaps, - native, - identity, - }))); - } - Err(error) => return Err(error.to_string()), - } - let presented = presented_extensions(&entry, device_type, portability, restriction)?; - let hidden = restriction.hidden(presented.iter().map(String::as_str)); - Ok(FirstCheck::Takes(Box::new(RuntimeRestriction { - restriction, - native, - identity, - hidden, - }))) -} - -impl RuntimeRestriction { - /// The committed profile's stem. - pub(crate) fn stem(&self) -> &str { - &self.restriction.stem - } - - /// `options` restricted to P as a restricted context's instance is: the profiles layer below - /// the validation layer (which `options` stacks first), configured with P and the hidden - /// extensions, and the instance at P's version ([`ProfileRestriction::context_version`]). - pub(crate) fn restrict( - &self, - options: &mut metal2vulkan_runtime::DeviceOptions, - ) -> Result<(), String> { - let settings = - ProfilesSettings::new(ProfilesLayer::Restrict(self.restriction, &self.hidden))?; - options.layers.push(PROFILES_LAYER.to_owned()); - options.layer_settings.extend(settings.runtime_settings()); - options.instance_api_version = Some(self.restriction.context_version()); - Ok(()) - } - - /// What `executor`'s typed refusal of the restricted device itself, before it opened (a - /// device the runtime refuses at creation), records of the device as it is, with the - /// restriction it was made under (`compute::native_refused_on`, as a refusal of the - /// restriction records it). - pub(crate) fn refused_on( - &self, - executor: &str, - ) -> Result { - let layer = serde_json::json!({ - "profile": self.restriction.stem, - "profile_name": self.restriction.profile_name, - "profile_sha256": self.restriction.sha256, - "hidden_extensions": self.hidden, - }); - super::compute::native_refused_on(&self.native, &self.identity, executor, layer) - } - - /// The restricted context's second check ([`profiles::check_restricted`]) on `device`, - /// opened with [`RuntimeRestriction::restrict`]'s options, read through its raw handles: the - /// layer active, its kept members the native device's, and every other member P's. - pub(crate) fn check( - &self, - device: &metal2vulkan_runtime::Device, - ) -> Result { - let version = self.restriction.context_version(); - // SAFETY: only physical-device queries of the device's own instance, created at P's - // version; nothing is created, destroyed, or submitted, and the handles are not kept. - let (tools, queried) = unsafe { - let handles = device.raw(); - let tools = - profiles::active_tools(handles.entry, handles.instance, handles.physical_device)?; - let queried = - DeviceDescription::query(handles.instance, handles.physical_device, version) - .map_err(|error| format!("query the restricted device: {error}"))?; - (tools, queried) - }; - let translated = - profiles::check_restricted(self.restriction, &self.native, &tools, &queried, version) - .map_err(|error| error.to_string())?; - let record = serde_json::json!({ - "tool": profiles::profiles_tool(&tools), - "profile": self.restriction.stem, - "profile_name": self.restriction.profile_name, - "profile_sha256": self.restriction.sha256, - "hidden_extensions": self.hidden, - }); - let kept = profiles::differences(&translated, &queried) - .into_iter() - .map(|difference| difference.path) - .collect(); - Ok(crate::candidate::RestrictedDevice { - translated, - kept, - record, - }) - } -} - /// The device extensions the device `device_type` selects presents under `restriction`, read /// through an instance whose profiles layer restricts it and hides nothing, then destroyed: P's /// extensions and the ones the layer adds for P's version. @@ -1580,19 +1402,6 @@ impl VulkanContext { .unwrap_or_default() } - /// Whether the device replay's generated-commands executions are preprocessed apart, as the - /// runtime's are on the driver that executes (`generated_commands::preprocess_apart` of its - /// queried description, the device as it is, under a restriction too); also where the query - /// failed, since preprocessing apart runs right on every driver. - pub(super) fn preprocesses_generated_commands_apart(&self) -> bool { - match &self.queried_description { - Ok(description) => { - metal2vulkan_runtime::generated_commands::preprocess_apart(description) - } - Err(_) => true, - } - } - /// Open a device of `device_type` for `purpose`: the only Vulkan device creation in this crate, /// and with its probes the only caller of [`create_instance`]. fn new(device_type: DeviceType, purpose: Purpose) -> Result { @@ -1849,10 +1658,9 @@ impl VulkanContext { }) .collect(); let _ = messages.making.set(making); - messages.unsupported_sets.store( - metal2vulkan_runtime::makes_layouts_past_support(description), - Ordering::Relaxed, - ); + messages + .unsupported_sets + .store(makes_layouts_past_support(description), Ordering::Relaxed); } let opened = opened_description .clone() @@ -1936,9 +1744,7 @@ impl VulkanContext { clippy::disallowed_methods, reason = "the one call site, after the loader word is put back" )] - pub(super) fn generated_commands( - &self, - ) -> Option { + pub(super) fn generated_commands(&self) -> Option { if !self.generated_commands { return None; } @@ -1952,7 +1758,7 @@ impl VulkanContext { } }; // SAFETY: each name is the extension's command of this device, which enabled it. - unsafe { metal2vulkan_runtime::generated_commands::Commands::load(handle, load) } + unsafe { super::generated_commands::Commands::load(handle, load) } } /// `vkGetMemoryHostPointerPropertiesEXT` (`VK_EXT_external_memory_host`), loaded through the diff --git a/crates/metal2vulkan-validation/src/candidate/platform/generated_commands.rs b/crates/metal2vulkan-validation/src/candidate/platform/generated_commands.rs new file mode 100644 index 000000000..1ec493a22 --- /dev/null +++ b/crates/metal2vulkan-validation/src/candidate/platform/generated_commands.rs @@ -0,0 +1,440 @@ +//! `VK_EXT_device_generated_commands`, which `ash 0.38` (Vulkan 1.3.281) predates: the structures +//! and commands the device replay's generated-commands path uses (`compute::device_replay`), laid +//! out as the registry defines them (`vk.xml`, extension number 573: structure types +//! `1000572000 + n`). +//! +//! The executor's context loads the commands only where it enabled the extension +//! ([`Commands::load`]). Every commands layout is made for explicit preprocessing: each execution +//! is preprocessed apart ([`Commands::preprocess`]) and runs preprocessed +//! ([`Commands::execute_preprocessed`]), a form that runs right on every driver. + +use ash::vk; +use std::ffi::{c_void, CStr}; + +/// `VkIndirectExecutionSetEXT` and `VkIndirectCommandsLayoutEXT`: non-dispatchable handles. +pub(crate) type Handle = u64; + +const fn structure(n: i32) -> vk::StructureType { + vk::StructureType::from_raw(1_000_572_000 + n) +} + +/// `VK_INDIRECT_EXECUTION_SET_INFO_TYPE_PIPELINES_EXT`. +pub(crate) const EXECUTION_SET_PIPELINES: i32 = 0; +/// `VK_INDIRECT_COMMANDS_TOKEN_TYPE_EXECUTION_SET_EXT`, `..._PUSH_CONSTANT_EXT`, +/// `..._DISPATCH_EXT`. +pub(crate) const TOKEN_EXECUTION_SET: i32 = 0; +pub(crate) const TOKEN_PUSH_CONSTANT: i32 = 1; +pub(crate) const TOKEN_DISPATCH: i32 = 9; +/// `VK_PIPELINE_CREATE_2_INDIRECT_BINDABLE_BIT_EXT`. +pub(crate) const INDIRECT_BINDABLE: vk::PipelineCreateFlags2KHR = + vk::PipelineCreateFlags2KHR::from_raw(0x40_0000_0000); +/// `VK_BUFFER_USAGE_2_PREPROCESS_BUFFER_BIT_EXT`. +pub(crate) const PREPROCESS_BUFFER: vk::BufferUsageFlags2KHR = + vk::BufferUsageFlags2KHR::from_raw(0x8000_0000); +/// `VK_INDIRECT_COMMANDS_LAYOUT_USAGE_EXPLICIT_PREPROCESS_BIT_EXT`: an execution of the layout +/// is preprocessed apart (`vkCmdPreprocessGeneratedCommandsEXT`) before it runs. +const LAYOUT_EXPLICIT_PREPROCESS: u32 = 0x1; +/// `VK_PIPELINE_STAGE_COMMAND_PREPROCESS_BIT_EXT`, `VK_ACCESS_COMMAND_PREPROCESS_READ_BIT_EXT` and +/// `VK_ACCESS_COMMAND_PREPROCESS_WRITE_BIT_EXT` (the values of the `NV` names `ash` has). +pub(crate) const PREPROCESS_STAGE: vk::PipelineStageFlags = + vk::PipelineStageFlags::COMMAND_PREPROCESS_NV; +pub(crate) const PREPROCESS_READ: vk::AccessFlags = vk::AccessFlags::COMMAND_PREPROCESS_READ_NV; +pub(crate) const PREPROCESS_WRITE: vk::AccessFlags = vk::AccessFlags::COMMAND_PREPROCESS_WRITE_NV; + +/// `VkIndirectExecutionSetPipelineInfoEXT`. +#[repr(C)] +pub(crate) struct ExecutionSetPipelineInfo { + s_type: vk::StructureType, + p_next: *const c_void, + initial_pipeline: vk::Pipeline, + max_pipeline_count: u32, +} + +impl ExecutionSetPipelineInfo { + pub(crate) fn new(initial_pipeline: vk::Pipeline, max_pipeline_count: u32) -> Self { + ExecutionSetPipelineInfo { + s_type: structure(10), + p_next: std::ptr::null(), + initial_pipeline, + max_pipeline_count, + } + } +} + +/// `VkIndirectExecutionSetCreateInfoEXT` of the pipelines type (its `info` union holds +/// `pPipelineInfo`). +#[repr(C)] +pub(crate) struct ExecutionSetCreateInfo { + s_type: vk::StructureType, + p_next: *const c_void, + kind: i32, + pipeline_info: *const ExecutionSetPipelineInfo, +} + +impl ExecutionSetCreateInfo { + pub(crate) fn new(pipeline_info: &ExecutionSetPipelineInfo) -> Self { + ExecutionSetCreateInfo { + s_type: structure(3), + p_next: std::ptr::null(), + kind: EXECUTION_SET_PIPELINES, + pipeline_info, + } + } +} + +/// `VkWriteIndirectExecutionSetPipelineEXT`. +#[repr(C)] +pub(crate) struct WriteExecutionSetPipeline { + s_type: vk::StructureType, + p_next: *const c_void, + index: u32, + pipeline: vk::Pipeline, +} + +impl WriteExecutionSetPipeline { + pub(crate) fn new(index: u32, pipeline: vk::Pipeline) -> Self { + WriteExecutionSetPipeline { + s_type: structure(8), + p_next: std::ptr::null(), + index, + pipeline, + } + } +} + +/// `VkIndirectCommandsPushConstantTokenEXT`. +#[repr(C)] +pub(crate) struct PushConstantToken { + pub(crate) update_range: vk::PushConstantRange, +} + +/// `VkIndirectCommandsExecutionSetTokenEXT`. +#[repr(C)] +pub(crate) struct ExecutionSetToken { + pub(crate) kind: i32, + pub(crate) shader_stages: vk::ShaderStageFlags, +} + +/// `VkIndirectCommandsLayoutTokenEXT` (its `data` union is one pointer). +#[repr(C)] +pub(crate) struct LayoutToken { + s_type: vk::StructureType, + p_next: *const c_void, + kind: i32, + data: *const c_void, + offset: u32, +} + +impl LayoutToken { + pub(crate) fn new(kind: i32, data: *const c_void, offset: u32) -> Self { + LayoutToken { + s_type: structure(7), + p_next: std::ptr::null(), + kind, + data, + offset, + } + } +} + +/// `VkIndirectCommandsLayoutCreateInfoEXT`, made for explicit preprocessing +/// (`VK_INDIRECT_COMMANDS_LAYOUT_USAGE_EXPLICIT_PREPROCESS_BIT_EXT`): each of its executions is +/// preprocessed apart ([`Commands::preprocess`]) and runs preprocessed +/// ([`Commands::execute_preprocessed`]). +#[repr(C)] +pub(crate) struct LayoutCreateInfo { + s_type: vk::StructureType, + p_next: *const c_void, + flags: u32, + shader_stages: vk::ShaderStageFlags, + indirect_stride: u32, + pipeline_layout: vk::PipelineLayout, + token_count: u32, + tokens: *const LayoutToken, +} + +impl LayoutCreateInfo { + pub(crate) fn new( + indirect_stride: u32, + pipeline_layout: vk::PipelineLayout, + tokens: &[LayoutToken], + ) -> Self { + LayoutCreateInfo { + s_type: structure(6), + p_next: std::ptr::null(), + flags: LAYOUT_EXPLICIT_PREPROCESS, + shader_stages: vk::ShaderStageFlags::COMPUTE, + indirect_stride, + pipeline_layout, + token_count: tokens.len() as u32, + tokens: tokens.as_ptr(), + } + } +} + +/// `VkGeneratedCommandsMemoryRequirementsInfoEXT`. +#[repr(C)] +pub(crate) struct MemoryRequirementsInfo { + s_type: vk::StructureType, + p_next: *const c_void, + execution_set: Handle, + commands_layout: Handle, + max_sequence_count: u32, + max_draw_count: u32, +} + +impl MemoryRequirementsInfo { + pub(crate) fn new(execution_set: Handle, commands_layout: Handle, sequences: u32) -> Self { + MemoryRequirementsInfo { + s_type: structure(2), + p_next: std::ptr::null(), + execution_set, + commands_layout, + max_sequence_count: sequences, + max_draw_count: 0, + } + } +} + +/// `VkGeneratedCommandsInfoEXT`. +#[repr(C)] +#[derive(Clone, Copy)] +pub(crate) struct GeneratedCommandsInfo { + s_type: vk::StructureType, + p_next: *const c_void, + shader_stages: vk::ShaderStageFlags, + execution_set: Handle, + commands_layout: Handle, + indirect_address: vk::DeviceAddress, + indirect_address_size: vk::DeviceSize, + preprocess_address: vk::DeviceAddress, + preprocess_size: vk::DeviceSize, + max_sequence_count: u32, + sequence_count_address: vk::DeviceAddress, + max_draw_count: u32, +} + +/// One execution's addresses and sizes. +pub(crate) struct Execution { + pub(crate) indirect: (vk::DeviceAddress, vk::DeviceSize), + pub(crate) preprocess: (vk::DeviceAddress, vk::DeviceSize), + pub(crate) max_sequences: u32, + pub(crate) count_address: vk::DeviceAddress, +} + +impl GeneratedCommandsInfo { + pub(crate) fn new(execution_set: Handle, commands_layout: Handle, e: &Execution) -> Self { + GeneratedCommandsInfo { + s_type: structure(4), + p_next: std::ptr::null(), + shader_stages: vk::ShaderStageFlags::COMPUTE, + execution_set, + commands_layout, + indirect_address: e.indirect.0, + indirect_address_size: e.indirect.1, + preprocess_address: e.preprocess.0, + preprocess_size: e.preprocess.1, + max_sequence_count: e.max_sequences, + sequence_count_address: e.count_address, + max_draw_count: 0, + } + } +} + +type CreateExecutionSet = unsafe extern "system" fn( + vk::Device, + *const ExecutionSetCreateInfo, + *const vk::AllocationCallbacks<'static>, + *mut Handle, +) -> vk::Result; +type DestroyHandle = + unsafe extern "system" fn(vk::Device, Handle, *const vk::AllocationCallbacks<'static>); +type UpdateExecutionSetPipeline = + unsafe extern "system" fn(vk::Device, Handle, u32, *const WriteExecutionSetPipeline); +type CreateCommandsLayout = unsafe extern "system" fn( + vk::Device, + *const LayoutCreateInfo, + *const vk::AllocationCallbacks<'static>, + *mut Handle, +) -> vk::Result; +type MemoryRequirements = unsafe extern "system" fn( + vk::Device, + *const MemoryRequirementsInfo, + *mut vk::MemoryRequirements2<'static>, +); +type Execute = + unsafe extern "system" fn(vk::CommandBuffer, vk::Bool32, *const GeneratedCommandsInfo); +type Preprocess = + unsafe extern "system" fn(vk::CommandBuffer, *const GeneratedCommandsInfo, vk::CommandBuffer); + +/// The extension's commands, loaded for one device. +#[derive(Clone, Copy)] +pub(crate) struct Commands { + device: vk::Device, + create_execution_set: CreateExecutionSet, + destroy_execution_set: DestroyHandle, + update_execution_set_pipeline: UpdateExecutionSetPipeline, + create_commands_layout: CreateCommandsLayout, + destroy_commands_layout: DestroyHandle, + memory_requirements: MemoryRequirements, + execute: Execute, + preprocess: Preprocess, +} + +impl Commands { + /// The commands of `device`, each from `load` (`vkGetDeviceProcAddr`); `None` when one is + /// missing. + /// + /// # Safety + /// `load` returns each name's command of `device`, which enabled the extension. + pub(crate) unsafe fn load( + device: vk::Device, + load: impl Fn(&CStr) -> vk::PFN_vkVoidFunction, + ) -> Option { + macro_rules! command { + ($name:literal, $ty:ty) => {{ + let f = load($name)?; + // SAFETY: the registry gives the command this signature. + unsafe { std::mem::transmute::(f) } + }}; + } + Some(Commands { + device, + create_execution_set: command!(c"vkCreateIndirectExecutionSetEXT", CreateExecutionSet), + destroy_execution_set: command!(c"vkDestroyIndirectExecutionSetEXT", DestroyHandle), + update_execution_set_pipeline: command!( + c"vkUpdateIndirectExecutionSetPipelineEXT", + UpdateExecutionSetPipeline + ), + create_commands_layout: command!( + c"vkCreateIndirectCommandsLayoutEXT", + CreateCommandsLayout + ), + destroy_commands_layout: command!(c"vkDestroyIndirectCommandsLayoutEXT", DestroyHandle), + memory_requirements: command!( + c"vkGetGeneratedCommandsMemoryRequirementsEXT", + MemoryRequirements + ), + execute: command!(c"vkCmdExecuteGeneratedCommandsEXT", Execute), + preprocess: command!(c"vkCmdPreprocessGeneratedCommandsEXT", Preprocess), + }) + } + + /// `vkCreateIndirectExecutionSetEXT`. + /// + /// # Safety + /// `info` and what it points at are valid for the call. + pub(crate) unsafe fn create_execution_set( + &self, + info: &ExecutionSetCreateInfo, + ) -> Result { + let mut out = 0; + // SAFETY: the caller's contract. + match unsafe { (self.create_execution_set)(self.device, info, std::ptr::null(), &mut out) } + { + vk::Result::SUCCESS => Ok(out), + error => Err(error), + } + } + + /// `vkDestroyIndirectExecutionSetEXT`. + /// + /// # Safety + /// No pending work uses `set`. + pub(crate) unsafe fn destroy_execution_set(&self, set: Handle) { + // SAFETY: the caller's contract. + unsafe { (self.destroy_execution_set)(self.device, set, std::ptr::null()) } + } + + /// `vkUpdateIndirectExecutionSetPipelineEXT`. + /// + /// # Safety + /// No submitted work references the written indices. + pub(crate) unsafe fn update_execution_set( + &self, + set: Handle, + writes: &[WriteExecutionSetPipeline], + ) { + // SAFETY: the caller's contract. + unsafe { + (self.update_execution_set_pipeline)( + self.device, + set, + writes.len() as u32, + writes.as_ptr(), + ) + } + } + + /// `vkCreateIndirectCommandsLayoutEXT`. + /// + /// # Safety + /// `info` and what it points at are valid for the call. + pub(crate) unsafe fn create_commands_layout( + &self, + info: &LayoutCreateInfo, + ) -> Result { + let mut out = 0; + // SAFETY: the caller's contract. + match unsafe { + (self.create_commands_layout)(self.device, info, std::ptr::null(), &mut out) + } { + vk::Result::SUCCESS => Ok(out), + error => Err(error), + } + } + + /// `vkDestroyIndirectCommandsLayoutEXT`. + /// + /// # Safety + /// No pending work uses `layout`. + pub(crate) unsafe fn destroy_commands_layout(&self, layout: Handle) { + // SAFETY: the caller's contract. + unsafe { (self.destroy_commands_layout)(self.device, layout, std::ptr::null()) } + } + + /// `vkGetGeneratedCommandsMemoryRequirementsEXT`. + /// + /// # Safety + /// `info`'s handles are live. + pub(crate) unsafe fn memory_requirements( + &self, + info: &MemoryRequirementsInfo, + ) -> vk::MemoryRequirements { + let mut out = vk::MemoryRequirements2::default(); + // SAFETY: the caller's contract. + unsafe { (self.memory_requirements)(self.device, info, &mut out) }; + out.memory_requirements + } + + /// `vkCmdPreprocessGeneratedCommandsEXT` of `info` into `command`, the state taken from + /// `command` itself. + /// + /// # Safety + /// `command` is recording, with the execution set's initial pipeline bound; `info`'s handles + /// and addresses are live until the work completes. + pub(crate) unsafe fn preprocess( + &self, + command: vk::CommandBuffer, + info: &GeneratedCommandsInfo, + ) { + // SAFETY: the caller's contract. + unsafe { (self.preprocess)(command, info, command) } + } + + /// `vkCmdExecuteGeneratedCommandsEXT` of commands [`preprocess`](Self::preprocess) wrote. + /// + /// # Safety + /// `command` is recording, with the execution set's initial pipeline bound; `info` was + /// preprocessed in `command`, with the same contents and the same state bound, a barrier + /// ordering that preprocessing's writes before this execution, and its handles and addresses + /// are live until the work completes. + pub(crate) unsafe fn execute_preprocessed( + &self, + command: vk::CommandBuffer, + info: &GeneratedCommandsInfo, + ) { + // SAFETY: the caller's contract. + unsafe { (self.execute)(command, vk::TRUE, info) } + } +} diff --git a/crates/metal2vulkan-validation/src/candidate/platform/ignored_drivers.rs b/crates/metal2vulkan-validation/src/candidate/platform/ignored_drivers.rs new file mode 100644 index 000000000..ec2ba57bb --- /dev/null +++ b/crates/metal2vulkan-validation/src/candidate/platform/ignored_drivers.rs @@ -0,0 +1,160 @@ +//! The loader's reports, at `vkCreateInstance`, of each driver manifest whose library it could not +//! load, or that is no driver, and then ignores ([`IgnoredDrivers`]): the host's listing of its +//! drivers (a vendor's manifest left behind by a driver no longer installed is common), whatever +//! the device does, and nothing it did. The executor's sink passes those with a line of their own, +//! each naming the library the loader said it ignored. + +/// The id name the Vulkan loader gives the messages it reports itself. +const LOADER_MESSAGE: &str = "Loader Message"; + +/// How the loader's message about a driver manifest whose library it could not load begins +/// (`loader_icd_scan`, Vulkan-Loader `loader/loader.c`): the library the manifest names follows, +/// then [`IGNORING`]. +const ICD_SCAN_FAILED: &str = "loader_icd_scan: Failed loading library associated with ICD JSON "; + +/// How that message ends: the loader goes on without the manifest. +const IGNORING: &str = ". Ignoring this JSON"; + +/// How the loader's message about a driver library that loaded and gave no `vkCreateInstance` +/// begins (`loader_scanned_icd_add`): the library follows, and the message after it is +/// [`ICD_SCAN_FAILED`]'s about the same library. +const NO_CREATE_INSTANCE: &str = "loader_scanned_icd_add: Could not get 'vkCreateInstance' via \ + 'vk_icdGetInstanceProcAddr' for ICD "; + +/// How the loader's message about a library a driver manifest names that loaded and exports +/// neither entry point a driver does begins (`loader_scanned_icd_add`): the library follows, then +/// [`NO_ENTRY_POINT_END`]; the loader ignores the manifest with no other message. +const NO_ENTRY_POINT: &str = "loader_scanned_icd_add: Attempt to retrieve either \ + 'vkGetInstanceProcAddr' or 'vk_icdGetInstanceProcAddr' from ICD "; + +/// How that message ends. +const NO_ENTRY_POINT_END: &str = " failed."; + +/// The loader's own reports, in one message list, of driver manifests it ignored: the libraries +/// it said it ignored for failing to load them ([`ICD_SCAN_FAILED`]), which explain its messages +/// about the same library alone. +pub(crate) struct IgnoredDrivers(Vec); + +impl IgnoredDrivers { + /// The libraries the loader said it ignored, among `messages`, each its id name and text. + pub(crate) fn of<'a>(messages: impl IntoIterator) -> IgnoredDrivers { + let libraries = (messages.into_iter()) + .filter(|&(id_name, _)| id_name == LOADER_MESSAGE) + .filter_map(|(_, text)| { + let library = text.strip_prefix(ICD_SCAN_FAILED)?; + library + .strip_suffix(IGNORING) + .filter(|library| !library.is_empty()) + }) + .map(str::to_owned) + .collect(); + IgnoredDrivers(libraries) + } + + /// Whether a message with this id name and text is the loader's own report of a driver + /// manifest it ignored, and nothing wider: its message that it ignored the library, the dynamic + /// linker's error it forwards about that library (`: `), or its message that the + /// library gave no `vkCreateInstance`; or its message that a library a manifest names is no + /// driver, which names the library it ignored itself. + pub(crate) fn explains(&self, id_name: &str, text: &str) -> bool { + if id_name != LOADER_MESSAGE { + return false; + } + let no_driver = (text.strip_prefix(NO_ENTRY_POINT)) + .and_then(|rest| rest.strip_suffix(NO_ENTRY_POINT_END)) + .is_some_and(|library| !library.is_empty()); + no_driver + || self.0.iter().any(|library| { + let named = |prefix: &str, suffix: &str| { + (text.strip_prefix(prefix)) + .and_then(|rest| rest.strip_suffix(suffix)) + .is_some_and(|named| named == library) + }; + named(ICD_SCAN_FAILED, IGNORING) + || named(NO_CREATE_INSTANCE, "") + || (text.strip_prefix(library.as_str())) + .is_some_and(|why| why.starts_with(": ")) + }) + } +} + +#[cfg(test)] +mod tests { + use super::IgnoredDrivers; + + /// The loader's messages about a driver manifest it ignored, as a host left them, each its id + /// name and text: one whose library is missing (the dynamic linker's error, then the + /// loader's), one whose library loaded and gave no `vkCreateInstance`, and one whose library + /// is no driver. + fn ignored_drivers() -> Vec<(&'static str, &'static str)> { + [ + "/nonexistent/libstale_vulkan.so: cannot open shared object file: No such file or \ + directory", + "loader_icd_scan: Failed loading library associated with ICD JSON \ + /nonexistent/libstale_vulkan.so. Ignoring this JSON", + "loader_scanned_icd_add: Could not get 'vkCreateInstance' via \ + 'vk_icdGetInstanceProcAddr' for ICD libGLX_nvidia.so.0", + "loader_icd_scan: Failed loading library associated with ICD JSON libGLX_nvidia.so.0. \ + Ignoring this JSON", + "loader_scanned_icd_add: Attempt to retrieve either 'vkGetInstanceProcAddr' or \ + 'vk_icdGetInstanceProcAddr' from ICD /usr/lib/libz.so.1 failed.", + ] + .map(|text| ("Loader Message", text)) + .to_vec() + } + + /// The loader's reports of a driver manifest it ignored, each about the library it said it + /// ignored, and nothing wider: the same words of another id name, a linker's error or a missing + /// `vkCreateInstance` about a library it did not say it ignored, and its other messages. + #[test] + fn the_loader_s_reports_of_a_driver_manifest_it_ignored_are_matched_and_nothing_wider() { + let reported = ignored_drivers(); + let ignored = IgnoredDrivers::of(reported.iter().copied()); + for &(id_name, text) in &reported { + assert!(ignored.explains(id_name, text), "{text}"); + } + for (id_name, text) in [ + // The same words from something that is not the loader. + ( + "VUID-vkCreateInstance-None", + "loader_icd_scan: Failed loading library associated with ICD JSON \ + /nonexistent/libstale_vulkan.so. Ignoring this JSON", + ), + // A linker's error about a library the loader did not say it ignored. + ( + "Loader Message", + "/usr/lib/libvulkan_radeon.so: cannot open shared object file: No such file or \ + directory", + ), + // No `vkCreateInstance` from a library the loader did not say it ignored. + ( + "Loader Message", + "loader_scanned_icd_add: Could not get 'vkCreateInstance' via \ + 'vk_icdGetInstanceProcAddr' for ICD libvulkan_radeon.so", + ), + // A manifest naming no library. + ( + "Loader Message", + "loader_icd_scan: Failed loading library associated with ICD JSON . Ignoring this \ + JSON", + ), + // Another of the loader's messages. + ( + "Loader Message", + "terminator_CreateInstance: Failed to CreateInstance in ICD 0", + ), + // The library named, in other words. + ( + "Loader Message", + "/nonexistent/libstale_vulkan.so was loaded", + ), + ] { + assert!(!ignored.explains(id_name, text), "{id_name}: {text}"); + } + // Without the loader's word that it ignored the library, its linker error and its missing + // `vkCreateInstance` stand alone and fail. + let alone = IgnoredDrivers::of(reported[..1].iter().copied()); + assert!(!alone.explains(reported[0].0, reported[0].1)); + assert!(!alone.explains(reported[2].0, reported[2].1)); + } +} diff --git a/crates/metal2vulkan-validation/src/candidate/platform/profiles.rs b/crates/metal2vulkan-validation/src/candidate/platform/profiles.rs index a06f3d38b..3094ea7a7 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/profiles.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/profiles.rs @@ -29,7 +29,6 @@ use ash::vk; use metal2vulkan::device::ApiVersion; use metal2vulkan::device::{DeviceDescription, Independence}; -use metal2vulkan_runtime::{LayerSetting, LayerSettingValue}; use serde_json::Value; use std::collections::BTreeSet; use std::ffi::{c_char, CStr, CString}; @@ -407,23 +406,6 @@ impl ProfilesSettings { Ok(ProfilesSettings { values }) } - /// The settings as a runtime device's options take them (`DeviceOptions::layer_settings`), - /// owned. - pub(super) fn runtime_settings(&self) -> Vec { - self.values - .iter() - .map(|(name, values)| { - let value = match values { - SettingValues::Bool(value) => LayerSettingValue::Bool(*value == vk::TRUE), - SettingValues::Strings { owned, .. } => { - LayerSettingValue::Strings(owned.clone()) - } - }; - LayerSetting::new(PROFILES_LAYER.to_owned(), (*name).to_owned(), value) - }) - .collect() - } - /// The settings, pointing into `self`. pub(super) fn settings(&self) -> Vec> { self.values @@ -439,9 +421,9 @@ impl ProfilesSettings { setting.value_count = 1; setting.p_values = std::ptr::from_ref(value).cast(); } - SettingValues::Strings { pointers, .. } => { + SettingValues::Strings { owned, pointers } => { setting = setting.ty(vk::LayerSettingTypeEXT::STRING); - setting.value_count = pointers.len() as u32; + setting.value_count = owned.len() as u32; setting.p_values = pointers.as_ptr().cast(); } } diff --git a/crates/metal2vulkan-validation/src/candidate/runtime_case.rs b/crates/metal2vulkan-validation/src/candidate/runtime_case.rs deleted file mode 100644 index 91879a3b0..000000000 --- a/crates/metal2vulkan-validation/src/candidate/runtime_case.rs +++ /dev/null @@ -1,1942 +0,0 @@ -//! A case's run through the Metal-like runtime, `metal2vulkan_runtime`: the one copy the runtime -//! lane's device tests (`runtime_lane`) and the engine executor's runtime path (`runtime_run`) -//! share. -//! -//! A kernel case runs as a Metal program would run it: a compute pipeline state of the oracle's -//! descriptor ([`compute_descriptor`]: its kernel, the functions it links, its stage-input -//! descriptor), its buffers, textures, sampler states, threadgroup memory, imageblock size and -//! stage-in region set on a compute encoder, its dispatch, and its output read back after the -//! command buffer completed. Each texture is made as the Metal oracle makes it: its type, pixel -//! format, extent and usage (the case's role united with the AIR's declared access, -//! [`texture_usage`]), `Shared`, its levels (one unless the case declares more), its bytes written -//! per level and slice with `replace_region`, or, for a texture buffer, a texture over a `Shared` -//! buffer of its bytes (`Buffer::new_texture`); a multisampled texture `Private`, filled sample by -//! sample by render passes the case's command buffer runs before its dispatch (`runtime_samples`); -//! a texture output is read per slice with `get_bytes`. Each sampler state is the oracle's -//! descriptor (`resources::sampler_descriptor`). An argument buffer's members are made as the -//! oracle makes them and written into their owner at their fields as its argument encoder writes -//! them ([`bound_buffers`]): a buffer, `Shared`, of its bytes, by its `gpu_address`; a texture as a -//! bound one is made (a multisampled one filled as a bound one is), its usage its role united with -//! the declared access of the AIR member at its field ([`argument_texture_usage`]), by its -//! `gpu_resource_id`; a sampler state supporting argument buffers, of the oracle's descriptor -//! (`resources::argument_sampler_descriptor`), by its `gpu_resource_id`. The buffers and textures -//! are made resident for reading and writing (`use_resources`), as the oracle's -//! `useResource:usage:` does; a sampler state is no resource. A buffer or argument-buffer buffer -//! holding a rasterization-rate map's parameter data is made as the oracle makes it -//! ([`rate_map_buffer`]): the runtime makes the map (`new_rasterization_rate_map`) and copies its -//! data to offset 0 of a `Shared` buffer of the size it answers (`copy_parameter_data_to_buffer`). -//! A buffer, argument-buffer buffer or texture buffer that is an out-of-bounds target (or holds the -//! stage input that is one) lies in a placement heap of its own between guards -//! ([`guarded_buffer`]): every byte of the heap outside the target's length padded to 16 is its -//! guard, and what a run changed there is counted once it completed ([`Committed::guard_counts`]). -//! -//! A tile kernel, a kernel case over a tile pass's render targets, dispatches through a tile -//! pipeline state on a render encoder ([`encoded_tile`], the `tile` module's rule). A render case -//! draws as a Metal program would draw it ([`encoded_render`], [`commit_render`], the `render` -//! module's rule), a vertex buffer that is an out-of-bounds target between guards as a kernel's -//! buffer target is. -//! -//! Every runtime call's refusal stays typed ([`CaseError::Runtime`]), so the executor can tell a -//! gap the runtime names from the product's refusal. - -use crate::air_library::AirLibrary; -use crate::candidate::engine::argument_buffers::owner_bytes; -use crate::candidate::engine::guards::{ - buffer_target, embedded_guard_reach, guard_reach, texel_guard_reach, GuardCount, GuardReach, - MIN_GUARD, -}; -use crate::candidate::engine::resources::{ - argument_sampler_descriptor, pixel_format, sampler_descriptor, texture_type, -}; -use crate::candidate::engine::tables::{FunctionTable, TableBuffers}; -use crate::candidate::engine::{ComputeCase, ComputeOutput, LinkedModule}; -use crate::candidate::runtime_samples::{multisampled_texture_with, SampleFill}; -use crate::candidate::{unadvertised_stage, unsupported_set}; -use crate::case::out_of_bounds::OutOfBoundsResource; -use crate::case::{ArgumentBufferSamplerResource, AuthoredCase, RateMapLiteral, TextureType}; -use crate::check::interface::{ - declared_texture_atomic, declared_texture_writable, declared_writable, texture_shader_usage, - AirInterface, -}; -use crate::executor_contract::out_of_bounds::{GUARD_FILL, PAD_FILL}; -use crate::executor_contract::stage_inputs; -use crate::gpu::DeviceType; -use crate::literal::{subresource_span, LiteralResources, LiteralTexture, SubresourceSpan}; -use metal2vulkan::bind::{Dispatch, FunctionTableWords}; -use metal2vulkan::metal::{ResourceUsage, TextureUsage}; -use metal2vulkan::pipeline::{ - ComputePipelineDescriptor, LinkedFunctions, Stage as ShaderStage, StageSource, -}; -use metal2vulkan_air::abi::ParamRole; -use metal2vulkan_runtime::{ - Buffer, CommandBuffer, ComputeCommandEncoder, ComputePipelineState, CpuCacheMode, DebugMessage, - Degradation, Device, DeviceKind, DeviceOptions, Error, Execution, Function, FunctionHandle, - HazardTrackingMode, Heap, HeapDescriptor, HeapType, LayerSetting, LayerSettingValue, - MessageSeverity, MessageSink, Region, ResourceOptions, SamplerState, SamplerStateOptions, - ShaderCacheOptions, Size, StorageMode, Texture, TextureDescriptor, VisibleFunctionTable, - VisibleFunctionTableDescriptor, -}; -use std::collections::{BTreeMap, BTreeSet}; -use std::fmt; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Mutex, OnceLock}; - -mod commands; -mod host_wait_gap; -pub(crate) mod imageblock; -mod input_index_gap; -mod layer_claim; -mod query_reset_gap; -mod raster_order_gap; -mod render; -mod sparse; -mod tile; -pub use commands::{encoded_execution, pipeline_states, CaseCommands, TemplateState}; -/// The engine executor's sink and the lane's own instances pass the loader's reports of driver -/// manifests it ignored as `Messages` does (`layer_claim`). -pub(crate) use layer_claim::IgnoredDrivers; -pub use layer_claim::{ - layer_reported_nothing, layer_reported_nothing_at_all, nothing_reported_without_the_layer, - EnabledLayers, LayerClaim, LAYERS_DROPPED, -}; -pub use render::{ - commit_render, encoded_mesh, encoded_render, mesh_pipeline_state, render_pipeline_descriptor, - render_pipeline_state, CommittedRender, EncodedRender, MeshInputs, RenderInputs, -}; -pub use tile::{encoded_tile, tile_descriptor, tile_tables}; - -/// Why a case did not run through the runtime. -#[derive(Debug)] -pub enum CaseError { - /// The runtime call `call` returned `error`. - Runtime { call: String, error: Box }, - /// The runtime call `call`, making or drawing the pipeline of a helper of the runner's own (a - /// multisampled texture's sample fill, a sample readback, `runtime_samples`; a fragment - /// imageblock's initializer and resolver, `imageblock.rs`: the work the Metal oracle does - /// around the case's draw), returned `error`: not the case's own pipeline. - Helper { call: String, error: Box }, - /// The case cannot run so: an input of a later runtime step, or a literal that does not fit. - Case(String), -} - -impl CaseError { - /// The runtime's refusal of `call`. - pub fn runtime(call: impl Into) -> impl FnOnce(Error) -> CaseError { - let call = call.into(); - move |error| CaseError::Runtime { - call, - error: Box::new(error), - } - } - - /// The runtime's refusal of `call`, which makes a helper's pipeline ([`CaseError::Helper`]). - pub fn helper(call: impl Into) -> impl FnOnce(Error) -> CaseError { - let call = call.into(); - move |error| CaseError::Helper { - call, - error: Box::new(error), - } - } -} - -impl fmt::Display for CaseError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - CaseError::Runtime { call, error } | CaseError::Helper { call, error } => { - write!(f, "{call}: {error}") - } - CaseError::Case(why) => f.write_str(why), - } - } -} - -impl From for CaseError { - fn from(why: String) -> CaseError { - CaseError::Case(why) - } -} - -impl From<&str> for CaseError { - fn from(why: &str) -> CaseError { - CaseError::Case(why.into()) - } -} - -impl From for String { - fn from(error: CaseError) -> String { - error.to_string() - } -} - -/// Whether every [`Messages`] sink also writes each failing message to stderr as the layer -/// reports it ([`echo_messages`]). -static ECHO: AtomicBool = AtomicBool::new(false); - -/// Write every failing message a [`Messages`] sink keeps to stderr as well, the moment the layer -/// reports it: the engine device worker's setting for its whole process, so a worker a driver -/// fault kills still shows the messages before the fault. -pub(crate) fn echo_messages() { - ECHO.store(true, Ordering::Relaxed); -} - -/// Whether every [`Messages`] sink also writes each failing message to stderr as one -/// `LANE-VALIDATION` line naming its test. -static REPORT: AtomicBool = AtomicBool::new(false); - -/// What the validation layer reported that fails a run: every error, and every warning of the -/// validation type (the rule the executor's own context applies); and, apart, the runtime's -/// degrade notices (`DebugMessage::degradation`), which fail nothing. Bounded so a flood cannot -/// grow without limit. While a test holds the layer's hazard reports -/// ([`Messages::hold_hazards`]), each distinct one is kept once and its repeats counted, for the -/// test's claim to judge. -/// -/// Four layer gaps pass, on the layer releases whose source was read with their cause in place: -/// the layer's synchronization validation forgetting a semaphore chain once the host waited on a -/// timeline (`runtime_case/host_wait_gap.rs`); the layer's synchronization validation not -/// reading rasterization-order attachment access, so that it reports an input attachment read of -/// the runtime's pipelines made with it (named so) after an earlier draw's color write -/// (`runtime_case/raster_order_gap.rs`); the layer's check of a host query reset reporting the -/// whole pool in use where the valid usage speaks of the range reset -/// (`runtime_case/query_reset_gap.rs`); and the layer's link-time check of a fragment shader's -/// input attachments reading a pipeline made against a `VkRenderPass` as one made for dynamic -/// rendering (`runtime_case/input_index_gap.rs`). Each message passed prints a `LAYER-GAP` line -/// with the layer's source, and a test's count of them prints once its messages go. On any other -/// release each fails, marked "re-read WaitForSemaphore in layer X.Y.Z", "re-read the input -/// attachment ordering in layer X.Y.Z", "re-read vkResetQueryPool in layer X.Y.Z" or "re-read the -/// link-time input attachment check in layer X.Y.Z". -/// -/// One message about the driver passes too, once the runtime announced it: the layer's report -/// of a vertex module's subgroup operations outside `subgroupSupportedStages` -/// (`candidate/unadvertised_stage.rs`), after the device's -/// `Degradation::UnadvertisedVertexSimdgroups` notice, which it gives only where its profile -/// takes `DriverDeviation::MetalVertexSimdgroups`. Each such message prints an `UNADVERTISED-STAGE` -/// line, and a test's count of them prints once its messages go; before the notice it fails. -/// So does the layer's report of a descriptor set layout the driver's support query refuses -/// (`candidate/unsupported_set.rs`), after the device's `Degradation::SetPastLayoutSupport` notice, -/// which it gives only where its driver runs what the query refuses -/// (`RuntimeDriverDefect::SetLayoutSupportUnderstated`), each printing an `UNSUPPORTED-SET` line. -#[derive(Clone, Default)] -pub struct Messages(Arc>); - -/// The messages [`Messages`] keeps. -struct Reported { - failing: Vec, - notices: Vec, - /// How many of the layer gap's messages passed. - layer_gaps: usize, - /// Whether a device announced `Degradation::UnadvertisedVertexSimdgroups`. - unadvertised_vertex: bool, - /// How many of the layer's messages about such a vertex module passed. - unadvertised_messages: usize, - /// Whether a device announced `Degradation::SetPastLayoutSupport`. - unsupported_sets: bool, - /// How many of the layer's messages about such a set layout passed. - unsupported_set_messages: usize, - /// The thread that made the list: the test's. - test: String, - /// What the devices reporting here enabled of the instance layers they asked for, and the - /// claims stated against it (`layer_claim`). - layers: layer_claim::LayerFacts, - /// How many notices of each kind were taken so far (`Messages::take_notices`), less those - /// put back (`Messages::restore_notices`): a device announces a kind once, so a later making - /// or use of it announces nothing again. - taken: BTreeMap, - /// The layer's hazard reports held apart from `failing` while a test holds them - /// (`Messages::hold_hazards`): each distinct report once, with the times it came. - held: Option>, -} - -impl Default for Reported { - fn default() -> Reported { - Reported { - failing: Vec::new(), - notices: Vec::new(), - layer_gaps: 0, - unadvertised_vertex: false, - unadvertised_messages: 0, - unsupported_sets: false, - unsupported_set_messages: 0, - taken: BTreeMap::new(), - held: None, - layers: layer_claim::LayerFacts::default(), - test: std::thread::current() - .name() - .unwrap_or("an unnamed thread") - .to_owned(), - } - } -} - -impl Drop for Reported { - fn drop(&mut self) { - self.layers.report(&self.test); - if self.layer_gaps != 0 { - eprintln!( - "LAYER-GAP count {}: {} layer gap message(s) passed", - self.test, self.layer_gaps - ); - } - if self.unadvertised_messages != 0 { - eprintln!( - "UNADVERTISED-STAGE count {}: {} message(s) about the vertex stage's subgroups \ - passed", - self.test, self.unadvertised_messages - ); - } - if self.unsupported_set_messages != 0 { - eprintln!( - "UNSUPPORTED-SET count {}: {} message(s) about set layouts the driver's support \ - query refuses passed", - self.test, self.unsupported_set_messages - ); - } - } -} - -/// The id name of the informational message a device sends where its queue limits -/// (`DeviceOptions::queue_limits`) changed a placement from what its queue plan gives, which fails -/// a run ([`Messages::sink`]). -pub const QUEUE_LIMITS_REACHED: &str = "metal2vulkan-queue-limits-reached"; - -/// The start of every id name the validation layer's synchronization validation reports a hazard -/// by (`SYNC-HAZARD-WRITE-AFTER-WRITE`, ...). -pub const HAZARD: &str = "SYNC-HAZARD-"; - -/// The `specVersion` of the validation layer the runtime's loader offers, read once. -static LAYER_VERSION: OnceLock> = OnceLock::new(); - -impl Messages { - /// The most messages kept of each list: past it, a failing message is dropped unread. - pub(crate) const MAX: usize = 64; - - /// A device reporting here is about to be made asking for the instance layers `layers`: what - /// it enables of them is the instance's answer, which it announces as it is made - /// (`layer_claim`). Called once per device, before it opens; a later device's list replaces - /// an earlier one's. - pub fn device_asked_layers(&self, layers: &[std::ffi::CString]) { - let mut reported = self.0.lock().unwrap_or_else(|p| p.into_inner()); - reported.layers.asked(layers); - } - - /// Take the informational message `id_name`, text `text`, where it is one this list keeps - /// apart (the message a device sends as it is made without the layers it asked for); whether - /// it was taken. The sink's own path for such a message, and the way a test states one - /// without a device. - pub fn heard_informational(&self, id_name: &str, text: &str) -> bool { - let mut reported = self.0.lock().unwrap_or_else(|p| p.into_inner()); - let test = reported.test.clone(); - reported.layers.heard(&test, id_name, text) - } - - /// What the instance of the devices reporting here enabled of the instance layers they asked - /// for: the layers asked for, less those it announced it was made without. - pub fn enabled_layers(&self) -> EnabledLayers { - let reported = self.0.lock().unwrap_or_else(|p| p.into_inner()); - reported.layers.enabled() - } - - /// The text of the message a device reporting here sent as it was made without the layers it - /// asked for, which the loader could not provide; `None` where none was. - pub fn layers_dropped_message(&self) -> Option { - let reported = self.0.lock().unwrap_or_else(|p| p.into_inner()); - reported.layers.dropped_message().map(str::to_owned) - } - - /// State the layer-dependent claim `claim` against what the instance enabled - /// ([`layer_reported_nothing`], which reads this list's messages first). - pub(crate) fn state_layer_claim(&self, claim: &str) -> LayerClaim { - let mut reported = self.0.lock().unwrap_or_else(|p| p.into_inner()); - let test = reported.test.clone(); - reported.layers.claim(&test, claim) - } - - /// The failing messages reported so far, removed, with the loader's own messages about a - /// layer it could not provide that no device of this list explained, and without its reports - /// of driver manifests it ignored, each printed (`layer_claim`). Hazard reports still held - /// ([`Messages::hold_hazards`]) are among them, each once, and holding ends. - pub fn take(&self) -> Vec { - let mut reported = self.0.lock().unwrap_or_else(|p| p.into_inner()); - let mut unexplained = reported.layers.release(); - let mut failing = reported.failing.split_off(0); - unexplained.append(&mut failing); - let held = reported.held.take().unwrap_or_default(); - unexplained.extend(held.into_iter().map(|(message, _)| message)); - let ignored = layer_claim::IgnoredDrivers::of_messages(&unexplained); - unexplained.retain(|message| { - let host = ignored.explains(&message.id_name, &message.text); - if host { - eprintln!( - "LANE-LOADER-DRIVER {}: passed, the loader's own report of a driver manifest \ - it ignored: {}", - reported.test, - message.text.replace('\n', " ") - ); - } - !host - }); - unexplained - } - - /// Hold the layer's synchronization hazard reports (id names [`HAZARD`]`*`) apart from the - /// failing messages from here on, until [`Messages::take_held_hazards`] or - /// [`Messages::take`]: each distinct report (its id name and text) once, a repeat only - /// counted, so a claim that judges a report by those alone reads every report the layer - /// made, however often it repeats one (`runtime_lane::apart_writes`). Past `Messages::MAX` - /// distinct reports, a new one is a failing message as before. - pub fn hold_hazards(&self) { - let mut reported = self.0.lock().unwrap_or_else(|p| p.into_inner()); - reported.held.get_or_insert_with(Vec::new); - } - - /// The hazard reports held since [`Messages::hold_hazards`], each with the times it came, - /// removed; holding ends. - pub fn take_held_hazards(&self) -> Vec<(DebugMessage, usize)> { - let mut reported = self.0.lock().unwrap_or_else(|p| p.into_inner()); - reported.held.take().unwrap_or_default() - } - - /// Whether a device reporting here announced `kind`: a notice of it taken - /// ([`Messages::taken_kinds`]) or still to be taken. - pub fn announced(&self, kind: Degradation) -> bool { - let reported = self.0.lock().unwrap_or_else(|p| p.into_inner()); - reported.taken.contains_key(&kind) - || (reported.notices.iter()) - .filter_map(|message| message.degradation.as_ref()) - .any(|notice| notice.degradation == kind) - } - - /// The degrade notices delivered so far, removed. - pub fn take_notices(&self) -> Vec { - let mut reported = self.0.lock().unwrap_or_else(|p| p.into_inner()); - let notices = reported.notices.split_off(0); - for notice in notices.iter().filter_map(|m| m.degradation.as_ref()) { - *reported.taken.entry(notice.degradation).or_insert(0) += 1; - } - notices - } - - /// The kinds of the notices taken so far ([`Messages::take_notices`]): those a device - /// reporting here announced before, which it does not announce again. - pub fn taken_kinds(&self) -> BTreeSet { - let reported = self.0.lock().unwrap_or_else(|p| p.into_inner()); - reported.taken.keys().copied().collect() - } - - /// Start [`Messages::taken_kinds`] over for a new device reporting here, whose making - /// announced `made` (taken apart from the test's notices): a device announces each kind - /// once, its own, so the kinds an earlier device announced are the new one's to announce - /// again. - pub fn device_made(&self, made: &[DebugMessage]) { - let mut reported = self.0.lock().unwrap_or_else(|p| p.into_inner()); - reported.taken.clear(); - for notice in made.iter().filter_map(|m| m.degradation.as_ref()) { - *reported.taken.entry(notice.degradation).or_insert(0) += 1; - } - } - - /// Whether every device reporting here was torn down within `wait`: the sink a device's - /// instance holds goes after `vkDestroyInstance`, its teardown's last step, wherever that - /// teardown runs (the device's reaper, after a making still running), so only this list's - /// own shares remain. - pub fn unshared_within(&self, wait: std::time::Duration) -> bool { - let deadline = std::time::Instant::now() + wait; - while Arc::strong_count(&self.0) > 1 { - if std::time::Instant::now() >= deadline { - return false; - } - std::thread::sleep(std::time::Duration::from_millis(1)); - } - true - } - - /// How many failing messages are kept so far: the mark [`Messages::drop_failing_since`] takes. - pub fn failing_kept(&self) -> usize { - self.0 - .lock() - .unwrap_or_else(|p| p.into_inner()) - .failing - .len() - } - - /// Drop the failing messages kept since `mark` ([`Messages::failing_kept`]): those a device - /// making delivered that the runtime lane makes again, the driver having refused the device, - /// or its queue plan, for want of what other processes' devices hold. The loader reports each - /// refused `vkCreateDevice` as two errors ("terminator_CreateDevice: Failed in ICD ... - /// vkCreateDevice call", "vkCreateDevice: Failed to create device chain."), which the making - /// the test keeps does not deliver (`runtime_lane/device_room.rs`). - pub fn drop_failing_since(&self, mark: usize) { - let mut reported = self.0.lock().unwrap_or_else(|p| p.into_inner()); - reported.failing.truncate(mark); - } - - /// Put `notices`, taken earlier, back before those delivered since: the runtime lane's device - /// constructor takes a new device's creation notices apart from those a test has not read. - pub fn restore_notices(&self, mut notices: Vec) { - let mut reported = self.0.lock().unwrap_or_else(|p| p.into_inner()); - for notice in notices.iter().filter_map(|m| m.degradation.as_ref()) { - let kind = notice.degradation; - if let Some(count) = reported.taken.get_mut(&kind) { - *count -= 1; - if *count == 0 { - reported.taken.remove(&kind); - } - } - } - notices.append(&mut reported.notices); - reported.notices = notices; - } - - /// How many of the layer gaps' messages passed so far (`runtime_case/host_wait_gap.rs`, - /// `runtime_case/raster_order_gap.rs`, `runtime_case/query_reset_gap.rs`, - /// `runtime_case/input_index_gap.rs`). - pub fn layer_gaps(&self) -> usize { - self.0.lock().unwrap_or_else(|p| p.into_inner()).layer_gaps - } - - /// How many hold the message list: this handle and its clones, and the instance of each - /// device made to report to it, which holds it (through its debug messenger's sink) until the - /// instance is destroyed, the last step of the device's teardown. So with one handle and no - /// device left, 1. - pub fn holders(&self) -> usize { - Arc::strong_count(&self.0) - } - - /// The sink a device reports to. - pub fn sink(&self) -> MessageSink { - let messages = Arc::clone(&self.0); - let layer = - *LAYER_VERSION.get_or_init(|| host_wait_gap::layer_version(loader().as_deref())); - MessageSink::new(move |message: &DebugMessage| { - let fails = message.severity == MessageSeverity::Error - || (message.severity == MessageSeverity::Warning && message.kind.validation); - let mut reported = messages.lock().unwrap_or_else(|p| p.into_inner()); - if let Some(notice) = &message.degradation { - if notice.degradation == Degradation::UnadvertisedVertexSimdgroups { - reported.unadvertised_vertex = true; - } - if notice.degradation == Degradation::SetPastLayoutSupport { - reported.unsupported_sets = true; - } - if reported.notices.len() < Self::MAX { - reported.notices.push(message.clone()); - } - return; - } - // The runtime's pipeline creation log, on where `METAL2VULKAN_LOG_PIPELINES` is set: - // printed as it comes, never a failure. - if message.id_name == "metal2vulkan-pipeline-creation" { - eprintln!("{}", message.text); - return; - } - // What the instance enabled of the layers the device asked for: informational, so it - // fails nothing, and kept rather than dropped with the rest, since a claim of what the - // validation layer reported holds nothing without it (`layer_claim`). - let test = reported.test.clone(); - if reported - .layers - .heard(&test, &message.id_name, &message.text) - { - return; - } - // The loader's own message about an instance layer it cannot provide, reported through - // the messenger chained at creation before the call answers - // `VK_ERROR_LAYER_NOT_PRESENT`: held until the device says whether it was made - // without that layer, which passes it (`layer_claim`), and failing with the rest - // where nothing says so. - if layer_claim::loader_layer_message(&message.id_name, &message.text) - && reported.layers.hold(message) - { - return; - } - // A device placed a queue otherwise than its queue plan gives, under the queue limits - // the lane makes its devices with (`DeviceOptions::queue_limits`, - // `runtime_lane::LANE_QUEUE_LIMITS`): the work depends on the plan's queues, so it - // fails as the layer's errors do, and the test makes its device with the plan. - if message.id_name == QUEUE_LIMITS_REACHED { - eprintln!( - "QUEUE-LIMITS-REACHED {}: {}", - reported.test, - message.text.replace('\n', " ") - ); - if reported.failing.len() < Self::MAX { - reported.failing.push(message.clone()); - } - return; - } - if !fails { - return; - } - if reported.unadvertised_vertex - && unadvertised_stage::shape(&message.id_name, &message.text) - { - reported.unadvertised_messages += 1; - eprintln!( - "UNADVERTISED-STAGE {}: passed, announced as {}: {} ({}): {}", - reported.test, - Degradation::UnadvertisedVertexSimdgroups.code(), - message.id_name, - message.id, - message.text.replace('\n', " ") - ); - return; - } - if reported.unsupported_sets && unsupported_set::shape(&message.id_name, &message.text) - { - reported.unsupported_set_messages += 1; - eprintln!( - "UNSUPPORTED-SET {}: passed, announced as {}: {} ({}): {}", - reported.test, - Degradation::SetPastLayoutSupport.code(), - message.id_name, - message.id, - message.text.replace('\n', " ") - ); - return; - } - let index_gap = input_index_gap::shape(message.id, &message.id_name, &message.text); - if index_gap && layer.is_some_and(input_index_gap::read) { - reported.layer_gaps += 1; - eprintln!( - "LAYER-GAP {}: passed, the layer's link-time input attachment gap ({}): {} \ - ({}): {}", - reported.test, - input_index_gap::SOURCE, - message.id_name, - message.id, - message.text.replace('\n', " ") - ); - return; - } - let gap = host_wait_gap::shape(message.id, &message.id_name, &message.text); - if gap && layer.is_some_and(host_wait_gap::read) { - reported.layer_gaps += 1; - eprintln!( - "LAYER-GAP {}: passed, the layer's host-wait gap ({}): {} ({}): {}", - reported.test, - host_wait_gap::SOURCE, - message.id_name, - message.id, - message.text.replace('\n', " ") - ); - return; - } - let raster_gap = raster_order_gap::shape(message.id, &message.id_name, &message.text); - if raster_gap && layer.is_some_and(raster_order_gap::read) { - reported.layer_gaps += 1; - eprintln!( - "LAYER-GAP {}: passed, the layer's rasterization-order gap ({}): {} ({}): {}", - reported.test, - raster_order_gap::SOURCE, - message.id_name, - message.id, - message.text.replace('\n', " ") - ); - return; - } - let reset_gap = query_reset_gap::shape(message.id, &message.id_name, &message.text); - if reset_gap && layer.is_some_and(query_reset_gap::read) { - reported.layer_gaps += 1; - eprintln!( - "LAYER-GAP {}: passed, the layer's query-reset gap ({}): {} ({}): {}", - reported.test, - query_reset_gap::SOURCE, - message.id_name, - message.id, - message.text.replace('\n', " ") - ); - return; - } - let mut message = message.clone(); - if reset_gap { - let read: Vec = query_reset_gap::READ - .iter() - .map(|&version| host_wait_gap::release(version)) - .collect(); - message.text = format!( - "re-read vkResetQueryPool in layer {}: the layer's query-reset gap passes \ - only on the releases read ({}). {}", - layer.map_or_else(|| "of an unknown release".into(), host_wait_gap::release), - read.join(", "), - message.text - ); - eprintln!( - "LAYER-GAP {}: failed, {}", - reported.test, - message.text.replace('\n', " ") - ); - } - if raster_gap { - let read: Vec = raster_order_gap::READ - .iter() - .map(|&version| host_wait_gap::release(version)) - .collect(); - message.text = format!( - "re-read the input attachment ordering in layer {}: the layer's \ - rasterization-order gap passes only on the releases read ({}). {}", - layer.map_or_else(|| "of an unknown release".into(), host_wait_gap::release), - read.join(", "), - message.text - ); - eprintln!( - "LAYER-GAP {}: failed, {}", - reported.test, - message.text.replace('\n', " ") - ); - } - if gap { - let read: Vec = host_wait_gap::READ - .iter() - .map(|&version| host_wait_gap::release(version)) - .collect(); - message.text = format!( - "re-read WaitForSemaphore in layer {}: the layer's host-wait gap passes only \ - on the releases read ({}). {}", - layer.map_or_else(|| "of an unknown release".into(), host_wait_gap::release), - read.join(", "), - message.text - ); - eprintln!( - "LAYER-GAP {}: failed, {}", - reported.test, - message.text.replace('\n', " ") - ); - } - if index_gap { - let read: Vec = input_index_gap::READ - .iter() - .map(|&version| host_wait_gap::release(version)) - .collect(); - message.text = format!( - "re-read the link-time input attachment check in layer {}: the layer's \ - link-time input attachment gap passes only on the releases read ({}). {}", - layer.map_or_else(|| "of an unknown release".into(), host_wait_gap::release), - read.join(", "), - message.text - ); - eprintln!( - "LAYER-GAP {}: failed, {}", - reported.test, - message.text.replace('\n', " ") - ); - } - // A hazard report while a test holds them (`Messages::hold_hazards`): a repeat of - // one held is counted, a new one held, while there is room. - let hold = message.id_name.starts_with(HAZARD) - && match reported.held.as_mut() { - None => false, - Some(held) => { - let repeat = (held.iter_mut()).find(|(kept, _)| { - kept.id_name == message.id_name && kept.text == message.text - }); - if let Some((_, times)) = repeat { - *times += 1; - return; - } - held.len() < Self::MAX - } - }; - if ECHO.load(Ordering::Relaxed) { - use std::io::Write as _; - let _ = writeln!( - std::io::stderr(), - "VK_LAYER_KHRONOS_validation: {message:?}" - ); - } - if REPORT.load(Ordering::Relaxed) { - use std::io::Write as _; - let _ = writeln!( - std::io::stderr(), - "LANE-VALIDATION {}: {} ({}): {}", - reported.test, - message.id_name, - message.id, - message.text.replace('\n', " ") - ); - } - match reported.held.as_mut() { - Some(held) if hold => held.push((message, 1)), - _ => { - if reported.failing.len() < Self::MAX { - reported.failing.push(message); - } - } - } - }) - } -} - -/// The Vulkan loader library the runtime opens: its default name when that opens (the system -/// library path), else the first installed of the places the executor's own context also looks -/// (`candidate::platform::device`): Homebrew's and `/usr/local`'s on macOS. -pub fn loader() -> Option { - // SAFETY: opening the loader library runs only its initializers; the entry is dropped. - if unsafe { ash::Entry::load() }.is_ok() { - return None; - } - [ - "/opt/homebrew/lib/libvulkan.1.dylib", - "/opt/homebrew/lib/libvulkan.dylib", - "/usr/local/lib/libvulkan.1.dylib", - "/usr/local/lib/libvulkan.dylib", - ] - .into_iter() - .map(PathBuf::from) - .find(|path| path.is_file()) -} - -/// The validation layer every device validation makes through the runtime enables. -pub const VALIDATION_LAYER: &std::ffi::CStr = c"VK_LAYER_KHRONOS_validation"; - -/// The validation layer's settings the executor's devices are made with, as its own context sets -/// them: every occurrence of a message reported (`enable_message_limit` off: by default the layer -/// reports each message ID at most ten times per instance), and synchronization validation on. -pub fn executor_layer_settings() -> Vec { - [(c"enable_message_limit", false), (c"validate_sync", true)] - .into_iter() - .map(|(name, value)| { - LayerSetting::new( - VALIDATION_LAYER.to_owned(), - name.to_owned(), - LayerSettingValue::Bool(value), - ) - }) - .collect() -} - -/// The options of a device validation makes through the runtime: the validation layer reporting -/// to `messages`, its shader cache in `cache`, and the loader [`loader`] finds. Its policy takes -/// Metal's answer wherever the policy offers the device's instead (`DevicePolicy::exact_answers`: -/// the runtime's heap compression, completion, batch order, render lowering and host-page -/// textures), which changes no translation. The device's sampler and its arithmetic, rounding and -/// conversions answer Metal's only within their recorded bounds (`PrecisionNote::DeviceSampling`, -/// `DeviceTexelConversion`; `NativeTranscendentals`, `NativeDivision`, `NativeFma`; -/// `NativeHalfConversion`, `NativeHalfQuantize`; `NativeNanEncoding`, `NativeMinMax`; -/// `NativeDot`, `NativeMix`), which validation compares against Metal's answers by those notes; -/// the lane of the device's maths checks the bounds themselves (`runtime_lane::native_maths`). Its -/// devices keep execution records (`DeviceOptions::record_executions`), which the executor and the -/// lanes read. -pub fn validated_options(messages: &Messages, cache: &Path) -> DeviceOptions { - let mut options = DeviceOptions::default(); - options.policy = options.policy.exact_answers(); - options.shader_cache = ShaderCacheOptions::in_directory(cache); - options.loader = loader(); - options.layers.push(VALIDATION_LAYER.to_owned()); - options.messages = Some(messages.sink()); - // What a claim of what the validation layer reported stands on is what the instance enabled of - // this list, so the list is told what the device asks for (`layer_claim`). - messages.device_asked_layers(&options.layers); - // The executor and the lanes read what each dispatch and draw ran. - options.record_executions = true; - options -} - -/// The runtime's default device among the physical devices of `device_type`, made with -/// `options`, whose kinds this sets. A GPU is opened only while the hang tripwire is absent: every -/// device validation makes through the runtime opens here (`gpu.rs`'s test). -pub fn open_device(device_type: DeviceType, options: DeviceOptions) -> Result { - let options = checked_options(device_type, options)?; - Device::system_default_with(&options).map_err(CaseError::runtime("system_default_with")) -} - -/// Every device of `device_type` the runtime lists, made with `options`, whose kinds this sets, as -/// [`open_device`] makes the default one: opened only while the hang tripwire is absent. -pub fn open_devices( - device_type: DeviceType, - options: DeviceOptions, -) -> Result, CaseError> { - let options = checked_options(device_type, options)?; - Device::all_with(&options).map_err(CaseError::runtime("all_with")) -} - -/// `options` with the kinds of `device_type`, once the hang tripwire is found absent for a GPU. -fn checked_options( - device_type: DeviceType, - mut options: DeviceOptions, -) -> Result { - if device_type == DeviceType::Gpu { - crate::gpu::tripwire::refuse_if_tripped()?; - } - options.kinds = match device_type { - DeviceType::Cpu => vec![DeviceKind::Cpu], - DeviceType::Gpu => vec![ - DeviceKind::Discrete, - DeviceKind::Integrated, - DeviceKind::Virtual, - ], - }; - Ok(options) -} - -/// A shader cache directory one run or test owns: a new, empty directory in the project's scratch -/// root, removed when dropped (after the devices that use it), so a warm cache never stands in for -/// a translation a run measures. -/// -/// Dropping covers a return and an unwind, and a lane process that is killed or that exits before -/// its drop runs covers nothing -- which left 900 to 2200 of these on a host. The scratch root is -/// what closes that: the next run of any suite removes the directory of every run whose lock the -/// kernel has released, and no live run's ([`metal2vulkan_devtools::scratch`]). -pub struct ScratchCache(metal2vulkan_devtools::scratch::Owned); - -impl ScratchCache { - /// A new directory, not yet made (the device makes it). - pub fn new() -> std::io::Result { - metal2vulkan_devtools::scratch::Owned::reserved("lane-shader-cache").map(ScratchCache) - } - - /// The directory. - pub fn path(&self) -> &Path { - self.0.path() - } -} - -/// The usage the Metal oracle gives each texture of `case`, by Metal texture slot: its role -/// united with the AIR's declared access at its slot, with `ShaderAtomic` where a texture atomic -/// reaches it; an element of a texture array takes its array's declared access, and a later bind -/// of a slot wins (`metal::platform::textures`). -pub fn texture_usage( - case: &AuthoredCase, - interface: &AirInterface, -) -> Result, String> { - let resources = LiteralResources::prepare(case)?; - let mut usage = BTreeMap::new(); - for texture in &resources.textures { - let mut texture_usage = texture_shader_usage( - texture.role, - declared_texture_writable(interface, texture.binding), - ); - if declared_texture_atomic(interface, texture.binding) { - texture_usage |= TextureUsage::SHADER_ATOMIC; - } - usage.insert(texture.binding, texture_usage); - } - for array in &resources.texture_arrays { - let writable = declared_texture_writable(interface, array.binding); - for (element, texture) in (0u32..).zip(&array.elements) { - let slot = array - .binding - .checked_add(element) - .ok_or("a texture array's slot overflows")?; - usage.insert(slot, texture_shader_usage(texture.role, writable)); - } - } - Ok(usage) -} - -/// The usage the Metal oracle gives each of a function's argument-buffer `textures`, by its owner -/// and field offset: its role united with the declared access of the AIR member at its field -/// (`metal::platform::argument_buffers`), without the atomic usage a bound texture may take. -pub fn argument_texture_usage( - textures: &BTreeMap<(u32, u32), LiteralTexture>, - interface: &AirInterface, -) -> Result, String> { - textures - .iter() - .map(|(&(owner, field), texture)| { - let what = format!("argument-buffer texture {owner}+{field}"); - let (_, member) = interface - .member_at(owner, field) - .ok_or_else(|| format!("{what} is no AIR argument-buffer member"))?; - let ParamRole::Texture(declared) = &member.role else { - return Err(format!("{what} disagrees with its AIR member role")); - }; - let writable = declared_writable(declared.access); - Ok(( - (owner, field), - texture_shader_usage(texture.role, Some(writable)), - )) - }) - .collect() -} - -/// A Shared buffer of `bytes` (one zero byte when empty: Metal has no empty buffer). -pub fn buffer_with(device: &Device, bytes: &[u8]) -> Result { - buffer_with_options(device, bytes, ResourceOptions::shared()) -} - -/// A buffer of `options` (a storage mode the host reaches) holding `bytes`. -pub fn buffer_with_options( - device: &Device, - bytes: &[u8], - options: ResourceOptions, -) -> Result { - let buffer = device - .new_buffer(bytes.len().max(1) as u64, options) - .map_err(CaseError::runtime("new_buffer"))?; - write_contents(&buffer, bytes)?; - Ok(buffer) -} - -/// Write `bytes` at the start of `buffer`, which the host reaches and no command uses yet. -fn write_contents(buffer: &Buffer, bytes: &[u8]) -> Result<(), CaseError> { - if bytes.len() as u64 > buffer.length() { - return Err("bytes past the buffer's length".into()); - } - let contents = buffer.contents().ok_or("the buffer has no contents")?; - // SAFETY: the buffer holds at least `bytes.len()` bytes at `contents`, and no command uses - // it yet. - unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), contents.as_ptr(), bytes.len()) }; - Ok(()) -} - -/// A `Shared` buffer of `bytes` (one zero byte when empty) placed in a tracked placement heap of -/// its own between guards of `reach`: an out-of-bounds target's. The buffer lies at the first -/// multiple of the heap's placement alignment at least `reach.before` (and [`MIN_GUARD`]) bytes -/// into the heap, and the heap holds at least `reach.after` (and [`MIN_GUARD`]) bytes past the -/// buffer's length padded to 16. Those padding bytes (the contract: a descriptor's range may -/// include them) are the memory bound to the target past its end, holding `PAD_FILL`; every other -/// byte of the heap is its guard, holding `GUARD_FILL` ([`guard_count`] counts what a run changed). -/// Tracked, as a buffer of its own is. -pub fn guarded_buffer( - device: &Device, - bytes: &[u8], - reach: GuardReach, -) -> Result { - let options = ResourceOptions::new( - StorageMode::Shared, - CpuCacheMode::DefaultCache, - HazardTrackingMode::Tracked, - ); - let length = bytes.len().max(1) as u64; - let align = device.heap_buffer_size_and_align(length, options).align; - let front = u64::from(reach.before) - .max(MIN_GUARD) - .next_multiple_of(align); - let padded = length.next_multiple_of(16); - let size = front + padded + u64::from(reach.after).max(MIN_GUARD); - let heap = device - .new_heap(&HeapDescriptor::new(HeapType::Placement, size, options)) - .map_err(CaseError::runtime("new_heap"))?; - let mut fill = vec![GUARD_FILL; heap.size() as usize]; - fill[(front + length) as usize..(front + padded) as usize].fill(PAD_FILL); - write_contents(&placed(&heap, heap.size(), 0)?, &fill)?; - let buffer = placed(&heap, length, front)?; - write_contents(&buffer, bytes)?; - Ok(buffer) -} - -/// What a run changed around `buffer`, placed by [`guarded_buffer`], once no pending command -/// writes its heap: the guard bytes (every byte of the heap outside the buffer's length padded to -/// 16) that no longer hold `GUARD_FILL`, and the padding bytes past its length that no longer -/// hold `PAD_FILL`. -pub fn guard_count(buffer: &Buffer) -> Result { - let heap = buffer - .heap() - .filter(|heap| heap.heap_type() == HeapType::Placement) - .ok_or("a guarded target outside a placement heap")?; - let bytes = read_buffer(&placed(heap, heap.size(), 0)?, 0, heap.size())?; - let front = buffer.heap_offset() as usize; - let end = front + buffer.length() as usize; - let padded = front + buffer.length().next_multiple_of(16) as usize; - let changed = |bytes: &[u8], fill: u8| bytes.iter().filter(|&&byte| byte != fill).count(); - Ok(GuardCount { - escaped: (changed(&bytes[..front], GUARD_FILL) + changed(&bytes[padded..], GUARD_FILL)) - as u64, - past_end: changed(&bytes[end..padded], PAD_FILL) as u64, - }) -} - -/// A `Shared` buffer of `length` bytes `offset` bytes into `heap`, of the heap's modes. -fn placed(heap: &Heap, length: u64, offset: u64) -> Result { - heap.new_buffer_at_offset(length, ResourceOptions::shared(), offset) - .map_err(CaseError::runtime("new_buffer_at_offset")) -} - -/// A `Shared` buffer of the runtime's parameter data of `map`, made as the Metal oracle makes -/// Metal's (`metal::platform::buffers::rate_map_buffer`): the device makes the map -/// (`new_rasterization_rate_map`) and copies its data (`copy_parameter_data_to_buffer`) to offset 0 -/// of a buffer of the size it answers (`parameter_buffer_size_and_align`). -pub fn rate_map_buffer(device: &Device, map: &RateMapLiteral) -> Result { - let map = device - .new_rasterization_rate_map(&map.descriptor()) - .map_err(CaseError::runtime("new_rasterization_rate_map"))?; - let length = map.parameter_buffer_size_and_align().size.max(1); - let buffer = device - .new_buffer(length, ResourceOptions::shared()) - .map_err(CaseError::runtime("new_buffer"))?; - map.copy_parameter_data_to_buffer(&buffer, 0) - .map_err(CaseError::runtime("copy_parameter_data_to_buffer"))?; - Ok(buffer) -} - -/// `length` bytes of `buffer` from `offset`. No command that writes them is pending. -pub fn read_buffer(buffer: &Buffer, offset: u64, length: u64) -> Result, CaseError> { - let end = offset - .checked_add(length) - .filter(|&end| end <= buffer.length()) - .ok_or("a read past the buffer")?; - let contents = buffer - .contents() - .ok_or("a Private buffer has no contents")?; - // SAFETY: `[offset, end)` is inside the buffer's bytes, and no pending command writes them - // (the caller's contract). - let bytes = unsafe { - std::slice::from_raw_parts( - contents.as_ptr().add(offset as usize), - (end - offset) as usize, - ) - }; - Ok(bytes.to_vec()) -} - -/// The Metal texture of `literal` on `device`, made as the Metal oracle makes it (the module's -/// rule) with `usage`, holding the literal's bytes. A texture buffer is the oracle's too: a -/// texture over a `Shared` buffer of the literal's bytes, from its first byte, its row the -/// bytes' length. A multisampled texture is filled by a render pass the case's command buffer -/// runs ([`multisampled_texture_with`]: [`CaseResources::of`]'s textures, bound and in argument -/// buffers, and the render runner's), so it is refused here. A sparse texture is made from a -/// sparse heap and mapped before the work (`sparse.rs`). -pub fn texture_with( - device: &Device, - literal: &LiteralTexture, - usage: TextureUsage, -) -> Result { - let label = format!("texture {}", literal.binding); - if literal.sample_count != 1 { - return Err(format!("{label}: a multisampled texture its command buffer fills").into()); - } - if let Some(mappings) = &literal.sparse { - return sparse::texture_with(device, literal, mappings, usage); - } - if literal.texture_type == TextureType::Buffer { - return texture_buffer_over(&buffer_with(device, &literal.bytes)?, literal, usage); - } - let descriptor = texture_descriptor(literal, usage)?; - let texture = device - .new_texture(&descriptor) - .map_err(CaseError::runtime(format!("{label}: new_texture")))?; - // Each level's bytes, level 0 first, written at its level as the oracle writes them; a - // one-level texture's level 0 is every byte. - for level in 0..literal.mip_levels { - let (dimensions, bytes) = literal.level(level)?; - let span = subresource_span(literal.texture_type, [0; 3], dimensions, 1)?; - let (row, image, slice) = span_strides(&span, literal); - let needed = slice * span.slice_count as usize; - if bytes.len() < needed || needed == 0 { - return Err(format!( - "{label} supplies {} bytes but its level {level} needs {needed}", - bytes.len() - ) - .into()); - } - for index in 0..span.slice_count as usize { - texture - .replace_region( - span_region(&span), - level.into(), - u64::from(span.base_slice) + index as u64, - &bytes[index * slice..(index + 1) * slice], - row as u64, - image as u64, - ) - .map_err(CaseError::runtime(format!("{label}: replace_region")))?; - } - } - Ok(texture) -} - -/// The texture buffer of `literal`, of `usage`, over `buffer`, which holds the literal's bytes -/// from its first: the oracle's texture over a buffer, its row the bytes' length. -fn texture_buffer_over( - buffer: &Buffer, - literal: &LiteralTexture, - usage: TextureUsage, -) -> Result { - let label = format!("texture {}", literal.binding); - if literal.texture_type != TextureType::Buffer { - return Err(format!("{label}: a texture over a buffer that is no texture buffer").into()); - } - buffer - .new_texture( - &texture_descriptor(literal, usage)?, - 0, - literal.bytes.len() as u64, - ) - .map_err(CaseError::runtime(format!( - "{label}: new_texture over a buffer" - ))) -} - -/// The descriptor the Metal oracle makes `literal`'s texture with, of `usage`: its type, pixel -/// format and extent, `Shared`, its levels (one but where the case declares more). -pub fn texture_descriptor( - literal: &LiteralTexture, - usage: TextureUsage, -) -> Result { - let layout = literal.layout()?; - let mut descriptor = TextureDescriptor::default(); - descriptor.texture_type = texture_type(literal.texture_type); - descriptor.pixel_format = pixel_format(literal.format); - descriptor.width = layout.width.into(); - descriptor.height = layout.height.into(); - descriptor.depth = layout.depth.into(); - // Metal's `arrayLength` counts cubes for a cube array. - descriptor.array_length = match literal.texture_type { - TextureType::Cube => 1, - TextureType::CubeArray => (layout.array_layers / 6).into(), - _ => layout.array_layers.into(), - }; - descriptor.mipmap_level_count = literal.mip_levels.into(); - descriptor.usage = usage; - descriptor.resource_options = ResourceOptions::shared(); - Ok(descriptor) -} - -/// The bytes of one row, one image and one slice of `span` of `literal`, tightly packed. -fn span_strides(span: &SubresourceSpan, literal: &LiteralTexture) -> (usize, usize, usize) { - let row = span.size[0] as usize * literal.format.bytes_per_pixel(); - let image = row * span.size[1] as usize; - (row, image, image * span.size[2] as usize) -} - -/// The region of one slice `span` names. -fn span_region(span: &SubresourceSpan) -> Region { - Region::new_3d( - span.origin[0].into(), - span.origin[1].into(), - span.origin[2].into(), - span.size[0].into(), - span.size[1].into(), - span.size[2].into(), - ) -} - -/// The `(origin, dimensions)` selection, in the case's spelling, of `texture` (made from -/// `literal`), read per slice with `get_bytes` as the Metal oracle reads it. No command that -/// writes it is pending. -pub fn read_texture( - texture: &Texture, - literal: &LiteralTexture, - origin: [u32; 3], - dimensions: [u32; 3], -) -> Result, CaseError> { - let span = subresource_span(literal.texture_type, origin, dimensions, 1)?; - let (row, image, slice) = span_strides(&span, literal); - let mut output = vec![0u8; slice * span.slice_count as usize]; - for (index, bytes) in output.chunks_exact_mut(slice.max(1)).enumerate() { - texture - .get_bytes( - bytes, - row as u64, - image as u64, - span_region(&span), - 0, - u64::from(span.base_slice) + index as u64, - ) - .map_err(CaseError::runtime(format!( - "texture {}: get_bytes", - literal.binding - )))?; - } - Ok(output) -} - -/// What a case binds besides its buffers: textures and sampler states, by Metal slot; the -/// buffers, textures and sampler states its argument buffers hold, by owner slot and field -/// offset; its visible-function tables, by Metal buffer index, which its pipeline state makes -/// ([`visible_function_tables`]; [`encoded_case`] takes them); the fills of its multisampled -/// textures, which the command buffer that reads them runs first ([`SampleFill::encode`]); and -/// the buffer under each texture buffer an out-of-bounds target guards ([`guarded_buffer`]), by -/// Metal slot, whose heap its guard count reads ([`Committed::guard_counts`]). -#[derive(Default)] -pub struct CaseResources { - pub textures: BTreeMap, - pub samplers: BTreeMap, - pub argument_buffers: BTreeMap<(u32, u32), Buffer>, - pub argument_textures: BTreeMap<(u32, u32), Texture>, - pub argument_samplers: BTreeMap<(u32, u32), SamplerState>, - pub tables: BTreeMap, - pub fills: Vec, - pub guarded_texture_buffers: BTreeMap, - pub commands: CaseCommands, -} - -impl CaseResources { - /// `compute`'s textures (holding their bytes, each of its `usage`, or for an argument-buffer - /// texture its `argument_usage`) and sampler states on `device`, bound and in argument - /// buffers, and its argument-buffer buffers (a rate map's, [`rate_map_buffer`]); no table (a - /// pipeline state makes those). An argument-buffer buffer or a texture buffer that is an - /// out-of-bounds target lies in a heap of its own between guards ([`guarded_buffer`]). - pub fn of( - device: &Device, - compute: &ComputeCase, - usage: &BTreeMap, - argument_usage: &BTreeMap<(u32, u32), TextureUsage>, - ) -> Result { - let mut textures = BTreeMap::new(); - let mut fills = Vec::new(); - let mut guarded_texture_buffers = BTreeMap::new(); - for (&slot, literal) in &compute.textures { - let usage = usage - .get(&slot) - .copied() - .ok_or_else(|| format!("texture {slot} has no usage"))?; - let texture = if let Some(reach) = texel_guard_reach(compute, slot) { - let buffer = guarded_buffer(device, &literal.bytes, reach)?; - let texture = texture_buffer_over(&buffer, literal, usage)?; - guarded_texture_buffers.insert(slot, buffer); - texture - } else { - filled_texture(device, literal, usage, &mut fills)? - }; - textures.insert(slot, texture); - } - let samplers = compute - .samplers - .iter() - .map(|(&slot, sampler)| { - let state = device - .new_sampler_state(&sampler_descriptor(sampler)) - .map_err(CaseError::runtime(format!( - "sampler {slot}: new_sampler_state" - )))?; - Ok((slot, state)) - }) - .collect::>()?; - // A command buffer's field holds the command buffer, not the record storage the mapped - // case states for the executor (`commands`). - let argument_buffers = compute - .argument_buffer_buffers - .iter() - .filter(|(key, _)| !compute.command_buffers.contains_key(key)) - .map(|(&key, bytes)| { - let buffer = match ( - compute.argument_buffer_rate_maps.get(&key), - embedded_guard_reach(compute, key), - ) { - (Some(map), _) => rate_map_buffer(device, map)?, - (None, Some(reach)) => guarded_buffer(device, bytes, reach)?, - (None, None) => buffer_with(device, bytes)?, - }; - Ok((key, buffer)) - }) - .collect::>()?; - let argument_textures = argument_textures( - device, - &compute.argument_buffer_textures, - argument_usage, - &mut fills, - )?; - let argument_samplers = argument_samplers(device, &compute.argument_buffer_samplers)?; - Ok(CaseResources { - textures, - samplers, - argument_buffers, - argument_textures, - argument_samplers, - tables: BTreeMap::new(), - fills, - guarded_texture_buffers, - commands: CaseCommands::of(device, &compute.command_buffers)?, - }) - } -} - -/// A function's argument-buffer `textures` on `device`, by `(owner, field)`, each holding its -/// contents with its `usage` ([`argument_texture_usage`]), a multisampled one's fill joining -/// `fills` ([`filled_texture`]). -fn argument_textures( - device: &Device, - textures: &BTreeMap<(u32, u32), LiteralTexture>, - usage: &BTreeMap<(u32, u32), TextureUsage>, - fills: &mut Vec, -) -> Result, CaseError> { - textures - .iter() - .map(|(&key, literal)| { - let usage = usage - .get(&key) - .copied() - .ok_or_else(|| format!("argument-buffer texture {key:?} has no usage"))?; - Ok((key, filled_texture(device, literal, usage, fills)?)) - }) - .collect() -} - -/// A function's argument-buffer `samplers` on `device`, by `(owner, field)`: each a sampler state -/// made for argument buffers (`support_argument_buffers`), as the Metal oracle makes it. -fn argument_samplers( - device: &Device, - samplers: &BTreeMap<(u32, u32), ArgumentBufferSamplerResource>, -) -> Result, CaseError> { - let mut options = SamplerStateOptions::default(); - options.support_argument_buffers = true; - samplers - .iter() - .map(|(&key, sampler)| { - let state = device - .new_sampler_state_with_options(&argument_sampler_descriptor(sampler), options) - .map_err(CaseError::runtime(format!( - "argument-buffer sampler {key:?}: new_sampler_state" - )))?; - Ok((key, state)) - }) - .collect() -} - -/// The word each member's owner holds at its field, by `(owner, field)`, as Metal's argument -/// encoder writes it: `members` of each kind, a field two members name refused. -fn member_words( - members: impl IntoIterator, -) -> Result, CaseError> { - let mut fields = BTreeMap::new(); - for (key, word) in members { - if fields.insert(key, word).is_some() { - return Err(format!("argument-buffer field {key:?} holds two members").into()); - } - } - Ok(fields) -} - -/// The texture of `literal` on `device` with `usage`, as [`texture_with`] makes it, or a -/// multisampled one ([`multisampled_texture_with`]) whose fill, a render pass the case's command -/// buffer runs before its work, joins `fills`, as the Metal oracle fills one wherever the case -/// holds it. -fn filled_texture( - device: &Device, - literal: &LiteralTexture, - usage: TextureUsage, - fills: &mut Vec, -) -> Result { - if literal.sample_count == 1 { - return texture_with(device, literal, usage); - } - let (texture, fill) = multisampled_texture_with(device, literal, usage)?; - fills.push(fill); - Ok(texture) -} - -/// `case`'s bound buffers, each holding its bytes, or a rate map's the runtime's parameter data -/// ([`rate_map_buffer`]): an argument buffer's owner also holds, at each field, what Metal's -/// argument encoder writes there for the member of `resources` there: an argument-buffer buffer's -/// `gpu_address`, or a texture's or sampler state's `gpu_resource_id`. A field two members name -/// is refused. A buffer that is an out-of-bounds target, or holds the stage input that is one, -/// lies in a heap of its own between guards ([`guarded_buffer`]). -pub fn bound_buffers( - device: &Device, - case: &ComputeCase, - resources: &CaseResources, -) -> Result, CaseError> { - let buffers = resources - .argument_buffers - .iter() - .map(|(&key, buffer)| (key, buffer.gpu_address().0)); - let textures = resources - .argument_textures - .iter() - .map(|(&key, texture)| (key, texture.gpu_resource_id().0)); - let samplers = resources - .argument_samplers - .iter() - .map(|(&key, sampler)| (key, sampler.gpu_resource_id().0)); - let fields = member_words( - buffers - .chain(textures) - .chain(samplers) - .chain(resources.commands.words()), - )?; - case.buffers - .keys() - .map(|&index| { - if let Some(map) = case.rate_maps.get(&index) { - return Ok((index, rate_map_buffer(device, map)?)); - } - let bytes = owner_bytes(&case.buffers, index, &fields)?; - let buffer = match guard_reach(case, index) { - Some(reach) => guarded_buffer(device, &bytes, reach)?, - None => buffer_with(device, &bytes)?, - }; - Ok((index, buffer)) - }) - .collect() -} - -/// The descriptor of `case`'s compute pipeline state, as the Metal oracle states it: its kernel -/// `function` (made with the case's constant values) linking `linked`, and the case's stage-input -/// descriptor (`stageInputDescriptor`), Metal's defaults otherwise. -pub fn compute_descriptor( - function: &Function, - linked: LinkedFunctions, - case: &ComputeCase, -) -> ComputePipelineDescriptor { - let mut descriptor = ComputePipelineDescriptor::new(StageSource::Function( - function.function_descriptor().with_linked(linked), - )); - descriptor.stage_input = case.stage_input.clone(); - descriptor -} - -/// The functions a case links, made on a device ([`linked_functions`]): what its pipeline -/// descriptor links (`functions`), and each function made, by its module's SHA-256 and its Metal -/// name, the pair a visible-function table's entry names ([`visible_function_tables`]). -pub struct LinkedSet { - pub functions: LinkedFunctions, - made: BTreeMap<(String, String), Function>, -} - -impl LinkedSet { - /// The function `name` of the module whose SHA-256 is `module_sha256`, if the set links it. - fn function(&self, module_sha256: &str, name: &str) -> Option<&Function> { - self.made.get(&(module_sha256.to_owned(), name.to_owned())) - } -} - -/// The functions `modules` supply, each library's in turn, every one made with `constants`, as -/// the Metal oracle links them (`load_linked_functions`): a value for a constant a function does -/// not declare is ignored. -pub fn linked_functions( - device: &Device, - modules: &[LinkedModule], - constants: &metal2vulkan::library::FunctionConstantValues, -) -> Result { - let mut functions = LinkedFunctions::new(); - let mut made = BTreeMap::new(); - for module in modules { - let library = device - .new_library_with_air(&module.bitcode) - .map_err(CaseError::runtime("new_library_with_air"))?; - for name in &module.library.functions { - let function = library - .new_function_with_name_constant_values(name, constants) - .map_err(CaseError::runtime("new_function_with_name_constant_values"))?; - functions = functions.with_function(function.linked_function()); - made.insert((module.module_sha256.clone(), name.clone()), function); - } - } - Ok(LinkedSet { functions, made }) -} - -/// A kernel case's visible-function tables made for its pipeline state -/// ([`visible_function_tables`]): each table by Metal buffer index, and the bytes the runtime -/// wrote to each (`FunctionTableWords` of its size, each entry the word of the handle the state -/// gave), keyed by the kernel stage and the index as the executor's artifact records a table's -/// buffer (`tables::TableBuffers`). -pub struct CaseTables { - pub tables: BTreeMap, - pub words: TableBuffers, -} - -/// The visible-function tables of `case` for `pipeline`, by Metal buffer index, as the Metal -/// oracle makes them (`newVisibleFunctionTableWithDescriptor:` and `setFunction:atIndex:` of -/// `functionHandleWithFunction:`): a table of the authored size, each authored entry the handle -/// `pipeline` gives the function it holds among `linked`, every other entry null. An entry whose -/// function `linked` does not hold, or that the pipeline gives no handle, cannot run (the executor -/// links every entry's module into `functions`, as the oracle does). Each table's bytes are the -/// words the runtime writes: an entry's is the word of the handle `linked`'s functions give its -/// function (`LinkedFunctions::function_handle`), which is the handle the state answers, the state -/// linking those functions. -pub fn visible_function_tables( - pipeline: &ComputePipelineState, - case: &ComputeCase, - linked: &LinkedSet, -) -> Result { - tables_of( - (ShaderStage::Kernel, &case.function_tables), - linked, - |descriptor| pipeline.new_visible_function_table(descriptor), - |function| pipeline.function_handle(function), - ) -} - -/// The visible-function tables `authored` of a function of `stage`, each made by `make` and each -/// entry the handle `handle` gives the function it holds among `linked`, as -/// [`visible_function_tables`] states it for a kernel; a render state's stage makes its own -/// (`render.rs`), its words keyed by that stage. -fn tables_of( - (stage, authored): (ShaderStage, &BTreeMap), - linked: &LinkedSet, - make: impl Fn(&VisibleFunctionTableDescriptor) -> Result, - handle: impl Fn(&Function) -> Result, Error>, -) -> Result { - let mut made = CaseTables { - tables: BTreeMap::new(), - words: TableBuffers::new(), - }; - for (&binding, authored) in authored { - let descriptor = VisibleFunctionTableDescriptor::new(authored.size.into()); - let table = make(&descriptor).map_err(CaseError::runtime(format!( - "table {binding}: new_visible_function_table" - )))?; - let mut words = FunctionTableWords::new(authored.size); - for (&index, entry) in &authored.entries { - let function = linked - .function(&entry.module_sha256, &entry.function) - .ok_or_else(|| { - format!( - "table {binding} entry {index}: {} of module {} is not linked", - entry.function, entry.module_sha256 - ) - })?; - let no_handle = || { - format!( - "table {binding} entry {index}: the pipeline gives linked function {} no \ - handle", - entry.function - ) - }; - let handle = handle(function) - .map_err(CaseError::runtime(format!( - "table {binding} entry {index}: function_handle" - )))? - .ok_or_else(no_handle)?; - table - .set_function(Some(&handle), index) - .map_err(CaseError::runtime(format!( - "table {binding}: set_function {index}" - )))?; - let word = linked - .functions - .function_handle(&function.linked_function()) - .ok_or_else(no_handle)?; - if !words.set(index, Some(word)) { - return Err(format!("table {binding} has no entry {index}").into()); - } - } - made.tables.insert(binding, table); - made.words.insert((stage, binding), words.to_bytes()); - } - Ok(made) -} - -/// Encode `case`'s dispatch on `encoder` with `pipeline`, over `buffers` and `resources` (by Metal -/// slot, its tables by Metal buffer index, its argument-buffer buffers and textures resident for -/// reading and writing), the case's threadgroup memory lengths, its imageblock size -/// (`setImageblockWidth:height:`), and, for a case with stage inputs dispatching a grid of threads, -/// the case's stage-in region or that grid's from the origin, the region the oracle sets -/// (`stage_inputs::region`). A stage input of a dynamic layout's data is bound with the stride form -/// at its case's stride ([`ComputeCase::attribute_strides`]). -pub fn encode_case( - encoder: &mut ComputeCommandEncoder, - pipeline: &ComputePipelineState, - case: &ComputeCase, - buffers: &BTreeMap, - resources: &CaseResources, -) -> Result<(), CaseError> { - encoder - .set_compute_pipeline_state(pipeline) - .map_err(CaseError::runtime("set_compute_pipeline_state"))?; - for (&index, buffer) in buffers { - match case.attribute_strides.get(&index) { - Some(&stride) => encoder - .set_buffer_with_stride(Some(buffer), 0, stride.into(), index) - .map_err(CaseError::runtime(format!( - "set_buffer_with_stride {index}" - )))?, - None => encoder - .set_buffer(Some(buffer), 0, index) - .map_err(CaseError::runtime(format!("set_buffer {index}")))?, - } - } - for (&index, table) in &resources.tables { - encoder - .set_visible_function_table(Some(table), index) - .map_err(CaseError::runtime(format!( - "set_visible_function_table {index}" - )))?; - } - for (&index, texture) in &resources.textures { - encoder - .set_texture(Some(texture), index) - .map_err(CaseError::runtime(format!("set_texture {index}")))?; - } - for (&index, sampler) in &resources.samplers { - encoder - .set_sampler_state(Some(sampler), index) - .map_err(CaseError::runtime(format!("set_sampler_state {index}")))?; - } - let members: Vec<_> = resources - .argument_buffers - .values() - .map(Buffer::as_resource) - .chain( - resources - .argument_textures - .values() - .map(Texture::as_resource), - ) - .chain(resources.commands.resources()) - .collect(); - if !members.is_empty() { - encoder - .use_resources(&members, ResourceUsage::READ | ResourceUsage::WRITE) - .map_err(CaseError::runtime("use_resources"))?; - } - for (&index, &length) in &case.threadgroup_lengths { - encoder - .set_threadgroup_memory_length(length, index) - .map_err(CaseError::runtime(format!( - "set_threadgroup_memory_length {index}" - )))?; - } - if let Some([width, height]) = case.imageblock { - encoder - .set_imageblock_size(width.into(), height.into()) - .map_err(CaseError::runtime("set_imageblock_size"))?; - } - if let (Some(_), Dispatch::Threads { threads, .. }) = (&case.stage_input, case.dispatch) { - let region = stage_inputs::region(case.stage_in_region, threads); - let [x, y, z] = region.origin.map(u64::from); - let [width, height, depth] = region.size.map(u64::from); - encoder - .set_stage_in_region(Region::new_3d(x, y, z, width, height, depth)) - .map_err(CaseError::runtime("set_stage_in_region"))?; - } - let size = |axes: [u32; 3]| Size::new(axes[0].into(), axes[1].into(), axes[2].into()); - match case.dispatch { - Dispatch::Threads { - threads, - threads_per_group, - } => encoder - .dispatch_threads(size(threads), size(threads_per_group)) - .map_err(CaseError::runtime("dispatch")), - Dispatch::Threadgroups { - groups, - threads_per_group, - } => encoder - .dispatch_threadgroups(size(groups), size(threads_per_group)) - .map_err(CaseError::runtime("dispatch")), - other => Err(format!("the dispatch {other:?} is a later runtime step").into()), - } -} - -/// A kernel case's work encoded on its device and not yet committed ([`encoded_case`], or a tile -/// kernel's [`encoded_tile`]): its command buffer, what it binds, a tile kernel's pass's -/// attachments by color index, and what its dispatch executed (the command buffer's executions -/// after its fills'). The executions are known before anything runs, so a caller decides from them -/// whether to run the work ([`Encoded::commit`]); dropped uncommitted, it never runs. -pub struct Encoded { - pub command_buffer: CommandBuffer, - pub buffers: BTreeMap, - pub resources: CaseResources, - pub attachments: BTreeMap, - pub executions: Vec, -} - -/// A kernel case's work committed on its device ([`Encoded::commit`]). -pub struct Committed { - pub command_buffer: CommandBuffer, - pub buffers: BTreeMap, - pub resources: CaseResources, - pub attachments: BTreeMap, - pub executions: Vec, -} - -/// Encode `case`'s dispatch on `device` with `pipeline` (the pipeline state of its entry), its -/// visible-function `tables` ([`visible_function_tables`]), the pipeline state of each token its -/// commands and argument buffers name (`templates`, each made with -/// `support_indirect_command_buffers`), and the textures' `usage` and `argument_usage` -/// ([`CaseResources::of`]): its resources holding their bytes and its command buffers the host's -/// commands (`commands`), one command buffer with the fills of its multisampled textures, then one -/// compute encoder, ended, then the copy of each `Private` command buffer into its twin. The -/// encoded case holds the tables with its other resources. -pub fn encoded_case( - device: &Device, - case: &ComputeCase, - usage: &BTreeMap, - argument_usage: &BTreeMap<(u32, u32), TextureUsage>, - pipeline: &ComputePipelineState, - (tables, templates): ( - BTreeMap, - &BTreeMap, - ), -) -> Result { - let mut resources = CaseResources::of(device, case, usage, argument_usage)?; - resources.tables = tables; - resources.commands.states = pipeline_states(&case.objects, templates)?; - let buffers = bound_buffers(device, case, &resources)?; - commands::encode_host_commands( - &case.command_buffers, - &resources.commands, - &buffers, - templates, - )?; - let queue = device - .new_command_queue() - .map_err(CaseError::runtime("new_command_queue"))?; - let command_buffer = queue - .command_buffer() - .map_err(CaseError::runtime("command_buffer"))?; - for fill in &resources.fills { - fill.encode(&command_buffer)?; - } - let filled = command_buffer.executions().len(); - let mut encoder = command_buffer - .compute_command_encoder() - .map_err(CaseError::runtime("compute_command_encoder"))?; - encode_case(&mut encoder, pipeline, case, &buffers, &resources)?; - encoder - .end_encoding() - .map_err(CaseError::runtime("end_encoding"))?; - commands::encode_twin_copies(&command_buffer, &resources.commands)?; - // Each ended encoder's executions join the command buffer's in encoding order (a blit adds - // none). - let executions = command_buffer.executions().split_off(filled); - Ok(Encoded { - command_buffer, - buffers, - resources, - attachments: BTreeMap::new(), - executions, - }) -} - -impl Encoded { - /// Commit the encoded work. - pub fn commit(self) -> Result { - let Encoded { - command_buffer, - buffers, - resources, - attachments, - executions, - } = self; - command_buffer - .commit() - .map_err(CaseError::runtime("commit"))?; - Ok(Committed { - command_buffer, - buffers, - resources, - attachments, - executions, - }) - } -} - -/// [`encoded_case`] of a case whose commands and argument buffers name no pipeline token, -/// committed. Nothing is committed when a call is refused. -pub fn commit_case( - device: &Device, - case: &ComputeCase, - usage: &BTreeMap, - argument_usage: &BTreeMap<(u32, u32), TextureUsage>, - pipeline: &ComputePipelineState, - tables: BTreeMap, -) -> Result { - encoded_case( - device, - case, - usage, - argument_usage, - pipeline, - (tables, &BTreeMap::new()), - )? - .commit() -} - -impl Committed { - /// What the run changed around each of `case`'s targets it placed between guards - /// ([`guard_count`]), by target, once the command buffer completed: a bound buffer's (or the - /// stage input's whose data it binds), an argument-buffer buffer's, and a texture buffer's. - pub fn guard_counts( - &self, - case: &ComputeCase, - ) -> Result, CaseError> { - let mut counts = BTreeMap::new(); - for (&index, buffer) in &self.buffers { - if guard_reach(case, index).is_some() { - counts.insert(buffer_target(case, index), guard_count(buffer)?); - } - } - for (&key, buffer) in &self.resources.argument_buffers { - if embedded_guard_reach(case, key).is_some() { - let (buffer_binding, field_offset) = key; - let target = OutOfBoundsResource::ArgumentBufferBuffer { - buffer_binding, - field_offset, - }; - counts.insert(target, guard_count(buffer)?); - } - } - for (&binding, buffer) in &self.resources.guarded_texture_buffers { - counts.insert( - OutOfBoundsResource::Texture { binding }, - guard_count(buffer)?, - ); - } - Ok(counts) - } - - /// The bytes `case`'s output selects, once the command buffer completed. - pub fn output(&self, case: &ComputeCase) -> Result, CaseError> { - match case.output { - ComputeOutput::Buffer { - binding, - offset, - length, - } => read_buffer( - self.buffers - .get(&binding) - .ok_or_else(|| format!("the output buffer {binding} is not bound"))?, - offset, - length, - ), - ComputeOutput::Texture { - binding, - origin, - dimensions, - } => read_texture( - self.resources - .textures - .get(&binding) - .ok_or_else(|| format!("the output texture {binding} is not bound"))?, - case.textures - .get(&binding) - .ok_or_else(|| format!("the output texture {binding} is not declared"))?, - origin, - dimensions, - ), - ComputeOutput::ArgumentBufferBuffer { - owner, - field_offset, - offset, - length, - } => read_buffer( - self.resources - .argument_buffers - .get(&(owner, field_offset)) - .ok_or_else(|| { - format!("no argument-buffer buffer at {owner}+{field_offset}") - })?, - offset, - length, - ), - ComputeOutput::ArgumentBufferTexture { - owner, - field_offset, - origin, - dimensions, - } => read_texture( - self.resources - .argument_textures - .get(&(owner, field_offset)) - .ok_or_else(|| { - format!("no argument-buffer texture at {owner}+{field_offset}") - })?, - case.argument_buffer_textures - .get(&(owner, field_offset)) - .ok_or_else(|| { - format!("argument-buffer texture {owner}+{field_offset} undeclared") - })?, - origin, - dimensions, - ), - ComputeOutput::RenderTarget { - index, - origin, - dimensions, - } => read_texture( - self.attachments - .get(&index) - .ok_or_else(|| format!("the output attachment {index} is not attached"))?, - case.tile - .as_ref() - .and_then(|pass| pass.attachments.get(&index)) - .ok_or_else(|| format!("the output attachment {index} is not declared"))?, - [origin[0], origin[1], 0], - [dimensions[0], dimensions[1], 1], - ), - ComputeOutput::None => Ok(Vec::new()), - } - } -} diff --git a/crates/metal2vulkan-validation/src/candidate/runtime_case/commands.rs b/crates/metal2vulkan-validation/src/candidate/runtime_case/commands.rs deleted file mode 100644 index 6fb4b47a9..000000000 --- a/crates/metal2vulkan-validation/src/candidate/runtime_case/commands.rs +++ /dev/null @@ -1,599 +0,0 @@ -//! A case's indirect command buffers and pipeline states through the runtime, made and run as the -//! Metal oracle makes and runs them (`metal::platform::indirect_commands`): a kernel's -//! (`runtime_case::encoded_case`) and a draw's (`runtime_case::encoded_render`). -//! -//! Each authored command buffer is an `IndirectCommandBuffer` of the oracle's descriptor (compute -//! commands' types from the authored dispatch kinds and their kernel buffer and -//! threadgroup-length counts; render commands' `DRAW` and their vertex and fragment buffer -//! counts; the authored inheritance), of the authored capacity, `Shared` where the host encodes -//! commands and `Private` otherwise. Its argument-buffer field holds its `gpu_resource_id`, as the -//! oracle's argument encoder writes it (`setIndirectCommandBuffer:atIndex:`), and a pipeline -//! state's field the `gpu_resource_id` of the template's state, compute or render, made with -//! `support_indirect_command_buffers` ([`CaseCommands::words`], [`TemplateState`]). The host's -//! commands are encoded through their setters before the producer runs -//! (`encode_host_commands`); the producer's encoder makes each command buffer resident for -//! reading and writing. Once the producer completed, each command buffer's commands are read back -//! as the runtime decodes them ([`CaseCommands::check_commands`], the host contract's check of what -//! the producer wrote: a `Private` one through a blit copy into a `Shared` twin the producer's -//! command buffer makes), and each command buffer the case executes runs in key order, each in a -//! command buffer of its own committed after the one before it on the producer's queue -//! ([`encoded_execution`]): compute commands in a compute encoder, render commands in a render -//! encoder of the oracle's pass (its one attachment a 1x1 `R8Unorm` sink, neither loaded nor -//! stored), with the parent's pipeline state and buffers, every case buffer and argument-buffer -//! buffer resident for reading and writing, and `execute_commands_in_buffer` over the execution -//! range. - -use super::CaseError; -use crate::case::indirect_commands::{ - metal_index_type, metal_primitive_type, CommandBufferResource, CommandDescriptor, HostAction, - HostCommand, -}; -use metal2vulkan::metal::{PixelFormat, RenderStages, ResourceUsage, TextureUsage}; -use metal2vulkan_runtime::{ - Buffer, CommandBuffer, CommandQueue, ComputePipelineState, Device, IndirectCommandBuffer, - IndirectCommandBufferDescriptor, LoadAction, Region, RenderPassDescriptor, RenderPipelineState, - ResourceId, ResourceOptions, ResourceRef, Size, StoreAction, TextureDescriptor, -}; -use std::collections::BTreeMap; - -/// The state of a pipeline template, made with `support_indirect_command_buffers`: a kernel's -/// compute state, or a vertex or fragment case's render state. -#[derive(Clone)] -pub enum TemplateState { - Compute(ComputePipelineState), - Render(RenderPipelineState), -} - -impl TemplateState { - /// What Metal's argument encoder writes at a pipeline state field for it. - pub fn gpu_resource_id(&self) -> ResourceId { - match self { - TemplateState::Compute(state) => state.gpu_resource_id(), - TemplateState::Render(state) => state.gpu_resource_id(), - } - } -} - -/// A case's indirect command buffers and the pipeline states its argument buffers hold, each by -/// `(owner Metal index, field offset)`: a kernel's, or one stage's of a draw. -#[derive(Default)] -pub struct CaseCommands { - /// Each command buffer. - pub buffers: BTreeMap<(u32, u32), IndirectCommandBuffer>, - /// The `Shared` twin of each `Private` command buffer, which the producer's command buffer - /// copies it into after its dispatch or draw, so its commands read back - /// ([`CaseCommands::check_commands`]). - pub twins: BTreeMap<(u32, u32), IndirectCommandBuffer>, - /// Each pipeline state an argument buffer holds: its token's template's state. - pub states: BTreeMap<(u32, u32), TemplateState>, -} - -impl CaseCommands { - /// `command_buffers` on `device`, as the oracle makes them, each with a twin where it is - /// `Private`; no pipeline state (a caller sets [`CaseCommands::states`] from the templates it - /// made, `pipeline_states`). - pub fn of( - device: &Device, - command_buffers: &BTreeMap<(u32, u32), CommandBufferResource>, - ) -> Result { - let mut commands = CaseCommands::default(); - for (&key, resource) in command_buffers { - let descriptor = descriptor(resource); - let made = |options| { - device - .new_indirect_command_buffer(&descriptor, resource.capacity.into(), options) - .map_err(CaseError::runtime(format!( - "command buffer {key:?}: new_indirect_command_buffer" - ))) - }; - let options = if resource.commands.is_empty() { - commands.twins.insert(key, made(ResourceOptions::shared())?); - ResourceOptions::private() - } else { - ResourceOptions::shared() - }; - commands.buffers.insert(key, made(options)?); - } - Ok(commands) - } - - /// The word each command buffer's and pipeline state's owner holds at its field, as Metal's - /// argument encoder writes it: its `gpu_resource_id`. - pub fn words(&self) -> impl Iterator + '_ { - let buffers = self - .buffers - .iter() - .map(|(&key, icb)| (key, icb.gpu_resource_id().0)); - let states = self - .states - .iter() - .map(|(&key, state)| (key, state.gpu_resource_id().0)); - buffers.chain(states) - } - - /// Each command buffer, which the producer's encoder makes resident for reading and writing. - pub fn resources(&self) -> impl Iterator> { - self.buffers - .values() - .map(IndirectCommandBuffer::as_resource) - } - - /// The command buffer at `key`. - fn buffer(&self, key: (u32, u32)) -> Result<&IndirectCommandBuffer, CaseError> { - self.buffers - .get(&key) - .ok_or_else(|| format!("command buffer {key:?} was not made").into()) - } - - /// Read back, once the producer completed, the commands of each command buffer as the runtime - /// decodes them (a `Private` one's from its twin): the host contract's check of what the - /// producer wrote, as the oracle's guard and the executor's decode check it. - pub fn check_commands(&self) -> Result<(), CaseError> { - for (key, icb) in &self.buffers { - let readable = self.twins.get(key).unwrap_or(icb); - readable - .commands(0..readable.size()) - .map_err(CaseError::runtime(format!( - "command buffer {key:?}: commands" - )))?; - } - Ok(()) - } -} - -/// The pipeline state each of `objects`' fields (`(owner Metal index, field offset)` to token) -/// holds: the state `templates` makes for its token, made with `support_indirect_command_buffers`. -pub fn pipeline_states( - objects: &BTreeMap<(u32, u32), u64>, - templates: &BTreeMap, -) -> Result, CaseError> { - objects - .iter() - .map(|(&key, token)| { - let state = templates - .get(token) - .ok_or_else(|| format!("pipeline token {token} has no template"))?; - Ok((key, state.clone())) - }) - .collect() -} - -/// The runtime's descriptor of `resource`, as the oracle states its own -/// (`metal::indirect_command_descriptor`): for compute commands no vertex or fragment buffers, -/// the authored kernel counts, its command types the authored dispatch kinds; for render commands -/// the authored draw kinds (`DRAW`, `DRAW_INDEXED`, `DRAW_PATCHES`, `DRAW_INDEXED_PATCHES`, -/// `DRAW_MESH_THREADGROUPS`, `DRAW_MESH_THREADS`) and vertex, fragment, object and mesh buffer -/// counts, no kernel buffers; and the authored inheritance. -fn descriptor(resource: &CommandBufferResource) -> IndirectCommandBufferDescriptor { - let mut descriptor = IndirectCommandBufferDescriptor::new(); - descriptor.command_types = resource.descriptor.command_types(); - match resource.descriptor { - CommandDescriptor::Compute { - max_buffer_bind_count, - max_threadgroup_memory_bind_count, - support_dynamic_attribute_stride, - .. - } => { - descriptor.max_kernel_buffer_bind_count = max_buffer_bind_count; - descriptor.max_kernel_threadgroup_memory_bind_count = max_threadgroup_memory_bind_count; - descriptor.support_dynamic_attribute_stride = support_dynamic_attribute_stride; - } - CommandDescriptor::Render { - max_vertex_buffer_bind_count, - max_fragment_buffer_bind_count, - max_object_buffer_bind_count, - max_mesh_buffer_bind_count, - support_dynamic_attribute_stride, - .. - } => { - descriptor.max_vertex_buffer_bind_count = max_vertex_buffer_bind_count; - descriptor.max_fragment_buffer_bind_count = max_fragment_buffer_bind_count; - descriptor.max_object_buffer_bind_count = max_object_buffer_bind_count; - descriptor.max_mesh_buffer_bind_count = max_mesh_buffer_bind_count; - descriptor.support_dynamic_attribute_stride = support_dynamic_attribute_stride; - } - } - descriptor.inherit_pipeline_state = resource.inherit_pipeline_state; - descriptor.inherit_buffers = resource.inherit_buffers; - descriptor -} - -/// The stages a render encoder makes the case's resources resident in for `resource`'s commands, as -/// the oracle does: the vertex and fragment stages, and the object and mesh stages too where its -/// descriptor allows mesh draws. -fn render_stages(resource: &CommandBufferResource) -> RenderStages { - let mesh = match resource.descriptor { - CommandDescriptor::Render { draws, .. } => draws.mesh(), - CommandDescriptor::Compute { .. } => false, - }; - let stages = RenderStages::VERTEX | RenderStages::FRAGMENT; - if mesh { - stages | RenderStages::OBJECT | RenderStages::MESH - } else { - stages - } -} - -/// The size of a grid or threadgroup. -fn size([x, y, z]: [u32; 3]) -> Size { - Size::new(x.into(), y.into(), z.into()) -} - -/// The case's buffer `index` among `buffers`, which `what` binds. -fn case_buffer<'a>( - buffers: &'a BTreeMap, - index: u32, - what: &str, -) -> Result<&'a Buffer, CaseError> { - buffers - .get(&index) - .ok_or_else(|| format!("{what} buffer {index} is not bound").into()) -} - -/// The compute template state of `token` among `templates`. -fn compute_template( - templates: &BTreeMap, - token: u64, -) -> Result<&ComputePipelineState, CaseError> { - match templates.get(&token) { - Some(TemplateState::Compute(state)) => Ok(state), - _ => Err(format!("pipeline token {token} has no compute template").into()), - } -} - -/// The render template state of `token` among `templates`. -fn render_template( - templates: &BTreeMap, - token: u64, -) -> Result<&RenderPipelineState, CaseError> { - match templates.get(&token) { - Some(TemplateState::Render(state)) => Ok(state), - _ => Err(format!("pipeline token {token} has no render template").into()), - } -} - -/// Encode each host command of `command_buffers` (made as `commands`) through its setters, before -/// the producer runs, as the oracle encodes them (`encode_host_commands`): its pipeline state (its -/// token's template among `templates`), each buffer the case's buffer at its offset (among -/// `buffers`), a compute command's threadgroup lengths, its dispatch or draw, and a compute -/// command's barrier (the oracle models no render command's). -pub fn encode_host_commands( - command_buffers: &BTreeMap<(u32, u32), CommandBufferResource>, - commands: &CaseCommands, - buffers: &BTreeMap, - templates: &BTreeMap, -) -> Result<(), CaseError> { - for (&key, resource) in command_buffers { - let icb = commands.buffer(key)?; - for host in &resource.commands { - let label = format!("command buffer {key:?} command {}", host.index); - if resource.is_render() { - encode_render_command(icb, host, &label, buffers, templates)?; - } else { - encode_compute_command(icb, host, &label, buffers, templates)?; - } - } - } - Ok(()) -} - -/// Encode host command `host` of compute command buffer `icb` ([`encode_host_commands`]). -fn encode_compute_command( - icb: &IndirectCommandBuffer, - host: &HostCommand, - label: &str, - buffers: &BTreeMap, - templates: &BTreeMap, -) -> Result<(), CaseError> { - let runtime = |call: &str| CaseError::runtime(format!("{label}: {call}")); - let command = icb - .indirect_compute_command_at(host.index.into()) - .map_err(runtime("indirect_compute_command_at"))?; - if let Some(token) = host.pipeline { - command - .set_compute_pipeline_state(compute_template(templates, token)?) - .map_err(runtime("set_compute_pipeline_state"))?; - } - for binding in &host.buffers { - let buffer = case_buffer(buffers, binding.buffer, "a host command's")?; - match binding.attribute_stride { - Some(stride) => command - .set_kernel_buffer_with_stride( - Some(buffer), - binding.offset.into(), - stride.into(), - binding.index, - ) - .map_err(runtime("set_kernel_buffer_with_stride"))?, - None => command - .set_kernel_buffer(Some(buffer), binding.offset.into(), binding.index) - .map_err(runtime("set_kernel_buffer"))?, - } - } - if let Some(region) = host.stage_in_region { - let [x, y, z] = region.origin.map(u64::from); - let [width, height, depth] = region.size.map(u64::from); - command - .set_stage_in_region(Region::new_3d(x, y, z, width, height, depth)) - .map_err(runtime("set_stage_in_region"))?; - } - for memory in &host.threadgroup_memory_lengths { - command - .set_threadgroup_memory_length(memory.length, memory.index) - .map_err(runtime("set_threadgroup_memory_length"))?; - } - match host.action { - Some(HostAction::DispatchThreadgroups { - grid, - threads_per_threadgroup, - }) => command - .concurrent_dispatch_threadgroups(size(grid), size(threads_per_threadgroup)) - .map_err(runtime("concurrent_dispatch_threadgroups"))?, - Some(HostAction::DispatchThreads { - grid, - threads_per_threadgroup, - }) => command - .concurrent_dispatch_threads(size(grid), size(threads_per_threadgroup)) - .map_err(runtime("concurrent_dispatch_threads"))?, - Some( - HostAction::DrawPrimitives { .. } - | HostAction::DrawIndexedPrimitives { .. } - | HostAction::DrawPatches { .. }, - ) => return Err(format!("{label}: a compute command draws nothing").into()), - None => {} - } - if host.barrier { - command.set_barrier().map_err(runtime("set_barrier"))?; - } - Ok(()) -} - -/// Encode host command `host` of render command buffer `icb` ([`encode_host_commands`]): its -/// render pipeline state, vertex and fragment buffers, and draw (of primitives, indexed from a -/// case buffer at its offset, or of patches from case buffers at their offsets), as the oracle's -/// `indirectRenderCommandAtIndex:` setters do. -fn encode_render_command( - icb: &IndirectCommandBuffer, - host: &HostCommand, - label: &str, - buffers: &BTreeMap, - templates: &BTreeMap, -) -> Result<(), CaseError> { - let runtime = |call: &str| CaseError::runtime(format!("{label}: {call}")); - let command = icb - .indirect_render_command_at(host.index.into()) - .map_err(runtime("indirect_render_command_at"))?; - if let Some(token) = host.pipeline { - command - .set_render_pipeline_state(render_template(templates, token)?) - .map_err(runtime("set_render_pipeline_state"))?; - } - for binding in &host.vertex_buffers { - let buffer = case_buffer(buffers, binding.buffer, "a host command's")?; - match binding.attribute_stride { - Some(stride) => command - .set_vertex_buffer_with_stride( - Some(buffer), - binding.offset.into(), - stride.into(), - binding.index, - ) - .map_err(runtime("set_vertex_buffer_with_stride"))?, - None => command - .set_vertex_buffer(Some(buffer), binding.offset.into(), binding.index) - .map_err(runtime("set_vertex_buffer"))?, - } - } - for binding in &host.fragment_buffers { - command - .set_fragment_buffer( - Some(case_buffer(buffers, binding.buffer, "a host command's")?), - binding.offset.into(), - binding.index, - ) - .map_err(runtime("set_fragment_buffer"))?; - } - match host.action { - Some(HostAction::DrawPrimitives { - primitive, - vertex_start, - vertex_count, - instance_count, - base_instance, - }) => command - .draw_primitives( - metal_primitive_type(primitive), - vertex_start.into(), - vertex_count.into(), - instance_count.into(), - base_instance.into(), - ) - .map_err(runtime("draw_primitives"))?, - Some(HostAction::DrawIndexedPrimitives { - primitive, - index_count, - index_type, - index_buffer, - index_buffer_offset, - instance_count, - base_vertex, - base_instance, - }) => command - .draw_indexed_primitives( - metal_primitive_type(primitive), - index_count.into(), - metal_index_type(index_type), - case_buffer(buffers, index_buffer, "an indexed draw's index")?, - index_buffer_offset.into(), - instance_count.into(), - base_vertex.into(), - base_instance.into(), - ) - .map_err(runtime("draw_indexed_primitives"))?, - Some(HostAction::DrawPatches { - control_points, - patch_start, - patch_count, - patch_index_buffer, - patch_index_buffer_offset, - instance_count, - base_instance, - factor_buffer, - factor_buffer_offset, - factor_instance_stride, - }) => command - .draw_patches( - control_points.into(), - patch_start.into(), - patch_count.into(), - patch_index_buffer - .map(|index| case_buffer(buffers, index, "a patch draw's patch index")) - .transpose()?, - patch_index_buffer_offset.into(), - instance_count.into(), - base_instance.into(), - case_buffer(buffers, factor_buffer, "a patch draw's factor")?, - factor_buffer_offset.into(), - factor_instance_stride.into(), - ) - .map_err(runtime("draw_patches"))?, - Some(_) => return Err(format!("{label}: a render command dispatches nothing").into()), - None => {} - } - if host.barrier { - return Err( - format!("{label}: a host-encoded render command's barrier is not modeled").into(), - ); - } - Ok(()) -} - -/// Encode on `command_buffer`, after the producer's dispatch or draw, the copy of each `Private` -/// command buffer of `commands` into its `Shared` twin, so its commands read back once the -/// producer completed ([`CaseCommands::check_commands`]). -pub fn encode_twin_copies( - command_buffer: &CommandBuffer, - commands: &CaseCommands, -) -> Result<(), CaseError> { - if commands.twins.is_empty() { - return Ok(()); - } - let mut blit = command_buffer - .blit_command_encoder() - .map_err(CaseError::runtime("blit_command_encoder"))?; - for (&key, twin) in &commands.twins { - let icb = commands.buffer(key)?; - blit.copy_indirect_command_buffer(icb, 0..icb.size(), twin, 0) - .map_err(CaseError::runtime(format!( - "command buffer {key:?}: copy_indirect_command_buffer" - )))?; - } - blit.end_encoding() - .map_err(CaseError::runtime("end_encoding")) -} - -/// The case's command buffer at `key` that it executes (`resource`, whose `execute` is set, one of -/// `commands`), encoded on a command buffer of `queue`, the producer's, and not committed, as the -/// oracle runs it (`execute_host_commands`): a compute encoder for compute commands, and for render -/// commands a render encoder of the oracle's pass, whose one attachment is a 1x1 `R8Unorm` sink -/// neither loaded nor stored (`make_rasterization_sink`: the render templates draw nothing into -/// it); the parent's pipeline state (its token's template among `templates`) and buffers (among -/// `buffers`, the case's by Metal index), `resident` (every buffer of the case and every -/// argument-buffer buffer) resident for reading and writing, in the vertex and fragment stages of -/// a render encoder, and `execute_commands_in_buffer` over the execution range. Committed after -/// the producer's command buffer, it runs once the producer completed, as the oracle's waits order -/// it: the queue runs its command buffers in commit order, and commands the producer writes run -/// once the work before them completed. -pub fn encoded_execution( - queue: &CommandQueue, - (buffers, resident): (&BTreeMap, &[ResourceRef<'_>]), - commands: &CaseCommands, - (key, resource): ((u32, u32), &CommandBufferResource), - templates: &BTreeMap, -) -> Result { - let execution = resource - .execute - .as_ref() - .ok_or_else(|| format!("command buffer {key:?} is not executed"))?; - let icb = commands.buffer(key)?; - let label = format!("command buffer {key:?}'s execution"); - let runtime = |call: &str| CaseError::runtime(format!("{label}: {call}")); - let parent = |binding: &crate::case::indirect_commands::CommandBinding| { - case_buffer(buffers, binding.buffer, "the parent's") - }; - let command_buffer = queue.command_buffer().map_err(runtime("command_buffer"))?; - let [start, end] = resource.execution_range; - let range = u64::from(start)..u64::from(end); - let usage = ResourceUsage::READ | ResourceUsage::WRITE; - if resource.is_render() { - let mut sink = TextureDescriptor::texture_2d(PixelFormat::R8Unorm, 1, 1, false); - sink.usage = TextureUsage::RENDER_TARGET; - sink.resource_options = ResourceOptions::shared(); - let sink = queue - .device() - .new_texture(&sink) - .map_err(runtime("new_texture"))?; - let mut pass = RenderPassDescriptor::new(); - let attachment = &mut pass.color_attachments[0]; - attachment.texture = Some(sink); - attachment.load_action = LoadAction::DontCare; - attachment.store_action = StoreAction::DontCare; - let mut encoder = command_buffer - .render_command_encoder(&pass) - .map_err(runtime("render_command_encoder"))?; - if let Some(parent) = &execution.pipeline { - encoder - .set_render_pipeline_state(render_template(templates, parent.token)?) - .map_err(runtime("set_render_pipeline_state"))?; - } - for binding in &execution.vertex_buffers { - encoder - .set_vertex_buffer(Some(parent(binding)?), binding.offset.into(), binding.index) - .map_err(runtime("set_vertex_buffer"))?; - } - for binding in &execution.fragment_buffers { - encoder - .set_fragment_buffer(Some(parent(binding)?), binding.offset.into(), binding.index) - .map_err(runtime("set_fragment_buffer"))?; - } - for binding in &execution.object_buffers { - encoder - .set_object_buffer(Some(parent(binding)?), binding.offset.into(), binding.index) - .map_err(runtime("set_object_buffer"))?; - } - for binding in &execution.mesh_buffers { - encoder - .set_mesh_buffer(Some(parent(binding)?), binding.offset.into(), binding.index) - .map_err(runtime("set_mesh_buffer"))?; - } - encoder - .use_resources(resident, usage, render_stages(resource)) - .map_err(runtime("use_resources"))?; - encoder - .execute_commands_in_buffer(icb, range) - .map_err(runtime("execute_commands_in_buffer"))?; - encoder.end_encoding().map_err(runtime("end_encoding"))?; - } else { - let mut encoder = command_buffer - .compute_command_encoder() - .map_err(runtime("compute_command_encoder"))?; - if let Some(parent) = &execution.pipeline { - encoder - .set_compute_pipeline_state(compute_template(templates, parent.token)?) - .map_err(runtime("set_compute_pipeline_state"))?; - } - for binding in &execution.buffers { - encoder - .set_buffer(Some(parent(binding)?), binding.offset.into(), binding.index) - .map_err(runtime("set_buffer"))?; - } - encoder - .use_resources(resident, usage) - .map_err(runtime("use_resources"))?; - encoder - .execute_commands_in_buffer(icb, range) - .map_err(runtime("execute_commands_in_buffer"))?; - encoder.end_encoding().map_err(runtime("end_encoding"))?; - } - Ok(command_buffer) -} diff --git a/crates/metal2vulkan-validation/src/candidate/runtime_case/host_wait_gap.rs b/crates/metal2vulkan-validation/src/candidate/runtime_case/host_wait_gap.rs deleted file mode 100644 index fb1a19684..000000000 --- a/crates/metal2vulkan-validation/src/candidate/runtime_case/host_wait_gap.rs +++ /dev/null @@ -1,280 +0,0 @@ -//! The one validation-layer message a [`Messages`](super::Messages) sink lets pass: the layer's -//! synchronization validation forgets a semaphore chain once the host waited on a timeline. -//! -//! The layer credits a host wait for a timeline semaphore (`vkGetSemaphoreCounterValue`, or a -//! wait-all `vkWaitSemaphores`) only to the accesses of the queue that signalled it: -//! `SyncValidator::WaitForSemaphore` calls `ApplyTaggedWait` with no queue sync tags, under -//! "TODO: specify queue sync tags argument similar to WaitForFence" (Vulkan-ValidationLayers -//! v1.4.357, commit e4786f7c, `layers/sync/sync_validation.cpp` line 280; v1.4.363, commit -//! 2ea16de8, line 282, `WaitForSemaphore` and `ApplyTaggedWait` unchanged; still there in main -//! 4f8ac9ce of 2026-10-05, line 282). That wait also drops the waited queue's writes from the -//! batches a semaphore chain ran through. So when a batch on `VkQueue` A was ordered before a -//! batch on B by a semaphore, the host read B's timeline past it, and A's next batch waits for -//! B's, the layer finds A's earlier write ordered only by the barrier that ends A's batch for -//! the host, and reports a `WRITE_AFTER_WRITE` between A's two batches. It prints that barrier -//! as "allows 0", since the host's accesses are no queue's. Vulkan orders them through the -//! chain, and the host's read orders them again. -//! -//! A standalone program shows it with no runtime code: two queues, three fills of one buffer, -//! each command buffer ending with the barrier to the host the runtime's batches end with, the -//! host waiting for the middle one (the RTX 5080 and the RTX 3090). Its control, the same chain -//! without the host wait, gets no message. -//! -//! The runtime's queue waiters read the timelines while its scheduler submits, so on a -//! device with several `VkQueue`s a lane test hits it at random: on the RTX 5080, -//! `runtime_lane::exits::an_exit_while_submitting_is_clean` failed 4 to 12 runs in 30. A single -//! `VkQueue` cannot hit it. -//! -//! [`shape`] matches that message and nothing wider. [`read`] keys the layer releases whose -//! source was read with the TODO in place. On any other release, the message fails as before, -//! marked "re-read WaitForSemaphore in layer X.Y.Z", so a fixed or changed layer is checked -//! again rather than trusted. - -use ash::vk; - -/// `messageIdNumber` of `SYNC-HAZARD-WRITE-AFTER-WRITE`, as the layer hashes its name. -const ID: i32 = 1544472022; - -/// The id name of the hazard. -const ID_NAME: &str = "SYNC-HAZARD-WRITE-AFTER-WRITE"; - -/// The call the layer reports the hazard at: a `vkQueueSubmit`, against a command buffer -/// submitted earlier. -const SUBMIT: &str = "vkQueueSubmit(): "; - -/// The hazard, after the call, or after the command buffer's place in the submission where the -/// layer names it (v1.4.363: `pSubmits[0].pCommandBuffers[1]`, `sync_submit.cpp` line 737, -/// `submit_loc.dot(vvl::Field::pSubmits, batch_index)` then `.dot(vvl::Field::pCommandBuffers, -/// index)`; v1.4.357 names none). -const HAZARD: &str = "WRITE_AFTER_WRITE hazard detected. "; - -/// What names the queue of the command buffer being submitted. -const CURRENT_QUEUE: &str = " submitted on the current "; - -/// What starts the earlier write. -const PRIOR: &str = "which was previously written by another "; - -/// What names the queue of the earlier write's command buffer. -const PRIOR_QUEUE: &str = " submitted on "; - -/// The earlier write's barriers: none a queue's access is in (`sync_reporting.cpp`, -/// `FormatErrorMessage` and `FormatSyncAccesses`): the barrier for the host that ends a batch -/// orders nothing later on a queue. A write with no barrier at all reads "No sufficient -/// synchronization is present" instead, which no batch of the runtime's leaves. -const NO_BARRIER: &str = "\nThe current synchronization allows 0, but to prevent this hazard"; - -/// The layer releases (`VkLayerProperties::specVersion` of `VK_LAYER_KHRONOS_validation`) whose -/// `WaitForSemaphore` was read with the TODO in place: v1.4.357 (tag commit e4786f7c) and -/// v1.4.363 (tag commit 2ea16de8), whose `WaitForSemaphore`, `ApplyTaggedWait` and the text the -/// hazard's message is made of (`sync_error_messages.cpp`, `sync_reporting.cpp`, -/// `FormatErrorMessage`) are those of v1.4.357. -pub(super) const READ: &[u32] = &[ - vk::make_api_version(0, 1, 4, 357), - vk::make_api_version(0, 1, 4, 363), -]; - -/// Where the TODO is, for the line each message let pass prints. -pub(super) const SOURCE: &str = "Vulkan-ValidationLayers v1.4.357 (e4786f7c) \ - layers/sync/sync_validation.cpp:280 and v1.4.363 (2ea16de8) :282, \ - SyncValidator::WaitForSemaphore: \"TODO: specify queue \ - sync tags argument similar to WaitForFence\""; - -/// Whether a message with this id, id name and text is the gap's: a `WRITE_AFTER_WRITE` found at -/// a `vkQueueSubmit` against a write of a command buffer submitted earlier on the same -/// `VkQueue`, which no barrier for a queue's later access ordered. -pub(super) fn shape(id: i32, id_name: &str, text: &str) -> bool { - if id != ID || id_name != ID_NAME { - return false; - } - let Some(rest) = text.strip_prefix(SUBMIT) else { - return false; - }; - let Some(rest) = after_place(rest).strip_prefix(HAZARD) else { - return false; - }; - let Some(prior_at) = rest.find(PRIOR) else { - return false; - }; - let (current, prior) = rest.split_at(prior_at); - let queue_after = |text: &str, marker: &str| -> Option { - let start = text.find(marker)? + marker.len(); - let end = start + text[start..].find(')')?; - let queue = &text[start..end]; - queue.starts_with("VkQueue ").then(|| queue.to_owned()) - }; - let (Some(current_queue), Some(prior_queue)) = ( - queue_after(current, CURRENT_QUEUE), - queue_after(prior, PRIOR_QUEUE), - ) else { - return false; - }; - current_queue == prior_queue && prior.contains(NO_BARRIER) -} - -/// What follows a command buffer's place in a submission, `pSubmits[N].pCommandBuffers[M] `, that -/// `text` begins with; `text` itself where it begins with none. -fn after_place(text: &str) -> &str { - let index = |text: &'static str, rest: &str| -> Option { - let digits = rest.strip_prefix(text)?; - let end = digits.find(|c: char| !c.is_ascii_digit())?; - (end > 0 && digits[end..].starts_with(']')).then_some(text.len() + end + 1) - }; - let Some(submit) = index("pSubmits[", text) else { - return text; - }; - let Some(buffer) = index(".pCommandBuffers[", &text[submit..]) else { - return text; - }; - text[submit + buffer..].strip_prefix(' ').unwrap_or(text) -} - -/// Whether the layer release `version` is one whose source was read with the gap in place. -pub(super) fn read(version: u32) -> bool { - READ.contains(&version) -} - -/// `version` as `X.Y.Z`. -pub(super) fn release(version: u32) -> String { - format!( - "{}.{}.{}", - vk::api_version_major(version), - vk::api_version_minor(version), - vk::api_version_patch(version) - ) -} - -/// The `specVersion` of the validation layer the loader `loader` (the system's default when -/// `None`) offers; `None` when it cannot be read. -pub(super) fn layer_version(loader: Option<&std::path::Path>) -> Option { - // SAFETY: opening the loader library runs only its initializers. - let entry = unsafe { - match loader { - Some(path) => ash::Entry::load_from(path), - None => ash::Entry::load(), - } - } - .ok()?; - // SAFETY: a global command of a loaded entry, called with no instance. - let layers = unsafe { entry.enumerate_instance_layer_properties() }.ok()?; - layers - .iter() - .find(|layer| { - layer - .layer_name_as_c_str() - .is_ok_and(|name| name == super::VALIDATION_LAYER) - }) - .map(|layer| layer.spec_version) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// The message the RTX 5080 reported (`runtime_lane::exits`, run 18). - const SEEN: &str = "vkQueueSubmit(): WRITE_AFTER_WRITE hazard detected. vkCmdFillBuffer (from \ - VkCommandBuffer 0x7faa33f276b0 submitted on the current VkQueue 0x7faa30e9aab0) writes to \ - VkBuffer 0x1c000000001c, which was previously written by another vkCmdFillBuffer command \ - (from VkCommandBuffer 0x7faa33ebf730 submitted on VkQueue 0x7faa30e9aab0). \nThe current \ - synchronization allows 0, but to prevent this hazard, it must allow \ - VK_ACCESS_2_TRANSFER_WRITE_BIT accesses at VK_PIPELINE_STAGE_2_CLEAR_BIT."; - - #[test] - fn the_layer_s_message_is_the_gap() { - assert!(shape(ID, ID_NAME, SEEN)); - // As v1.4.363 reports it: the command buffer's place in the submission after the call, - // and the parameter before the resource. - let placed = SEEN - .replacen( - "vkQueueSubmit(): ", - "vkQueueSubmit(): pSubmits[0].pCommandBuffers[1] ", - 1, - ) - .replacen("writes to VkBuffer", "writes to dstBuffer VkBuffer", 1); - assert!(shape(ID, ID_NAME, &placed)); - // Another place, or a place the layer does not print so. - let other = placed.replace( - "pSubmits[0].pCommandBuffers[1]", - "pSubmits[12].pCommandBuffers[3]", - ); - assert!(shape(ID, ID_NAME, &other)); - for broken in [ - "pSubmits[].pCommandBuffers[1]", - "pSubmits[0].pCommandBufferInfos[1]", - "pSubmits[0]", - ] { - let broken = placed.replace("pSubmits[0].pCommandBuffers[1]", broken); - assert!(!shape(ID, ID_NAME, &broken), "{broken}"); - } - } - - #[test] - fn another_hazard_is_not_the_gap() { - let read_after_write = SEEN - .replace("WRITE_AFTER_WRITE", "READ_AFTER_WRITE") - .replace("writes to", "reads"); - assert!(!shape( - -1, - "SYNC-HAZARD-READ-AFTER-WRITE", - &read_after_write - )); - assert!(!shape(ID, "SYNC-HAZARD-READ-AFTER-WRITE", SEEN)); - assert!(!shape(-1, ID_NAME, SEEN)); - let write_after_read = "vkQueueSubmit(): WRITE_AFTER_READ hazard detected. \ - vkCmdFillBuffer (from VkCommandBuffer 0x2 submitted on the current VkQueue 0x1) \ - writes to VkBuffer 0x3, which was previously read by vkCmdCopyBuffer command (from \ - VkCommandBuffer 0x4 submitted on VkQueue 0x1). \nThe current synchronization defines \ - the destination stage mask as 0, but to prevent this hazard, it must include \ - VK_PIPELINE_STAGE_2_CLEAR_BIT."; - assert!(!shape(ID, ID_NAME, write_after_read)); - } - - #[test] - fn a_hazard_inside_one_command_buffer_is_not_the_gap() { - let recorded = "vkCmdFillBuffer(): WRITE_AFTER_WRITE hazard detected. vkCmdFillBuffer \ - writes to VkBuffer 0x1c000000001c, which was previously written by another \ - vkCmdFillBuffer command. \nThe current synchronization allows 0, but to prevent this \ - hazard, it must allow VK_ACCESS_2_TRANSFER_WRITE_BIT accesses at \ - VK_PIPELINE_STAGE_2_CLEAR_BIT."; - assert!(!shape(ID, ID_NAME, recorded)); - } - - #[test] - fn an_earlier_write_on_another_queue_is_not_the_gap() { - let other = SEEN.replace( - "submitted on VkQueue 0x7faa30e9aab0", - "submitted on VkQueue 0x7faa30e9a000", - ); - assert!(!shape(ID, ID_NAME, &other)); - } - - #[test] - fn an_earlier_write_with_no_barrier_at_all_is_not_the_gap() { - let start = SEEN.find("\nThe current").unwrap(); - let none = format!( - "{}\nNo sufficient synchronization is present to ensure that a write \ - (VK_ACCESS_2_TRANSFER_WRITE_BIT) at VK_PIPELINE_STAGE_2_CLEAR_BIT does not conflict \ - with a prior write of the same type at the same stage.", - &SEEN[..start] - ); - assert!(!shape(ID, ID_NAME, &none)); - } - - #[test] - fn an_earlier_write_with_a_barrier_is_not_the_gap() { - let some = SEEN.replace( - "allows 0,", - "allows VK_ACCESS_2_TRANSFER_WRITE_BIT accesses at VK_PIPELINE_STAGE_2_COPY_BIT,", - ); - assert!(!shape(ID, ID_NAME, &some)); - } - - #[test] - fn only_the_releases_read_let_it_pass() { - assert!(read(vk::make_api_version(0, 1, 4, 357))); - assert!(read(vk::make_api_version(0, 1, 4, 363))); - assert!(!read(vk::make_api_version(0, 1, 4, 358))); - assert!(!read(vk::make_api_version(0, 1, 4, 364))); - assert!(!read(vk::make_api_version(0, 1, 4, 341))); - assert_eq!(release(vk::make_api_version(0, 1, 4, 358)), "1.4.358"); - } -} diff --git a/crates/metal2vulkan-validation/src/candidate/runtime_case/imageblock.rs b/crates/metal2vulkan-validation/src/candidate/runtime_case/imageblock.rs deleted file mode 100644 index 0b8582591..000000000 --- a/crates/metal2vulkan-validation/src/candidate/runtime_case/imageblock.rs +++ /dev/null @@ -1,416 +0,0 @@ -//! A fragment case's explicit imageblock through the runtime: the Metal oracle's initializer and -//! resolver, generated as AIR. -//! -//! The Metal oracle defines every cell of a fragment case's imageblock before the case's draw, -//! and reads the selected member after it, with two helper fragment functions it compiles from -//! MSL at run time (`metal::platform::imageblocks`), drawn in the case's pass with the case's -//! vertex function, the pass's attachment formats and no color writes: its initializer writes each -//! member of the master layout from its authored plane, and its resolver writes the selected -//! member's plane into a buffer. The runtime compiles no MSL, so the runtime path draws the same -//! two helpers generated as AIR ([`helpers_text`]) from the checked reflection's master, over the -//! cells the executor's own context fills its storage with ([`Cells`]): -//! -//! - **The layout.** One struct of the master's members in declaration order, each of its -//! reflected type (`half`, `half4`, `uchar4`, `ushort`, `float` or `uint`), whose natural offsets must -//! be the reflected ones; its `air.struct_type_info` repeats the master's (each member's offset, -//! size, type name, user key and raster order group), and its data size is the master's, so the -//! product fingerprints it as the case's master (`FragmentImageblock::master`) and the runtime -//! draws the helpers and the case in one pass. Its stated alignment is its largest member's. -//! - **The initializer** reads pixel `(x, y)`'s cell from a buffer of the cells, at -//! `(y * width + x) * cell_bytes` with each member at its offset, and returns it as its -//! imageblock output, after the early fragment tests (so that link takes it beside a depth or -//! stencil attachment; nothing is tested then, the encoder's state being Metal's default). -//! - **The resolver** reads the cell as its imageblock input and writes each member into a buffer -//! of cells laid out alike, whose selected member's plane is the output ([`Cells::select`]). -//! The oracle's resolver writes only that plane: the bytes the output selects are the same. -//! -//! Both read the pixel from `[[position]]` (`air.convert` of its coordinates, as Metal's compiler -//! spells `uint(position.x)`). - -use super::{buffer_with, read_buffer, CaseError}; -use crate::air::reflect::FragmentImageblock; -use crate::air_library::AirLibrary; -use crate::candidate::engine::imageblock::Cells; -use crate::case::FragmentImageblockFormat; -use metal2vulkan::metal::{ColorWriteMask, PrimitiveType}; -use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; -use metal2vulkan_runtime::{ - Buffer, Device, PipelineOptions, RenderCommandEncoder, RenderPassDescriptor, - RenderPipelineState, -}; -use std::fmt::Write as _; - -/// The initializer's entry point. -pub const INITIALIZE_ENTRY: &str = "metal2vulkan_imageblock_initialize"; -/// The resolver's entry point. -pub const RESOLVE_ENTRY: &str = "metal2vulkan_imageblock_resolve"; - -const DATA_LAYOUT: &str = "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"; -const TRIPLE: &str = "air64_v28-apple-macosx26.0.0"; -/// The module's source name, so that two assemblies of the same helpers are the same bitcode. -const SOURCE_FILENAME: &str = "metal2vulkan-imageblock-helpers"; -/// The struct of the master's members. -const STRUCT: &str = "%struct.Metal2VulkanImageblock"; - -/// One member of the generated struct: its LLVM type, its natural alignment, and the alignment -/// of its element, which each access to the cells' buffer states (a cell starts at a multiple of -/// 4 bytes only). -struct Field { - ty: &'static str, - align: u32, - element: u32, -} - -/// The field of a member of `format`. -fn field(format: FragmentImageblockFormat) -> Field { - let (ty, align, element) = match format { - FragmentImageblockFormat::Half => ("half", 2, 2), - FragmentImageblockFormat::Half4 => ("<4 x half>", 8, 2), - FragmentImageblockFormat::Uchar4 => ("<4 x i8>", 4, 1), - FragmentImageblockFormat::Ushort => ("i16", 2, 2), - FragmentImageblockFormat::Float => ("float", 4, 4), - FragmentImageblockFormat::Uint => ("i32", 4, 4), - }; - Field { ty, align, element } -} - -/// The AIR text (opaque pointers, for `llvm-as`) of the initializer and resolver of `master`, the -/// checked reflection's master layout, over `cells` (their width and cell size), as the module -/// docs state them. Refused: a member of a type the oracle's helpers do not take, and a master -/// whose members do not lie at their natural offsets in declaration order. -pub fn helpers_text(master: &FragmentImageblock, cells: &Cells) -> Result { - let mut fields = Vec::with_capacity(master.members.len()); - let mut end = 0u32; - let mut alignment = 1u32; - for member in &master.members { - let format = FragmentImageblockFormat::from_air_type(&member.type_name, member.size) - .ok_or_else(|| { - format!( - "imageblock member {} of type {} and size {}, which the helpers do not take", - member.semantic, member.type_name, member.size - ) - })?; - let field = field(format); - let at = end.next_multiple_of(field.align); - if at != member.offset { - return Err(format!( - "imageblock member {} at {}, where a natural struct places it at {at}", - member.semantic, member.offset - )); - } - end = at + member.size; - alignment = alignment.max(field.align); - fields.push((member, field)); - } - if fields.is_empty() || end > cells.cell_bytes { - return Err(format!( - "an imageblock master of {} members ending at {end} over {}-byte cells", - fields.len(), - cells.cell_bytes - )); - } - let width = cells.dimensions[0]; - let cell_bytes = cells.cell_bytes; - let types: Vec<&str> = fields.iter().map(|(_, field)| field.ty).collect(); - let mut text = format!( - "; metal2vulkan generated imageblock helpers.\n\ - source_filename = \"{SOURCE_FILENAME}\"\n\ - target datalayout = \"{DATA_LAYOUT}\"\n\ - target triple = \"{TRIPLE}\"\n\n\ - {STRUCT} = type {{ {} }}\n\n", - types.join(", ") - ); - // The address of pixel `position`'s cell in the buffer `cells`. - let address = |text: &mut String| { - for line in [ - "%x = extractelement <4 x float> %position, i64 0".to_owned(), - "%y = extractelement <4 x float> %position, i64 1".to_owned(), - "%xi = tail call i32 @air.convert.u.i32.f.f32(float %x)".to_owned(), - "%yi = tail call i32 @air.convert.u.i32.f.f32(float %y)".to_owned(), - format!("%row = mul i32 %yi, {width}"), - "%pixel = add i32 %row, %xi".to_owned(), - format!("%start = mul i32 %pixel, {cell_bytes}"), - "%start64 = zext i32 %start to i64".to_owned(), - "%cell = getelementptr inbounds i8, ptr addrspace(1) %cells, i64 %start64".to_owned(), - ] { - let _ = writeln!(text, " {line}"); - } - for (index, (member, _)) in fields.iter().enumerate() { - let _ = writeln!( - text, - " %p{index} = getelementptr inbounds i8, ptr addrspace(1) %cell, i64 {}", - member.offset - ); - } - }; - let _ = writeln!( - text, - "define <{{ {STRUCT} }}> @{INITIALIZE_ENTRY}(<4 x float> noundef %position, \ - ptr addrspace(1) noundef readonly %cells) {{" - ); - address(&mut text); - let mut value = "poison".to_owned(); - for (index, (_, field)) in fields.iter().enumerate() { - let _ = writeln!( - text, - " %v{index} = load {ty}, ptr addrspace(1) %p{index}, align {align}", - ty = field.ty, - align = field.element - ); - let _ = writeln!( - text, - " %s{index} = insertvalue {STRUCT} {value}, {ty} %v{index}, {index}", - ty = field.ty - ); - value = format!("%s{index}"); - } - let _ = writeln!( - text, - " %out = insertvalue <{{ {STRUCT} }}> undef, {STRUCT} {value}, 0\n \ - ret <{{ {STRUCT} }}> %out\n}}\n" - ); - let _ = writeln!( - text, - "define void @{RESOLVE_ENTRY}({STRUCT} %data, <4 x float> noundef %position, \ - ptr addrspace(1) noundef %cells) {{" - ); - address(&mut text); - for (index, (_, field)) in fields.iter().enumerate() { - let _ = writeln!( - text, - " %e{index} = extractvalue {STRUCT} %data, {index}\n \ - store {ty} %e{index}, ptr addrspace(1) %p{index}, align {align}", - ty = field.ty, - align = field.element - ); - } - text.push_str(" ret void\n}\n\ndeclare i32 @air.convert.u.i32.f.f32(float)\n\n"); - // The metadata: the master's layout, each entry's outputs and inputs, and the module's. - let layout = fields - .iter() - .map(|(member, _)| { - format!( - "i32 {}, i32 {}, i32 0, !\"{}\", !\"{}\", !\"air.raster_order_group\", i32 {}", - member.offset, - member.size, - member.type_name, - member.semantic, - member.raster_order_group - ) - }) - .collect::>() - .join(", "); - let imageblock = format!( - "!\"air.imageblock_data\", !\"air.imageblock_data_size\", i32 {}, \ - !\"air.struct_type_info\", !0, !\"air.arg_type_align_size\", i32 {alignment}, \ - !\"air.arg_type_name\", !\"Metal2VulkanImageblock\", !\"air.arg_name\", !\"data\"", - master.sample_size - ); - let position = |index: u32| { - format!( - "!{{i32 {index}, !\"air.position\", !\"air.center\", !\"air.no_perspective\", \ - !\"air.arg_type_name\", !\"float4\", !\"air.arg_name\", !\"position\"}}" - ) - }; - let buffer = |index: u32, access: &str| { - format!( - "!{{i32 {index}, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, \ - !\"{access}\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 1, \ - !\"air.arg_type_align_size\", i32 1, !\"air.arg_type_name\", !\"uchar\", \ - !\"air.arg_name\", !\"cells\"}}" - ) - }; - let nodes = [ - format!("!{{{layout}}}"), - // The initializer: its output, its inputs, and its entry, after the early tests. - format!("!{{!{{{imageblock}}}}}"), - format!("!{{{}, {}}}", position(0), buffer(1, "air.read")), - format!("!{{ptr @{INITIALIZE_ENTRY}, !1, !2, !\"early_fragment_tests\"}}"), - // The resolver: no output, its inputs, and its entry. - "!{}".to_owned(), - format!( - "!{{!{{i32 0, {imageblock}}}, {}, {}}}", - position(1), - buffer(2, "air.read_write") - ), - format!("!{{ptr @{RESOLVE_ENTRY}, !4, !5}}"), - "!{i32 7, !\"air.max_device_buffers\", i32 31}".to_owned(), - "!{!\"air.compile.denorms_disable\"}".to_owned(), - "!{!\"air.compile.fast_math_enable\"}".to_owned(), - "!{!\"air.compile.framebuffer_fetch_enable\"}".to_owned(), - "!{i32 2, i32 8, i32 0}".to_owned(), - "!{!\"Metal\", i32 4, i32 0, i32 0}".to_owned(), - ]; - text.push_str( - "!llvm.module.flags = !{!7}\n\ - !air.fragment = !{!3, !6}\n\ - !air.compile_options = !{!8, !9, !10}\n\ - !air.version = !{!11}\n\ - !air.language_version = !{!12}\n\n", - ); - for (id, node) in nodes.iter().enumerate() { - let _ = writeln!(text, "!{id} = {node}"); - } - Ok(text) -} - -/// A fragment case's helpers on a device, as the Metal oracle draws them (the module docs): the -/// initializer's state and the buffer of the cells it reads, and, where the case's output is an -/// imageblock member, the resolver's state and the buffer it writes. -pub(super) struct Helpers { - initialize: RenderPipelineState, - cells: Buffer, - resolve: Option<(RenderPipelineState, Buffer)>, - /// The cells' extent and cell size, which the resolver's buffer holds. - dimensions: [u32; 2], - cell_bytes: u32, -} - -impl Helpers { - /// The helpers of `master` over `cells` on `device`, drawn with `case`'s vertex function and - /// attachment formats (the case's descriptor), no color written; the resolver where - /// `resolves`. - pub(super) fn new( - device: &Device, - case: &RenderPipelineDescriptor, - master: &FragmentImageblock, - cells: &Cells, - resolves: bool, - ) -> Result { - let text = helpers_text(master, cells)?; - let bitcode = crate::check::loop_free::assemble(&text)?; - let library = device - .new_library_with_air(&bitcode) - .map_err(CaseError::helper( - "the imageblock helpers' new_library_with_air", - ))?; - let state = |entry: &str| { - let function = library - .new_function_with_name(entry) - .map_err(CaseError::helper(format!( - "{entry}: new_function_with_name" - )))?; - let mut descriptor = RenderPipelineDescriptor::new(case.vertex.clone()); - descriptor.fragment = Some(StageSource::Function(function.function_descriptor())); - for (helper, own) in descriptor - .color_attachments - .iter_mut() - .zip(&case.color_attachments) - { - *helper = own.as_ref().map(|own| { - let mut attachment = ColorAttachmentDescriptor::new(own.pixel_format); - attachment.write_mask = ColorWriteMask::NONE; - attachment - }); - } - descriptor.depth_format = case.depth_format; - descriptor.stencil_format = case.stencil_format; - device - .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) - .map_err(CaseError::helper(format!( - "{entry}: new_render_pipeline_state" - ))) - }; - let initialize = state(INITIALIZE_ENTRY)?; - let resolve = if resolves { - let resolved = buffer_with(device, &vec![0; cells.bytes.len()])?; - Some((state(RESOLVE_ENTRY)?, resolved)) - } else { - None - }; - Ok(Helpers { - initialize, - cells: buffer_with(device, &cells.bytes)?, - resolve, - dimensions: cells.dimensions, - cell_bytes: cells.cell_bytes, - }) - } - - /// Hold `pass` to the case's `pipeline` as the oracle does: its imageblock sample length the - /// pipeline's, which each helper's must be ("generated and target fragment imageblock layouts - /// disagree" otherwise), and a 16x16 tile. - pub(super) fn prepare_pass( - &self, - pass: &mut RenderPassDescriptor, - pipeline: &RenderPipelineState, - ) -> Result<(), CaseError> { - let length = |state: &RenderPipelineState| { - state - .imageblock_sample_length() - .map_err(CaseError::runtime("imageblock_sample_length")) - }; - let sample_length = length(pipeline)?; - let helpers = - std::iter::once(&self.initialize).chain(self.resolve.as_ref().map(|(state, _)| state)); - for helper in helpers { - let helper = length(helper)?; - if helper != sample_length { - return Err(format!( - "generated and target fragment imageblock layouts disagree: the helper's \ - sample length is {helper}, the case's {sample_length}" - ) - .into()); - } - } - pass.imageblock_sample_length = sample_length; - pass.tile_width = 16; - pass.tile_height = 16; - Ok(()) - } - - /// Draw the initializer: the fullscreen triangle of the case's vertex function, reading the - /// cells at fragment buffer 0. - pub(super) fn initialize(&self, encoder: &mut RenderCommandEncoder) -> Result<(), CaseError> { - draw(encoder, &self.initialize, &self.cells) - } - - /// Draw the resolver, where the case has one, writing the cells at fragment buffer 0. - pub(super) fn resolve(&self, encoder: &mut RenderCommandEncoder) -> Result<(), CaseError> { - match &self.resolve { - Some((state, resolved)) => draw(encoder, state, resolved), - None => Ok(()), - } - } - - /// The draws the helpers add to the case's, before it and after it. - pub(super) fn draws(&self) -> (usize, usize) { - (1, usize::from(self.resolve.is_some())) - } - - /// The cells the resolver wrote, once the command buffer completed. - pub(super) fn resolved(&self) -> Result { - let (_, buffer) = self - .resolve - .as_ref() - .ok_or("an imageblock output without its resolver")?; - Ok(Cells { - dimensions: self.dimensions, - cell_bytes: self.cell_bytes, - bytes: read_buffer(buffer, 0, buffer.length())?, - }) - } -} - -/// Draw `state`'s fullscreen triangle with `buffer` at fragment buffer 0. -fn draw( - encoder: &mut RenderCommandEncoder, - state: &RenderPipelineState, - buffer: &Buffer, -) -> Result<(), CaseError> { - encoder - .set_render_pipeline_state(state) - .map_err(CaseError::helper( - "an imageblock helper's set_render_pipeline_state", - ))?; - encoder - .set_fragment_buffer(Some(buffer), 0, 0) - .map_err(CaseError::helper( - "an imageblock helper's set_fragment_buffer", - ))?; - encoder - .draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0) - .map_err(CaseError::helper("an imageblock helper's draw_primitives")) -} diff --git a/crates/metal2vulkan-validation/src/candidate/runtime_case/input_index_gap.rs b/crates/metal2vulkan-validation/src/candidate/runtime_case/input_index_gap.rs deleted file mode 100644 index 9434b214b..000000000 --- a/crates/metal2vulkan-validation/src/candidate/runtime_case/input_index_gap.rs +++ /dev/null @@ -1,295 +0,0 @@ -//! A validation-layer gap a [`Messages`](super::Messages) sink lets pass: the layer's link-time -//! check of a fragment shader's input attachments reads a pipeline made against a `VkRenderPass` -//! as if it were made for dynamic rendering, and reports every input attachment it reads. -//! -//! `VUID-VkGraphicsPipelineCreateInfo-renderPass-09652` holds "If the pipeline is being created -//! with fragment shader state and fragment output state, the value of renderPass is -//! `VK_NULL_HANDLE`, and `VkRenderingInputAttachmentIndexInfo` is not included": it is a rule of -//! dynamic rendering, where input attachment `i` is colour attachment `i`. In a subpass, input -//! attachment `i` is `pInputAttachments[i]`, and the render pass is part of both states, so a -//! pipeline linked from libraries made against one has it. -//! -//! In layer v1.4.357 (tag commit e4786f7c) the check runs only for dynamic rendering: -//! `CoreChecks::ValidateShaderInputAttachment` (`layers/core_checks/cc_spirv.cpp` line 87) tests -//! `rp_state->UsesDynamicRendering()` first. v1.4.363 (tag commit 2ea16de8) adds a second pass -//! at link time, in `CoreChecks::ValidateInterfaceFragmentOutput` -//! (`layers/core_checks/cc_shader_interface.cpp` line 221), for a pipeline that takes its -//! fragment shader or fragment output state from a library, and that pass tests no such thing: -//! it calls `ValidateShaderInputAttachmentDynamicRendering` with the libraries' render pass, -//! whose `dynamic_pipeline_rendering_create_info` a `VkRenderPass` never sets -//! (`layers/state_tracker/render_pass_state.cpp` lines 340 and 357), so it compares each index -//! with a colour attachment count of 0. The layer's main branch adds the missing test in -//! 65fdd118 of 2026-10-03, "layers: Fix 09652 false positive", after the v1.4.363 tag. -//! -//! The runtime makes every graphics pipeline against a `VkRenderPass`, and links one from -//! libraries where the device enables `VK_EXT_graphics_pipeline_library` and links them fast -//! (`runtime/src/pipeline/libraries.rs`), so on layer v1.4.363 every linked pipeline that fetches -//! through an input attachment reports each one it reads (lavapipe links them). [`shape`] -//! matches only the second pass's message, word for word but for its numbers: at the create -//! info's location (the per-stage check reports at `pStages[i]`), against a count of 0. [`read`] -//! keys the layer releases whose source was read with the gap in place. On any other release -//! such a message fails, marked "re-read the link-time input attachment check in layer X.Y.Z", -//! so a fixed or changed layer is checked again rather than trusted. - -use ash::vk; - -/// `messageIdNumber` of the valid usage, as the layer hashes its name. -const ID: i32 = 454563899; - -/// The id name of the valid usage. -const ID_NAME: &str = "VUID-VkGraphicsPipelineCreateInfo-renderPass-09652"; - -/// The start of the message: the create info's location, the second pass's (`create_info_loc`). -const CALL: &str = "vkCreateGraphicsPipelines(): pCreateInfos["; - -/// What follows the create info's index: the fragment shader's input attachment -/// (`DescribeInputAttachmentIndex`), its set and binding. -const SHADER: &str = "] shader [VK_SHADER_STAGE_FRAGMENT_BIT] [Set "; - -/// The end of the message's first line: compared with the colour attachment count a -/// `VkRenderPass`'s state holds, 0. -const COUNT: &str = - " which is not less than VkPipelineRenderingCreateInfo::colorAttachmentCount (0)"; - -/// The rest of the message, after its first line, as layer v1.4.363 words it. -const REST: &str = "If VkRenderingInputAttachmentIndexInfo is provided, the index can be set, \ - but without it, it uses the default index values.\nHint: If using Depth/Stencil attachments, \ - you should be omitting the input attachment index in the shader to access the depth/stencil \ - attachments.\nThe Vulkan spec states: If the pipeline is being created with fragment shader \ - state and fragment output state, the value of renderPass is VK_NULL_HANDLE, and \ - VkRenderingInputAttachmentIndexInfo is not included, the fragment shader must not contain any \ - input attachments with a InputAttachmentIndex greater than or equal to \ - VkPipelineRenderingCreateInfo::colorAttachmentCount \ - (https://docs.vulkan.org/spec/latest/chapters/pipelines.html\ - #VUID-VkGraphicsPipelineCreateInfo-renderPass-09652)"; - -/// The note the layer puts before a message it reports for the last time -/// (`duplicate_message_limit`), around the count. -const LAST_TIME: (&str, &str) = ( - "(Warning - This VUID has now been reported ", - " times, which is the duplicate_message_limit value, this will be the last time reporting \ - it).\n", -); - -/// The layer releases (`VkLayerProperties::specVersion` of `VK_LAYER_KHRONOS_validation`) whose -/// source was read with the gap in place: v1.4.363 (tag commit 2ea16de8). -pub(super) const READ: &[u32] = &[vk::make_api_version(0, 1, 4, 363)]; - -/// Where the gap is, for the line each message let pass prints. -pub(super) const SOURCE: &str = "Vulkan-ValidationLayers v1.4.363 (2ea16de8) \ - layers/core_checks/cc_shader_interface.cpp:221, CoreChecks::ValidateInterfaceFragmentOutput: \ - the link-time input attachment pass does not test rp_state->UsesDynamicRendering() \ - (added in main 65fdd118, \"layers: Fix 09652 false positive\")"; - -/// Whether a message with this id, id name and text is the gap's: the link-time pass's report of -/// a fragment shader's input attachment at the create info's location, against a colour -/// attachment count of 0, word for word as layer v1.4.363 reports it but for its numbers. -pub(super) fn shape(id: i32, id_name: &str, text: &str) -> bool { - if id != ID || id_name != ID_NAME { - return false; - } - // Before the message, nothing or the layer's last-time note. - let text = match text.strip_prefix(LAST_TIME.0) { - Some(note) => match number(note).and_then(|rest| rest.strip_prefix(LAST_TIME.1)) { - Some(rest) => rest, - None => return false, - }, - None => text, - }; - let Some((first, rest)) = text.split_once('\n') else { - return false; - }; - let Some(index) = first.strip_prefix(CALL).and_then(number) else { - return false; - }; - let Some(binding) = index.strip_prefix(SHADER).and_then(number) else { - return false; - }; - let Some(read) = binding - .strip_prefix(", Binding ") - .and_then(number) - .and_then(|rest| rest.strip_prefix("] has an ")) - else { - return false; - }; - // The index the shader reads, or an array's element of one. - let end = match read.strip_prefix("InputAttachmentIndex of ") { - Some(rest) => number(rest), - None => read - .strip_prefix("effective InputAttachmentIndex of ") - .and_then(number) - .and_then(|rest| rest.strip_prefix(" (started at InputAttachmentIndex ")) - .and_then(number) - .and_then(|rest| rest.strip_prefix(" plus index ")) - .and_then(number) - .and_then(|rest| rest.strip_prefix(" into the array)")), - }; - end == Some(COUNT) && rest == REST -} - -/// What follows the decimal digits `text` starts with; `None` without any. -fn number(text: &str) -> Option<&str> { - let digits = text.bytes().take_while(u8::is_ascii_digit).count(); - (digits > 0).then(|| &text[digits..]) -} - -/// Whether the layer release `version` is one whose source was read with the gap in place. -pub(super) fn read(version: u32) -> bool { - READ.contains(&version) -} - -#[cfg(test)] -mod tests { - use super::*; - use std::path::{Path, PathBuf}; - - /// The message as the lanes saw it on lavapipe (Mesa, LLVM 23.1.4) with the layer 1.4.363, - /// word for word. - fn seen() -> String { - "vkCreateGraphicsPipelines(): pCreateInfos[0] shader [VK_SHADER_STAGE_FRAGMENT_BIT] \ - [Set 0, Binding 2] has an InputAttachmentIndex of 0 which is not less than \ - VkPipelineRenderingCreateInfo::colorAttachmentCount (0)\nIf \ - VkRenderingInputAttachmentIndexInfo is provided, the index can be set, but without it, \ - it uses the default index values.\nHint: If using Depth/Stencil attachments, you should \ - be omitting the input attachment index in the shader to access the depth/stencil \ - attachments.\nThe Vulkan spec states: If the pipeline is being created with fragment \ - shader state and fragment output state, the value of renderPass is VK_NULL_HANDLE, and \ - VkRenderingInputAttachmentIndexInfo is not included, the fragment shader must not \ - contain any input attachments with a InputAttachmentIndex greater than or equal to \ - VkPipelineRenderingCreateInfo::colorAttachmentCount \ - (https://docs.vulkan.org/spec/latest/chapters/pipelines.html\ - #VUID-VkGraphicsPipelineCreateInfo-renderPass-09652)" - .to_owned() - } - - #[test] - fn the_link_time_report_of_an_input_attachment_is_the_gap() { - assert!(shape(ID, ID_NAME, &seen())); - let last = format!( - "(Warning - This VUID has now been reported 10 times, which is the \ - duplicate_message_limit value, this will be the last time reporting it).\n{}", - seen() - ); - assert!(shape(ID, ID_NAME, &last)); - // Another create info, binding or index (an index the layer cannot resolve reads the - // same), or an array's element. - let other = seen() - .replacen("pCreateInfos[0]", "pCreateInfos[12]", 1) - .replacen( - "Binding 2] has an InputAttachmentIndex of 0", - "Binding 5] has an InputAttachmentIndex of 3", - 1, - ); - assert!(shape(ID, ID_NAME, &other)); - let element = seen().replacen( - "has an InputAttachmentIndex of 0", - "has an effective InputAttachmentIndex of 1 (started at InputAttachmentIndex 0 plus \ - index 1 into the array)", - 1, - ); - assert!(shape(ID, ID_NAME, &element)); - } - - #[test] - fn the_per_stage_check_and_a_real_colour_count_are_not_the_gap() { - let text = seen(); - // The per-stage check, which runs only for dynamic rendering, reports at the stage. - let stage = text.replacen( - "pCreateInfos[0] shader", - "pCreateInfos[0].pStages[1] shader", - 1, - ); - assert!(!shape(ID, ID_NAME, &stage), "at a stage"); - // A count of colour attachments a dynamic-rendering pipeline states. - let counted = text.replacen( - "colorAttachmentCount (0)\n", - "colorAttachmentCount (2)\n", - 1, - ); - assert!(!shape(ID, ID_NAME, &counted), "a stated count"); - // Another call, stage, valid usage or message. - let call = text.replacen("vkCreateGraphicsPipelines()", "vkCreateShadersEXT()", 1); - assert!(!shape(ID, ID_NAME, &call), "another call"); - let vertex = text.replacen( - "VK_SHADER_STAGE_FRAGMENT_BIT", - "VK_SHADER_STAGE_VERTEX_BIT", - 1, - ); - assert!(!shape(ID, ID_NAME, &vertex), "another stage"); - assert!(!shape( - ID, - "VUID-VkGraphicsPipelineCreateInfo-renderPass-09531", - &text - )); - assert!(!shape(0, ID_NAME, &text)); - let unindexed = text.replacen("pCreateInfos[0]", "pCreateInfos[]", 1); - assert!(!shape(ID, ID_NAME, &unindexed), "no index"); - let before = format!("Something else.\n{text}"); - assert!(!shape(ID, ID_NAME, &before), "another preface"); - let first = text.split_once('\n').unwrap().0.to_owned(); - assert!(!shape(ID, ID_NAME, &first), "the first line alone"); - let after = text.replacen("If VkRenderingInputAttachmentIndexInfo", "If something", 1); - assert!(!shape(ID, ID_NAME, &after), "another second line"); - let longer = format!("{text} More."); - assert!(!shape(ID, ID_NAME, &longer), "more after the message"); - let named = text.replacen("Binding 2]", "Binding 2, variable \"x\"]", 1); - assert!( - !shape(ID, ID_NAME, &named), - "another descriptor's description" - ); - let note = format!("{}{}{}", LAST_TIME.0, LAST_TIME.1, text); - assert!(!shape(ID, ID_NAME, ¬e), "a note without its count"); - } - - #[test] - fn only_the_releases_read_pass() { - assert!(read(vk::make_api_version(0, 1, 4, 363))); - assert!(!read(vk::make_api_version(0, 1, 4, 357))); - assert!(!read(vk::make_api_version(0, 1, 4, 364))); - } - - fn rust_sources(dir: &Path, out: &mut Vec) { - for entry in std::fs::read_dir(dir).unwrap() { - let path = entry.unwrap().path(); - if path.is_dir() { - rust_sources(&path, out); - } else if path.extension().is_some_and(|e| e == "rs") { - out.push(path); - } - } - } - - /// The gap passes the message only because no pipeline the lanes validate is made for - /// dynamic rendering, where the valid usage holds: neither the runtime nor this crate's - /// executors name the structure such a pipeline is made with, or begin dynamic rendering. - #[test] - fn no_pipeline_here_is_made_for_dynamic_rendering() { - let crates = metal2vulkan_devtools::workspace_dir().join("crates"); - let mut files = Vec::new(); - rust_sources(&crates.join("metal2vulkan-runtime/src"), &mut files); - rust_sources(&crates.join("metal2vulkan-validation/src"), &mut files); - assert!(files.len() > 100, "{} sources", files.len()); - let names = [ - concat!("PipelineRendering", "CreateInfo"), - concat!("cmd_begin", "_rendering("), - concat!("RenderingInfo", "::default()"), - ]; - // This module quotes the layer's message, which names the structure. - let quoting = - crates.join("metal2vulkan-validation/src/candidate/runtime_case/input_index_gap.rs"); - assert!(files.contains("ing)); - let found: Vec = files - .iter() - .filter(|file| **file != quoting) - .flat_map(|file| { - let text = std::fs::read_to_string(file).unwrap(); - names - .iter() - .filter(|name| text.contains(**name)) - .map(|name| format!("{} names {name}", file.display())) - .collect::>() - }) - .collect(); - assert_eq!(found, Vec::::new()); - } -} diff --git a/crates/metal2vulkan-validation/src/candidate/runtime_case/layer_claim.rs b/crates/metal2vulkan-validation/src/candidate/runtime_case/layer_claim.rs deleted file mode 100644 index 52b3dffb9..000000000 --- a/crates/metal2vulkan-validation/src/candidate/runtime_case/layer_claim.rs +++ /dev/null @@ -1,801 +0,0 @@ -//! What a device validation makes through the runtime enabled of the instance layers it asked -//! for, and what a claim that needs the validation layer therefore holds. -//! -//! A device opens although a layer its caller asked for is one the loader cannot provide: the -//! runtime drops the whole layer list, creates the instance with none, and says as the device is -//! made which layers it was made without ([`LAYERS_DROPPED`], an informational message, no degrade -//! notice: the layers are diagnostics and nothing of Metal's answers differs). That is the right -//! behaviour for a caller that asked for a device, and the wrong silence for a claim: a test that -//! requires the validation layer to have reported nothing passes by reporting nothing at all. -//! -//! So the sink keeps that message instead of swallowing it ([`LayerFacts::heard`]), beside the -//! layers its device asked for ([`LayerFacts::asked`]), and a layer-dependent claim is stated -//! against the two ([`layer_reported_nothing`]): where the layer was enabled the claim holds over -//! what the layer saw, and where it was dropped the claim says in its own output that it was not -//! exercised here (`LANE-LAYER-ABSENT `, and a count per message list as it goes), so an -//! empty message list is never read as a clean run. -//! -//! The loader says so too, and first: it reports the layer it cannot provide through the messenger -//! chained at `vkCreateInstance`, as an error of the general type, before the call answers -//! `VK_ERROR_LAYER_NOT_PRESENT` ([`loader_layer_message`]). That message is the dropped layer and -//! nothing else wrong, so it is held until the device says whether it was made without the layer -//! ([`LayerFacts::hold`]): once the device says so, the held message passes with a line of its own, -//! and where nothing says so it fails with the rest ([`LayerFacts::release`]). Without that, every -//! claim on such a device fails on the loader's own message instead of running its own work. -//! -//! The decision is the instance's alone: the layers the device asked for, less those it announced -//! it was made without. Never the host, the driver's name or an environment variable. -//! -//! The loader also reports, at `vkCreateInstance`, each driver manifest whose library it could not -//! load, or that is no driver, and then ignores it ([`IgnoredDrivers`]): the host's listing of its -//! drivers (a vendor's manifest left behind by a driver no longer installed is common), whatever -//! the device does, and nothing it did. Those pass with a line of their own -//! (`LANE-LOADER-DRIVER `), each naming the library the loader said it ignored. - -use super::Messages; -use metal2vulkan_runtime::DebugMessage; -use std::ffi::CString; - -/// The id name the Vulkan loader gives the messages it reports itself. -const LOADER_MESSAGE: &str = "Loader Message"; - -/// What the loader's message about a layer it cannot provide names: the check it failed, and what -/// it found (`loader_validate_layers`, Vulkan-Loader `loader/loader.c`). -const VALIDATE_LAYERS: &str = "loader_validate_layers"; - -/// The rest of that message: the layer is none the loader lists. -const NOT_AVAILABLE: &str = "does not exist in the list of available layers"; - -/// Whether a message with this id name and text is the loader's own complaint about an instance -/// layer it cannot provide, and nothing wider. -pub(crate) fn loader_layer_message(id_name: &str, text: &str) -> bool { - id_name == LOADER_MESSAGE && text.contains(VALIDATE_LAYERS) && text.contains(NOT_AVAILABLE) -} - -/// How the loader's message about a driver manifest whose library it could not load begins -/// (`loader_icd_scan`, Vulkan-Loader `loader/loader.c`): the library the manifest names follows, -/// then [`IGNORING`]. -const ICD_SCAN_FAILED: &str = "loader_icd_scan: Failed loading library associated with ICD JSON "; - -/// How that message ends: the loader goes on without the manifest. -const IGNORING: &str = ". Ignoring this JSON"; - -/// How the loader's message about a driver library that loaded and gave no `vkCreateInstance` -/// begins (`loader_scanned_icd_add`): the library follows, and the message after it is -/// [`ICD_SCAN_FAILED`]'s about the same library. -const NO_CREATE_INSTANCE: &str = "loader_scanned_icd_add: Could not get 'vkCreateInstance' via \ - 'vk_icdGetInstanceProcAddr' for ICD "; - -/// How the loader's message about a library a driver manifest names that loaded and exports -/// neither entry point a driver does begins (`loader_scanned_icd_add`): the library follows, then -/// [`NO_ENTRY_POINT_END`]; the loader ignores the manifest with no other message. -const NO_ENTRY_POINT: &str = "loader_scanned_icd_add: Attempt to retrieve either \ - 'vkGetInstanceProcAddr' or 'vk_icdGetInstanceProcAddr' from ICD "; - -/// How that message ends. -const NO_ENTRY_POINT_END: &str = " failed."; - -/// The loader's own reports, in one message list, of driver manifests it ignored: the libraries -/// it said it ignored for failing to load them ([`ICD_SCAN_FAILED`]), which explain its messages -/// about the same library alone. -pub(crate) struct IgnoredDrivers(Vec); - -impl IgnoredDrivers { - /// The libraries the loader said it ignored, among `messages`. - pub(crate) fn of_messages(messages: &[DebugMessage]) -> IgnoredDrivers { - IgnoredDrivers::of( - (messages.iter()).map(|message| (message.id_name.as_str(), message.text.as_str())), - ) - } - - /// The libraries the loader said it ignored, among `messages`, each its id name and text. - pub(crate) fn of<'a>(messages: impl IntoIterator) -> IgnoredDrivers { - let libraries = (messages.into_iter()) - .filter(|&(id_name, _)| id_name == LOADER_MESSAGE) - .filter_map(|(_, text)| { - let library = text.strip_prefix(ICD_SCAN_FAILED)?; - library - .strip_suffix(IGNORING) - .filter(|library| !library.is_empty()) - }) - .map(str::to_owned) - .collect(); - IgnoredDrivers(libraries) - } - - /// Whether a message with this id name and text is the loader's own report of a driver - /// manifest it ignored, and nothing wider: its message that it ignored the library, the dynamic - /// linker's error it forwards about that library (`: `), or its message that the - /// library gave no `vkCreateInstance`; or its message that a library a manifest names is no - /// driver, which names the library it ignored itself. - pub(crate) fn explains(&self, id_name: &str, text: &str) -> bool { - if id_name != LOADER_MESSAGE { - return false; - } - let no_driver = (text.strip_prefix(NO_ENTRY_POINT)) - .and_then(|rest| rest.strip_suffix(NO_ENTRY_POINT_END)) - .is_some_and(|library| !library.is_empty()); - no_driver - || self.0.iter().any(|library| { - let named = |prefix: &str, suffix: &str| { - (text.strip_prefix(prefix)) - .and_then(|rest| rest.strip_suffix(suffix)) - .is_some_and(|named| named == library) - }; - named(ICD_SCAN_FAILED, IGNORING) - || named(NO_CREATE_INSTANCE, "") - || (text.strip_prefix(library.as_str())) - .is_some_and(|why| why.starts_with(": ")) - }) - } -} - -/// How the loader's message about an instance layer the host lists twice begins (two manifests of -/// one layer name): it names the copy it removed, then the one it kept. -#[cfg(test)] -const REMOVING_LAYER: &str = "Removing layer "; - -/// The rest of that message, between the two copies. -#[cfg(test)] -const DUPLICATE_OF: &str = " because it is a duplicate of "; - -/// Whether a message with this id name and text is the loader's own warning that the host lists an -/// instance layer twice, and which copy it removed: the host's listing of its layers, reported -/// through the messenger chained at `vkCreateInstance` whichever layers a device asks for, and -/// nothing a device said; nothing wider. The lane's sink fails on no warning of the general kind, -/// so it reads this only where every message is checked (`runtime_lane::creation_heard_checked`). -#[cfg(test)] -pub(crate) fn loader_duplicate_layer_message(id_name: &str, text: &str) -> bool { - id_name == LOADER_MESSAGE && text.starts_with(REMOVING_LAYER) && text.contains(DUPLICATE_OF) -} - -/// The id name of the informational message a device sends as it is made where the loader could -/// not provide the instance layers its caller asked for; the runtime's `device/create.rs` names it -/// so. -pub const LAYERS_DROPPED: &str = "metal2vulkan-instance-layers-dropped"; - -/// What the instance of the devices reporting to one message list enabled of the layers they asked -/// for: the list asked for, and whether the loader could not provide it. The runtime drops the -/// whole list on a miss and creates the instance with none, so the enabled set is either all of -/// what was asked for or nothing. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct EnabledLayers { - asked: Vec, - dropped: bool, -} - -impl EnabledLayers { - /// The instance layers the device asked for, in the order it asked for them. - pub fn asked(&self) -> &[CString] { - &self.asked - } - - /// The layers the instance enabled: those asked for, or none where the loader could not - /// provide them. - pub fn enabled(&self) -> &[CString] { - match self.dropped { - true => &[], - false => &self.asked, - } - } - - /// The layers the loader could not provide, which the instance was created without. - pub fn dropped(&self) -> &[CString] { - match self.dropped { - true => &self.asked, - false => &[], - } - } - - /// Whether the instance enabled `layer`. - pub fn enabled_layer(&self, layer: &std::ffi::CStr) -> bool { - self.enabled().iter().any(|name| name.as_c_str() == layer) - } - - /// Whether the instance enabled the validation layer, so that what it reported is evidence. - pub fn validates(&self) -> bool { - self.enabled_layer(super::VALIDATION_LAYER) - } -} - -/// What a claim that needs the validation layer holds, stated against what the instance enabled -/// ([`layer_reported_nothing`]). -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum LayerClaim { - /// The device enabled the validation layer, and it reported nothing: the claim holds over - /// everything the layer checks. - Held, - /// The device asked for the validation layer and the loader could not provide it (the layers - /// it was made without, as it announced them): there was nothing to report, so the claim was - /// not exercised here. Printed as such, never a silent pass. - NotExercised { dropped: Vec }, - /// The device asked for no validation layer, so the claim is none of the layer's: a device a - /// test makes without it, to time it. - NoLayerAsked, -} - -impl LayerClaim { - /// Whether the claim was exercised: the layer was there to report. - pub fn exercised(&self) -> bool { - matches!(self, LayerClaim::Held) - } -} - -/// Require that the validation layer reported nothing of `claim` on the devices reporting to -/// `messages`, and say what that holds. -/// -/// Every message the layer reported fails here, as `assert_eq!(messages.take(), Vec::new())` did, -/// and the messages are taken either way. What the claim then stands on is the instance's answer -/// alone ([`EnabledLayers`]): [`LayerClaim::Held`] where the layer was enabled, else a claim that -/// was not exercised, printed on stderr with the test's name. -/// -/// For a claim no narrower than the layer's own silence, [`layer_reported_nothing_at_all`]. -/// -/// # Panics -/// -/// Where the layer reported anything that fails a run. -pub fn layer_reported_nothing(messages: &Messages, claim: &str) -> LayerClaim { - stated(messages, claim, &format!("{claim}: "), LAYER) -} - -/// What a lane states where it names no claim narrower than the layer's own silence: that the -/// validation layer reported nothing at all of the work the test did up to here. Named in the line -/// a layerless device prints, where the test's own name says the rest ([`LayerFacts::claim`]). -const NOTHING_AT_ALL: &str = "the validation layer reported nothing of the work so far"; - -/// Require that the validation layer reported nothing at all of the work the devices reporting to -/// `messages` did, and say what that holds ([`layer_reported_nothing`] of the lane's widest -/// claim). -/// -/// The claim the lane states oftenest, and exactly what `assert!(messages.take().is_empty())` -/// stated: whatever the layer checked of the work so far, it reported nothing of it. A test that -/// holds something narrower names it ([`layer_reported_nothing`]); the claim's words change -/// nothing of what fails, every message failing either way, and say which claim a layerless -/// device could not exercise. -/// -/// # Panics -/// -/// Where the layer reported anything that fails a run. -pub fn layer_reported_nothing_at_all(messages: &Messages) -> LayerClaim { - stated(messages, NOTHING_AT_ALL, "", LAYER) -} - -/// Require that the devices reporting to `messages` reported nothing of `claim` that fails, where -/// they asked for no validation layer: a device a test makes without it, so that what reaches the -/// list is the driver's own and the runtime's. The layer's absence takes nothing from such a -/// claim, and the claim is [`LayerClaim::NoLayerAsked`]. -/// -/// # Panics -/// -/// Where anything reported fails a run, and where such a device did ask for the validation layer: -/// then the claim is the layer's after all, and [`layer_reported_nothing`] is how it is stated. -pub fn nothing_reported_without_the_layer(messages: &Messages, claim: &str) -> LayerClaim { - let asked = messages.enabled_layers(); - assert!( - !asked - .asked() - .iter() - .any(|name| name.as_c_str() == super::VALIDATION_LAYER), - "{claim}: the device asked for the validation layer, so the claim is the layer's" - ); - stated(messages, claim, &format!("{claim}: "), "the device") -} - -/// What a claim names as having reported nothing, where the validation layer is what would have. -const LAYER: &str = "the validation layer"; - -/// Take what the devices reporting to `messages` reported, state `claim` against what their -/// instance enabled, and fail on anything reported, the failure led by `lead` and naming -/// `reporter` as what reported. -fn stated(messages: &Messages, claim: &str, lead: &str, reporter: &str) -> LayerClaim { - let reported = messages.take(); - let stated = messages.state_layer_claim(claim); - assert!( - reported.is_empty(), - "{lead}{reporter} reported\n{reported:#?}" - ); - stated -} - -/// What one message list knows of the layers of the devices reporting to it. -#[derive(Clone, Debug, Default)] -pub(super) struct LayerFacts { - /// The instance layers the device reporting here asked for, in order; empty until a device - /// records them ([`LayerFacts::asked`]). - asked: Vec, - /// The text of [`LAYERS_DROPPED`], where such a device announced it was made without them. - dropped: Option, - /// How many layer-dependent claims were stated here while the layers were dropped. - unexercised: usize, - /// Whether the absence was printed already, so one device's many claims print one line and a - /// count. - said: bool, - /// The loader's own messages about a layer it cannot provide, held until the device says - /// whether it was made without that layer ([`LayerFacts::hold`]). - held: Vec, - /// How many of them passed, the device having said so. - passed: usize, -} - -/// The most of the loader's own messages one list holds: a flood is nothing it can explain. -const MAX_HELD: usize = 8; - -impl LayerFacts { - /// A device reporting here asks for `layers`: what an earlier device of this list announced - /// about its own layers is not the new one's. - pub(super) fn asked(&mut self, layers: &[CString]) { - self.asked = layers.to_vec(); - self.dropped = None; - self.said = false; - } - - /// Take the message `id_name` with text `text` of the test `test`, where it is the one a - /// device sends as it is made without the layers it asked for; whether it was taken. - pub(super) fn heard(&mut self, test: &str, id_name: &str, text: &str) -> bool { - if id_name != LAYERS_DROPPED { - return false; - } - self.dropped = Some(text.to_owned()); - // The loader said the same thing first, about the same layers: the device's announcement - // explains it, so it passes with a line of its own. - for message in self.held.split_off(0) { - self.passed += 1; - eprintln!( - "LANE-LAYER-ABSENT {}: passed, the loader's own message about the layer the \ - device was then made without: {} ({}): {}", - test, - message.id_name, - message.id, - message.text.replace('\n', " ") - ); - } - true - } - - /// Whether the loader's own complaint about a layer it cannot provide is held here rather - /// than failed at once: only where this list's device asked for a layer at all (with none - /// asked for, the loader's complaint is about nothing of ours), and only up to [`MAX_HELD`]. - pub(super) fn holds(&self) -> bool { - !self.asked.is_empty() && self.held.len() < MAX_HELD - } - - /// Hold `message`, the loader's own complaint, until the device says whether it was made - /// without that layer; whether it was held ([`LayerFacts::holds`]). - pub(super) fn hold(&mut self, message: &DebugMessage) -> bool { - if !self.holds() { - return false; - } - self.held.push(message.clone()); - true - } - - /// Whether a device of this list said it was made without the layers it asked for, which is - /// what explains the loader's complaint. - pub(super) fn explained(&self) -> bool { - self.dropped.is_some() - } - - /// The held messages nothing explained, which fail with the rest: a loader that refused a - /// layer where no device of this list says it was made without one. - pub(super) fn release(&mut self) -> Vec { - match self.explained() { - true => Vec::new(), - false => self.held.split_off(0), - } - } - - /// What the instance of the devices reporting here enabled of the layers they asked for. - pub(super) fn enabled(&self) -> EnabledLayers { - EnabledLayers { - asked: self.asked.clone(), - dropped: self.dropped.is_some(), - } - } - - /// The text of the message a device of this list sent as it was made without the layers it - /// asked for. - pub(super) fn dropped_message(&self) -> Option<&str> { - self.dropped.as_deref() - } - - /// State `claim` of `test` against the layers the instance enabled, printing the first claim - /// a layerless device cannot exercise. - pub(super) fn claim(&mut self, test: &str, claim: &str) -> LayerClaim { - let enabled = self.enabled(); - if enabled.validates() { - return LayerClaim::Held; - } - let dropped: Vec = enabled - .dropped() - .iter() - .map(|name| name.to_string_lossy().into_owned()) - .collect(); - if dropped.is_empty() { - // A device that asked for no validation layer: the claim is none of the layer's. - return LayerClaim::NoLayerAsked; - } - self.unexercised += 1; - if !self.said { - self.said = true; - eprintln!( - "LANE-LAYER-ABSENT {test}: the loader could not provide {}, so the validation \ - layer reported nothing at all; every claim of what it reported is not exercised \ - here. First: {claim}", - dropped.join(", ") - ); - } - LayerClaim::NotExercised { dropped } - } - - /// The lines a message list prints as it goes: the claims no layer exercised, and the - /// loader's own messages that the device's announcement explained. - pub(super) fn report(&self, test: &str) { - if self.unexercised != 0 { - eprintln!( - "LANE-LAYER-ABSENT count {test}: {} layer-dependent claim(s) stated with no \ - validation layer, so not exercised", - self.unexercised - ); - } - if self.passed != 0 { - eprintln!( - "LANE-LAYER-ABSENT count {test}: {} message(s) of the loader's about the layer \ - the device was made without passed", - self.passed - ); - } - } -} - -#[cfg(test)] -mod tests { - use super::{ - layer_reported_nothing, layer_reported_nothing_at_all, nothing_reported_without_the_layer, - LayerClaim, LAYERS_DROPPED, - }; - use crate::candidate::runtime_case::{Messages, VALIDATION_LAYER}; - use std::ffi::CString; - - /// The message a device sends as it is made without the layers it asked for, as the runtime - /// writes it (`device/create.rs`, `layers_dropped`): its id name is what the sink keys on, and - /// the text is the device's own. - fn dropped_message() -> String { - format!( - "metal2vulkan: the device on a device was made without the instance layer(s) {} \ - [{LAYERS_DROPPED}]", - VALIDATION_LAYER.to_string_lossy() - ) - } - - /// A message list of a device that asked for the validation layer and was made without it, - /// the loader having none to provide. Its own input: no device, no loader, no host. - fn layerless() -> Messages { - let messages = Messages::default(); - messages.device_asked_layers(&[VALIDATION_LAYER.to_owned()]); - assert!( - messages.heard_informational(LAYERS_DROPPED, &dropped_message()), - "the sink keeps the message a device sends as it is made without its layers" - ); - messages - } - - /// A claim of what the validation layer reported, stated on a list whose device was made - /// without it, is not exercised: it names the layer that was dropped, and the message list is - /// empty, so the claim the lane used to state (`messages.take() == Vec::new()`) passed on the - /// same input. This test fails if [`layer_reported_nothing`] ever answers [`LayerClaim::Held`] - /// with no layer present. - #[test] - fn a_claim_of_what_the_layer_reported_is_not_exercised_where_the_layer_was_dropped() { - let messages = layerless(); - // What the instance enabled: nothing of what it asked for. - let enabled = messages.enabled_layers(); - assert_eq!(enabled.asked(), [VALIDATION_LAYER.to_owned()]); - assert_eq!(enabled.enabled(), [] as [CString; 0]); - assert_eq!(enabled.dropped(), [VALIDATION_LAYER.to_owned()]); - assert!(!enabled.validates()); - assert_eq!(messages.layers_dropped_message(), Some(dropped_message())); - // The bad input the old claim passed on: nothing was reported, because nothing could be. - assert_eq!( - messages.take(), - Vec::new(), - "the layerless list reports nothing at all" - ); - assert_eq!( - layer_reported_nothing(&messages, "no Vulkan object leaked"), - LayerClaim::NotExercised { - dropped: vec![VALIDATION_LAYER.to_string_lossy().into_owned()], - }, - "a claim with no layer present must say it was not exercised" - ); - assert!(!layer_reported_nothing(&messages, "and again").exercised()); - } - - /// The same claim on a list whose device enabled the layer it asked for holds: the layer was - /// there to report, and reported nothing. - #[test] - fn a_claim_of_what_the_layer_reported_holds_where_the_layer_was_enabled() { - let messages = Messages::default(); - messages.device_asked_layers(&[VALIDATION_LAYER.to_owned()]); - let enabled = messages.enabled_layers(); - assert_eq!(enabled.enabled(), [VALIDATION_LAYER.to_owned()]); - assert!(enabled.validates()); - assert_eq!(messages.layers_dropped_message(), None); - let claim = layer_reported_nothing(&messages, "no Vulkan object leaked"); - assert_eq!(claim, LayerClaim::Held); - assert!(claim.exercised()); - } - - /// The widest claim, which no test names ([`layer_reported_nothing_at_all`], the one the lane - /// states oftenest), is not exercised either where the layer was dropped: so the 300-odd lane - /// sites that asserted `messages.take()` was empty and said no more now say so instead of - /// passing on a list that could report nothing at all. - #[test] - fn the_widest_claim_is_not_exercised_where_the_layer_was_dropped() { - let messages = layerless(); - assert_eq!( - messages.take(), - Vec::new(), - "the layerless list reports nothing at all" - ); - assert_eq!( - layer_reported_nothing_at_all(&messages), - LayerClaim::NotExercised { - dropped: vec![VALIDATION_LAYER.to_string_lossy().into_owned()], - }, - "the widest claim with no layer present must say it was not exercised" - ); - assert!(!layer_reported_nothing_at_all(&messages).exercised()); - } - - /// The same claim on a list whose device enabled the layer holds. - #[test] - fn the_widest_claim_holds_where_the_layer_was_enabled() { - let messages = Messages::default(); - messages.device_asked_layers(&[VALIDATION_LAYER.to_owned()]); - let claim = layer_reported_nothing_at_all(&messages); - assert_eq!(claim, LayerClaim::Held); - assert!(claim.exercised()); - } - - /// A claim a test states of a device it made without the validation layer - /// ([`nothing_reported_without_the_layer`]: the driver's own messages and the runtime's) is - /// none of the layer's, and the layer's absence takes nothing from it. - #[test] - fn a_claim_of_what_a_layerless_device_reported_is_none_of_the_layer_s() { - let messages = Messages::default(); - messages.device_asked_layers(&[]); - assert_eq!( - nothing_reported_without_the_layer(&messages, "nothing the driver said fails"), - LayerClaim::NoLayerAsked - ); - } - - /// The same claim on a device that did ask for the validation layer fails: then what reaches - /// the list is the layer's, and the claim is the layer's to state - /// ([`layer_reported_nothing`]), so a test that stops clearing its device's layers cannot - /// keep the weaker statement. - #[test] - #[should_panic(expected = "the device asked for the validation layer")] - fn a_layerless_claim_on_a_device_that_asked_for_the_layer_fails() { - let messages = Messages::default(); - messages.device_asked_layers(&[VALIDATION_LAYER.to_owned()]); - nothing_reported_without_the_layer(&messages, "nothing the driver said fails"); - } - - /// A device a test makes with no layer at all, to time it, states no claim of the layer's. - #[test] - fn a_device_that_asked_for_no_layer_states_no_claim_of_the_layer_s() { - let messages = Messages::default(); - messages.device_asked_layers(&[]); - assert!(!messages.enabled_layers().validates()); - let claim = layer_reported_nothing(&messages, "nothing of the layer's"); - assert_eq!(claim, LayerClaim::NoLayerAsked); - assert!(!claim.exercised()); - } - - /// A device made again on one list answers for itself: the layers an earlier device of the - /// list was made without are not the new one's, which enabled every layer it asked for. - #[test] - fn a_later_device_on_one_list_answers_for_its_own_layers() { - let messages = layerless(); - assert!(!messages.enabled_layers().validates()); - messages.device_asked_layers(&[VALIDATION_LAYER.to_owned()]); - assert!( - messages.enabled_layers().validates(), - "the new device announced nothing, so it was made with the layer it asked for" - ); - assert_eq!(messages.layers_dropped_message(), None); - assert_eq!( - layer_reported_nothing(&messages, "no Vulkan object leaked"), - LayerClaim::Held - ); - } - - /// The loader's complaint is held only where this list's device asked for a layer, and it is - /// explained only once a device said it was made without one: so a loader that refuses a - /// layer no device accounts for still fails the run (`Messages::take` releases it). - #[test] - fn the_loader_s_message_is_held_for_a_device_that_asked_and_explained_by_its_answer() { - use super::LayerFacts; - let mut facts = LayerFacts::default(); - assert!( - !facts.holds(), - "with no layer asked for, the loader's complaint is about nothing of ours" - ); - facts.asked(&[VALIDATION_LAYER.to_owned()]); - assert!( - facts.holds(), - "a device that asked for a layer accounts for it" - ); - assert!( - !facts.explained(), - "nothing explains it until a device says it was made without the layer" - ); - assert!(facts.heard("a test", LAYERS_DROPPED, &dropped_message())); - assert!(facts.explained()); - // A device made again asks afresh: its own answer explains its own loader messages. - facts.asked(&[VALIDATION_LAYER.to_owned()]); - assert!(!facts.explained()); - assert!(facts.release().is_empty(), "nothing was held"); - } - - /// The loader's own complaint about the layer it cannot provide, and nothing wider. - #[test] - fn the_loader_s_message_about_a_layer_it_cannot_provide_is_matched_and_nothing_wider() { - assert!(super::loader_layer_message( - "Loader Message", - "loader_validate_layers: Layer 0 does not exist in the list of available layers" - )); - for (id_name, text) in [ - // Another of the loader's messages. - ( - "Loader Message", - "terminator_CreateInstance: Failed to CreateInstance in ICD 0", - ), - // The same words from something that is not the loader. - ( - "VUID-vkCreateInstance-ppEnabledLayerNames-01727", - "loader_validate_layers: Layer 0 does not exist in the list of available layers", - ), - // Half the words. - ("Loader Message", "loader_validate_layers: Layer 0 is fine"), - ] { - assert!( - !super::loader_layer_message(id_name, text), - "{id_name}: {text}" - ); - } - } - - /// The loader's messages about a driver manifest it ignored, as a host left them, each its id - /// name and text: one whose library is missing (the dynamic linker's error, then the - /// loader's), one whose library loaded and gave no `vkCreateInstance`, and one whose library - /// is no driver. - fn ignored_drivers() -> Vec<(&'static str, &'static str)> { - [ - "/nonexistent/libstale_vulkan.so: cannot open shared object file: No such file or \ - directory", - "loader_icd_scan: Failed loading library associated with ICD JSON \ - /nonexistent/libstale_vulkan.so. Ignoring this JSON", - "loader_scanned_icd_add: Could not get 'vkCreateInstance' via \ - 'vk_icdGetInstanceProcAddr' for ICD libGLX_nvidia.so.0", - "loader_icd_scan: Failed loading library associated with ICD JSON libGLX_nvidia.so.0. \ - Ignoring this JSON", - "loader_scanned_icd_add: Attempt to retrieve either 'vkGetInstanceProcAddr' or \ - 'vk_icdGetInstanceProcAddr' from ICD /usr/lib/libz.so.1 failed.", - ] - .map(|text| ("Loader Message", text)) - .to_vec() - } - - /// The loader's reports of a driver manifest it ignored, each about the library it said it - /// ignored, and nothing wider: the same words of another id name, a linker's error or a missing - /// `vkCreateInstance` about a library it did not say it ignored, and its other messages. - #[test] - fn the_loader_s_reports_of_a_driver_manifest_it_ignored_are_matched_and_nothing_wider() { - let reported = ignored_drivers(); - let ignored = super::IgnoredDrivers::of(reported.iter().copied()); - for &(id_name, text) in &reported { - assert!(ignored.explains(id_name, text), "{text}"); - } - for (id_name, text) in [ - // The same words from something that is not the loader. - ( - "VUID-vkCreateInstance-None", - "loader_icd_scan: Failed loading library associated with ICD JSON \ - /nonexistent/libstale_vulkan.so. Ignoring this JSON", - ), - // A linker's error about a library the loader did not say it ignored. - ( - "Loader Message", - "/usr/lib/libvulkan_radeon.so: cannot open shared object file: No such file or \ - directory", - ), - // No `vkCreateInstance` from a library the loader did not say it ignored. - ( - "Loader Message", - "loader_scanned_icd_add: Could not get 'vkCreateInstance' via \ - 'vk_icdGetInstanceProcAddr' for ICD libvulkan_radeon.so", - ), - // A manifest naming no library. - ( - "Loader Message", - "loader_icd_scan: Failed loading library associated with ICD JSON . Ignoring this \ - JSON", - ), - // Another of the loader's messages. - ( - "Loader Message", - "terminator_CreateInstance: Failed to CreateInstance in ICD 0", - ), - // The library named, in other words. - ( - "Loader Message", - "/nonexistent/libstale_vulkan.so was loaded", - ), - ] { - assert!(!ignored.explains(id_name, text), "{id_name}: {text}"); - } - // Without the loader's word that it ignored the library, its linker error and its missing - // `vkCreateInstance` stand alone and fail. - let alone = super::IgnoredDrivers::of(reported[..1].iter().copied()); - assert!(!alone.explains(reported[0].0, reported[0].1)); - assert!(!alone.explains(reported[2].0, reported[2].1)); - } - - /// The loader's warning that the host lists a layer twice, and nothing wider. - #[test] - fn the_loader_s_warning_about_a_layer_listed_twice_is_matched_and_nothing_wider() { - assert!(super::loader_duplicate_layer_message( - "Loader Message", - "Removing layer VK_LAYER_KHRONOS_validation (/usr/share/vulkan/explicit_layer.d/\ - VkLayer_khronos_validation.json) because it is a duplicate of \ - VK_LAYER_KHRONOS_validation (/tmp/layers/VkLayer_khronos_validation.json)" - )); - for (id_name, text) in [ - // The loader's message about a layer it cannot provide. - ( - "Loader Message", - "loader_validate_layers: Layer 0 does not exist in the list of available layers", - ), - // The same words from something that is not the loader. - ( - "VUID-vkCreateInstance-ppEnabledLayerNames-01727", - "Removing layer VK_LAYER_A (a.json) because it is a duplicate of VK_LAYER_A (b.json)", - ), - // Half the words. - ("Loader Message", "Removing layer VK_LAYER_A (a.json)"), - // The words, not at the start. - ( - "Loader Message", - "Failed: Removing layer VK_LAYER_A (a.json) because it is a duplicate of \ - VK_LAYER_A (b.json)", - ), - ] { - assert!( - !super::loader_duplicate_layer_message(id_name, text), - "{id_name}: {text}" - ); - } - } - - /// Every other informational message is none of this list's layer facts: the sink keeps the - /// one message and leaves the rest where they were. - #[test] - fn no_other_informational_message_is_taken_for_the_layers() { - let messages = Messages::default(); - messages.device_asked_layers(&[VALIDATION_LAYER.to_owned()]); - for id_name in [ - "metal2vulkan-driver-pipeline-cache-kept", - "metal2vulkan-pipeline-creation", - "", - ] { - assert!( - !messages.heard_informational(id_name, "a message"), - "{id_name} is not the dropped-layer message" - ); - } - assert_eq!(messages.layers_dropped_message(), None); - assert!(messages.enabled_layers().validates()); - } -} diff --git a/crates/metal2vulkan-validation/src/candidate/runtime_case/query_reset_gap.rs b/crates/metal2vulkan-validation/src/candidate/runtime_case/query_reset_gap.rs deleted file mode 100644 index fa93f33d2..000000000 --- a/crates/metal2vulkan-validation/src/candidate/runtime_case/query_reset_gap.rs +++ /dev/null @@ -1,180 +0,0 @@ -//! A validation-layer gap a [`Messages`](super::Messages) sink lets pass: the layer's check of -//! `VUID-vkResetQueryPool-firstQuery-02741` reports a whole query pool in use where the spec -//! speaks of the range reset. -//! -//! The valid usage reads: "Submitted commands that refer to the range specified by `firstQuery` -//! and `queryCount` in `queryPool` must have completed execution" (`vkResetQueryPool`). The -//! layer checks it so: for each query of the range, "if (query_state != QUERYSTATE_AVAILABLE && -//! query_state != QUERYSTATE_UNKNOWN)", it calls `ValidateObjectNotInUse(query_pool_state.get(), -//! ...)`, under "Same idea as VUID-vkDestroyQueryPool-queryPool-00793" (Vulkan-ValidationLayers -//! v1.4.363, tag commit 2ea16de8, and vulkan-sdk-1.4.363.1, 317cff06, -//! `layers/core_checks/cc_query.cpp`, `CoreChecks::PreCallValidateResetQueryPool`). That reports -//! the pool in use by any command buffer in flight that refers to any of its queries. A query -//! whose command buffer completed stays out of the two states it accepts, so a reset of it while -//! another range of the same pool is in flight is reported. Main later checks only a query still -//! `QUERYSTATE_ENDED`, "only ENDED between the submission that wrote it and that submission -//! completing (or its results being read)" (main of 2026-11-07); v1.4.357 has no check. -//! -//! The runtime's one host reset is a timestamp slot's (`runtime/src/gpu_time.rs`, `slot`): a -//! slot's queries are reset as a command buffer takes it, and a slot is taken only once given -//! back, after its last holding's command buffer completed and its timestamps were read, or was -//! never submitted. Its pool holds other slots, which other command buffers in flight hold, so -//! every lane that keeps two timed command buffers in flight at once meets the report: on -//! lavapipe and on RADV (a Radeon 780M) with the layer 1.4.363, -//! `runtime_lane::staging_batches::batches_after_one_that_waited_for_a_staging_copy_follow_its_wait` -//! failed every run, and both `runtime_lane::replayed_frames` tests that keep a frame in flight -//! failed some runs. -//! -//! [`shape`] matches that message for a `vkResetQueryPool` call and nothing wider; [`read`] keys -//! the layer releases whose source was read with the whole-pool check in place. The message -//! cannot tell the range's own use from another range's, so where it passes the reset is checked -//! as by v1.4.357, which has no check. On any other release it fails, marked "re-read -//! vkResetQueryPool in layer X.Y.Z", so a fixed or changed layer is checked again rather than -//! trusted. - -use ash::vk; - -/// `messageIdNumber` of `VUID-vkResetQueryPool-firstQuery-02741`, as the layer hashes its name. -const ID: i32 = 150880399; - -/// The id name of the valid usage. -const ID_NAME: &str = "VUID-vkResetQueryPool-firstQuery-02741"; - -/// The start of the message: the call, and the pool (`ValidateObjectNotInUse`). -const CALL: &str = "vkResetQueryPool(): can't be called on VkQueryPool 0x"; - -/// What follows the pool: the command buffer in flight that holds it. -const IN_USE: &str = " that is currently in use by VkCommandBuffer 0x"; - -/// The end of the message: the valid usage's text, as the layer 1.4.363 quotes it. -const STATES: &str = "\nThe Vulkan spec states: Submitted commands that refer to the range \ - specified by firstQuery and queryCount in queryPool must have completed execution \ - (https://docs.vulkan.org/spec/latest/chapters/queries.html#VUID-vkResetQueryPool-firstQuery-02741)"; - -/// The note the layer puts before a message it reports for the last time -/// (`duplicate_message_limit`). -const LAST_TIME: &str = "(Warning - This VUID has now been reported "; - -/// The end of that note. -const LAST_TIME_END: &str = ", this will be the last time reporting it).\n"; - -/// The layer releases (`VkLayerProperties::specVersion` of `VK_LAYER_KHRONOS_validation`) whose -/// `PreCallValidateResetQueryPool` was read with the whole-pool check in place: v1.4.363 (tag -/// commits 2ea16de8 and, for vulkan-sdk-1.4.363.1, 317cff06). -pub(super) const READ: &[u32] = &[vk::make_api_version(0, 1, 4, 363)]; - -/// Where the gap is, for the line each message let pass prints. -pub(super) const SOURCE: &str = "Vulkan-ValidationLayers v1.4.363 (2ea16de8; \ - vulkan-sdk-1.4.363.1, 317cff06) layers/core_checks/cc_query.cpp, \ - CoreChecks::PreCallValidateResetQueryPool: a query of the range neither AVAILABLE nor UNKNOWN \ - calls ValidateObjectNotInUse on the whole pool (\"Same idea as \ - VUID-vkDestroyQueryPool-queryPool-00793\")"; - -/// Whether a message with this id, id name and text is the gap's: `vkResetQueryPool` reported -/// for a pool in use by a command buffer, with the valid usage's text, and nothing else. -pub(super) fn shape(id: i32, id_name: &str, text: &str) -> bool { - if id != ID || id_name != ID_NAME { - return false; - } - let text = match text.strip_prefix(LAST_TIME) { - Some(note) => match note.find(LAST_TIME_END) { - Some(end) if !note[..end].contains('\n') => ¬e[end + LAST_TIME_END.len()..], - _ => return false, - }, - None => text, - }; - let Some(rest) = text.strip_prefix(CALL) else { - return false; - }; - let Some(rest) = after_handle(rest).and_then(|rest| rest.strip_prefix(IN_USE)) else { - return false; - }; - after_handle(rest) == Some(STATES) -} - -/// What follows the hexadecimal digits a handle begins `text` with, and the object's debug name -/// in brackets where the layer prints one; `None` without any digit. -fn after_handle(text: &str) -> Option<&str> { - let end = text - .find(|c: char| !c.is_ascii_hexdigit()) - .unwrap_or(text.len()); - if end == 0 { - return None; - } - let rest = &text[end..]; - match rest.strip_prefix('[') { - Some(named) => { - let close = named.find(']')?; - (!named[..close].contains('\n')).then(|| &named[close + 1..]) - } - None => Some(rest), - } -} - -/// Whether the layer release `version` is one whose source was read with the gap in place. -pub(super) fn read(version: u32) -> bool { - READ.contains(&version) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// The message as the lanes saw it on lavapipe (Mesa 26.2.6, LLVM 23.1.4) and RADV with the - /// layer 1.4.363. - fn seen() -> String { - format!( - "vkResetQueryPool(): can't be called on VkQueryPool 0x340000000034 that is currently \ - in use by VkCommandBuffer 0x7f28f5e85630{STATES}" - ) - } - - #[test] - fn the_layer_s_report_of_a_pool_in_use_at_a_host_reset_is_the_gap() { - assert!(shape(ID, ID_NAME, &seen())); - let last = format!( - "{LAST_TIME}10 times, which is the duplicate_message_limit value{LAST_TIME_END}{}", - seen() - ); - assert!(shape(ID, ID_NAME, &last)); - // A command buffer, or the pool, with a debug name. - let named = seen().replace("0x7f28f5e85630", "0x7f28f5e85630[a label]"); - assert!(shape(ID, ID_NAME, &named), "a named command buffer"); - let pool = seen().replace("0x340000000034", "0x340000000034[timestamps]"); - assert!(shape(ID, ID_NAME, &pool), "a named pool"); - } - - #[test] - fn other_messages_are_not_the_gap() { - let text = seen(); - assert!(!shape(0, ID_NAME, &text)); - assert!(!shape(ID, "VUID-vkResetQueryPool-firstQuery-09436", &text)); - // Another call, another object, another holder. - let destroy = text.replacen("vkResetQueryPool(): ", "vkDestroyQueryPool(): ", 1); - assert!(!shape(ID, ID_NAME, &destroy), "another call"); - let buffer = text.replace("VkQueryPool 0x", "VkBuffer 0x"); - assert!(!shape(ID, ID_NAME, &buffer), "another object"); - let queue = text.replace("VkCommandBuffer 0x", "VkQueue 0x"); - assert!(!shape(ID, ID_NAME, &queue), "another holder"); - // No handle, another valid usage's text, or more after it. - let unhandled = text.replace("0x340000000034", "0x"); - assert!(!shape(ID, ID_NAME, &unhandled), "no handle"); - let other = text.replace("must have completed execution", "must not be in use"); - assert!(!shape(ID, ID_NAME, &other), "another text"); - let more = format!("{text}\nSomething else."); - assert!(!shape(ID, ID_NAME, &more), "more after it"); - // Anything else before the call. - let before = format!("Something else.\n{text}"); - assert!(!shape(ID, ID_NAME, &before), "another preface"); - let broken = format!("{LAST_TIME}10 times\nand more{LAST_TIME_END}{text}"); - assert!(!shape(ID, ID_NAME, &broken), "a note over two lines"); - } - - #[test] - fn only_the_releases_read_pass() { - assert!(read(vk::make_api_version(0, 1, 4, 363))); - assert!(!read(vk::make_api_version(0, 1, 4, 357))); - assert!(!read(vk::make_api_version(0, 1, 4, 364))); - assert!(!read(vk::make_api_version(0, 1, 5, 0))); - } -} diff --git a/crates/metal2vulkan-validation/src/candidate/runtime_case/raster_order_gap.rs b/crates/metal2vulkan-validation/src/candidate/runtime_case/raster_order_gap.rs deleted file mode 100644 index 8d38c58c4..000000000 --- a/crates/metal2vulkan-validation/src/candidate/runtime_case/raster_order_gap.rs +++ /dev/null @@ -1,280 +0,0 @@ -//! The third validation-layer gap a [`Messages`](super::Messages) sink lets pass: the layer's -//! synchronization validation does not read rasterization-order attachment access, and reports -//! an input attachment read that it orders as a hazard against an earlier draw's color write. -//! -//! A pipeline made with -//! `VK_PIPELINE_COLOR_BLEND_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_ACCESS_BIT_EXT` "forms a -//! framebuffer-local memory dependency for each fragment generated by draw commands for that -//! pipeline": its first synchronization scope "includes the -//! `VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT` pipeline stage executed by all previous -//! fragments (as defined by primitive order) in the corresponding framebuffer regions including -//! those generated by the same draw command", its second the fragment's -//! `VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT`, and its access scopes "all writes to color -//! attachments" and "all reads from input attachments" (the Framebuffer chapter, -//! `VkPipelineColorBlendStateCreateFlagBits`). The layer's synchronization code never reads that -//! flag: nothing in `layers/sync` names it, and `AccessState::DetectHazard` orders an input -//! attachment read only after a load op, "Input attachment is ordered against load op but not -//! against regular draws (requires subpass barrier)" (Vulkan-ValidationLayers v1.4.357, commit -//! e4786f7c, `layers/sync/sync_access_state.cpp` line 115; the same line in v1.4.363, commit -//! 2ea16de8; unchanged in main aea761f of 2026-10-18). So every fetch through an input attachment after an earlier draw wrote the pixel -//! reports a `READ_AFTER_WRITE`. -//! -//! The runtime fetches through input attachments where the device has -//! `rasterizationOrderColorAttachmentAccess` (`runtime/src/framebuffer_fetch.rs`), every pipeline -//! of such a pass made with that flag, and names each such pipeline [`NAME`] where its instance -//! reports messages (`runtime/src/pipeline/graphics.rs`, `RASTER_ORDER_PIPELINE`). [`shape`] -//! matches exactly that hazard, an input attachment read at the fragment shader after a color -//! attachment write by an earlier draw with no barrier between, and only when the pipeline it -//! names bears that name; [`read`] keys the layer releases whose source was read with the gap in -//! place. On any other release such a message fails, marked "re-read the input attachment -//! ordering in layer X.Y.Z", so a fixed or changed layer is checked again rather than trusted. - -use ash::vk; - -/// `messageIdNumber` of `SYNC-HAZARD-READ-AFTER-WRITE`, as the layer hashes its name. -const ID: i32 = -455515022; - -/// The id name of the hazard. -const ID_NAME: &str = "SYNC-HAZARD-READ-AFTER-WRITE"; - -/// What follows the draw command the layer reports at: a read of an image view by the fragment -/// shader (`sync_reporting.cpp`, `FormatErrorMessage`, with `ImageDescriptorError`'s initiator). -const HAZARD: &str = "(): READ_AFTER_WRITE hazard detected. Shader stage \ - VK_SHADER_STAGE_FRAGMENT_BIT reads VkImageView 0x"; - -/// What follows the image view: the earlier write's command. -const PRIOR: &str = ", which was previously written by "; - -/// What every draw command's name starts with. -const DRAW: &str = "vkCmdDraw"; - -/// The descriptor the view is read through (`PrepareCommonDescriptorMessage`). -const INPUT: &str = " (VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT)"; - -/// What names the bound pipeline, after the descriptor set. -const PIPELINE: &str = ", VkPipeline 0x"; - -/// What follows the pipeline. -const LAYOUT: &str = ", image layout "; - -/// The end of the message: the read and the earlier write, with no barrier between them. -const ACCESSES: &str = "No sufficient synchronization is present to ensure that a read \ - (VK_ACCESS_2_INPUT_ATTACHMENT_READ_BIT) at VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT does not \ - conflict with a prior write (VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT) at \ - VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT."; - -/// The note the layer puts before a message it reports for the last time -/// (`duplicate_message_limit`). -const LAST_TIME: &str = "(Warning - This VUID has now been reported "; - -/// The runtime's name for a pipeline made with the flag (`runtime/src/pipeline/graphics.rs`, -/// `RASTER_ORDER_PIPELINE`), which the layer prints after the pipeline's handle. -pub(super) const NAME: &str = - "metal2vulkan: a pipeline reading its input attachments in rasterization order"; - -/// The layer releases (`VkLayerProperties::specVersion` of `VK_LAYER_KHRONOS_validation`) whose -/// synchronization code was read with the gap in place: v1.4.357 (tag commit e4786f7c) and -/// v1.4.363 (tag commit 2ea16de8). In v1.4.363 the descriptor check moved -/// (`sync_command_buffer.cpp` line 589 to `sync_command.cpp` line 1335, -/// `ShaderAccessCommand::ValidateImageShaderAccess`) with its test unchanged: an input attachment -/// read is still found by `DetectAttachmentHazard` with `SyncOrdering::kRaster`, ordered by -/// `AccessState::DetectHazard` only after a load op (line 115), and no file of `layers/sync` -/// names the rasterization-order flags; the record-time message is made of the same text. What -/// v1.4.363 adds, the same hazard reported again at a submission's replay ("Shader stage ... in -/// vkCmdDraw... (from VkCommandBuffer ... submitted on the current VkQueue ...)"), is another -/// message, which [`shape`] does not take. -pub(super) const READ: &[u32] = &[ - vk::make_api_version(0, 1, 4, 357), - vk::make_api_version(0, 1, 4, 363), -]; - -/// Where the gap is, for the line each message let pass prints. -pub(super) const SOURCE: &str = "Vulkan-ValidationLayers v1.4.357 (e4786f7c) and v1.4.363 \ - (2ea16de8) layers/sync/sync_access_state.cpp:115, AccessState::DetectHazard: \"Input attachment is \ - ordered against load op but not against regular draws (requires subpass barrier).\"; \ - layers/sync never reads the rasterization-order attachment access flags"; - -/// Whether a message with this id, id name and text is the gap's: a `READ_AFTER_WRITE` found at -/// a draw, the fragment shader's read of an input attachment after a color attachment write by -/// an earlier draw, with no barrier between, through a pipeline the runtime named [`NAME`]. -pub(super) fn shape(id: i32, id_name: &str, text: &str) -> bool { - if id != ID || id_name != ID_NAME { - return false; - } - let Some(at) = text.find(HAZARD) else { - return false; - }; - // The draw command, alone on its line; before it, nothing or the layer's last-time note. - let line = text[..at].rfind('\n').map_or(0, |end| end + 1); - let command = &text[line..at]; - if !command.starts_with(DRAW) || !command.bytes().all(|b| b.is_ascii_alphanumeric()) { - return false; - } - if line != 0 && !text.starts_with(LAST_TIME) { - return false; - } - // The view, then the earlier write: a draw's (the same command's, "another" one). - let Some(rest) = after_handle(&text[at + HAZARD.len()..]) else { - return false; - }; - let Some(rest) = rest.strip_prefix(PRIOR) else { - return false; - }; - let rest = rest.strip_prefix("another ").unwrap_or(rest); - if !rest.starts_with(DRAW) { - return false; - } - let Some(input_at) = rest.find(INPUT) else { - return false; - }; - let rest = &rest[input_at + INPUT.len()..]; - let Some(pipeline_at) = rest.find(PIPELINE) else { - return false; - }; - let Some(rest) = after_handle(&rest[pipeline_at + PIPELINE.len()..]) else { - return false; - }; - let named = format!("[{NAME}]{LAYOUT}"); - rest.starts_with(&named) && rest.trim_end().ends_with(ACCESSES) -} - -/// What follows the hexadecimal digits a handle begins `text` with; `None` without any. -fn after_handle(text: &str) -> Option<&str> { - let end = text - .find(|c: char| !c.is_ascii_hexdigit()) - .unwrap_or(text.len()); - (end > 0).then(|| &text[end..]) -} - -/// Whether the layer release `version` is one whose source was read with the gap in place. -pub(super) fn read(version: u32) -> bool { - READ.contains(&version) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// The message as the lanes saw it on lavapipe (Mesa, LLVM 23.1.1) with the layer 1.4.357, - /// the runtime's name after the pipeline's handle (the layer prints an object's debug name - /// there). - fn seen() -> String { - format!( - "vkCmdDraw(): READ_AFTER_WRITE hazard detected. Shader stage \ - VK_SHADER_STAGE_FRAGMENT_BIT reads VkImageView 0x3d000000003d, which was previously \ - written by another vkCmdDraw command. \nThe image is referenced by descriptor \ - binding 1 (VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) from descriptor set 0 \ - (VkDescriptorSet 0x0), VkPipeline 0x370000000037[{NAME}], image layout \ - VK_IMAGE_LAYOUT_GENERAL.\nNo sufficient synchronization is present to ensure that a \ - read (VK_ACCESS_2_INPUT_ATTACHMENT_READ_BIT) at \ - VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT does not conflict with a prior write \ - (VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT) at \ - VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT." - ) - } - - #[test] - fn the_layer_s_report_of_a_named_pipeline_s_input_attachment_read_is_the_gap() { - assert!(shape(ID, ID_NAME, &seen())); - // Reported for the last time, after the layer's note. - let last = format!( - "{LAST_TIME}10 times, which is the duplicate_message_limit value, this will be the \ - last time reporting it).\n{}", - seen() - ); - assert!(shape(ID, ID_NAME, &last)); - // Another draw command, at either end. - let indexed = seen().replacen("vkCmdDraw(): ", "vkCmdDrawIndexed(): ", 1); - let indexed = indexed.replace("another vkCmdDraw command", "vkCmdDraw"); - assert!(shape(ID, ID_NAME, &indexed)); - // Another binding, or an array element of one. - let element = seen().replace( - "binding 1 (VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT)", - "binding 2 (VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT), array element 1", - ); - assert!(shape(ID, ID_NAME, &element)); - } - - #[test] - fn a_pipeline_without_the_name_is_not_the_gap() { - let text = seen(); - let unnamed = text.replace(&format!("[{NAME}]"), ""); - assert!(!shape(ID, ID_NAME, &unnamed), "unnamed"); - let other = text.replace(NAME, "another pipeline"); - assert!(!shape(ID, ID_NAME, &other), "another name"); - let wider = text.replace(NAME, &format!("{NAME} and more")); - assert!(!shape(ID, ID_NAME, &wider), "a wider name"); - // The name on the view, the pipeline unnamed. - let elsewhere = unnamed.replace( - "VkImageView 0x3d000000003d", - &format!("VkImageView 0x3d000000003d[{NAME}]"), - ); - assert!(!shape(ID, ID_NAME, &elsewhere), "the name on the view"); - } - - #[test] - fn other_hazards_are_not_the_gap() { - let text = seen(); - assert!(!shape(1544472022, "SYNC-HAZARD-WRITE-AFTER-WRITE", &text)); - assert!(!shape(ID, "SYNC-HAZARD-WRITE-AFTER-READ", &text)); - assert!(!shape(0, ID_NAME, &text)); - // Another descriptor: a sampled image or a storage image. - for kind in [ - "VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE", - "VK_DESCRIPTOR_TYPE_STORAGE_IMAGE", - "VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER", - ] { - let other = text.replace("VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT", kind); - assert!(!shape(ID, ID_NAME, &other), "{kind}"); - } - // An earlier write by no draw: a load op, a store op, a clear, a copy. - for prior in [ - "at the beginning of subpass 0 (vkCmdBeginRenderPass) by the attachment loadOp", - "at the end of the render pass instance (vkCmdEndRenderPass) by the attachment storeOp", - "by vkCmdClearAttachments", - "by vkCmdCopyBufferToImage", - ] { - let other = text.replace("by another vkCmdDraw command", prior); - assert!(!shape(ID, ID_NAME, &other), "{prior}"); - } - // Another read or write, or a barrier that orders part of them. - let storage = text.replace( - "a prior write (VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT) at \ - VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT", - "a prior write (VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT) at \ - VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT", - ); - assert!(!shape(ID, ID_NAME, &storage), "a storage write"); - let sampled = text.replace( - "a read (VK_ACCESS_2_INPUT_ATTACHMENT_READ_BIT)", - "a read (VK_ACCESS_2_SHADER_SAMPLED_READ_BIT)", - ); - assert!(!shape(ID, ID_NAME, &sampled), "a sampled read"); - let at = text.find("No sufficient").unwrap(); - let partial = format!( - "{}The current synchronization allows COLOR_ATTACHMENT_WRITE accesses at \ - COLOR_ATTACHMENT_OUTPUT, but to prevent this hazard, it must allow \ - VK_ACCESS_2_INPUT_ATTACHMENT_READ_BIT accesses at \ - VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT.", - &text[..at] - ); - assert!(!shape(ID, ID_NAME, &partial), "a partial barrier"); - // Found at a dispatch, a copy, or the shader's read of another stage. - let dispatch = text.replacen("vkCmdDraw(): ", "vkCmdDispatch(): ", 1); - assert!(!shape(ID, ID_NAME, &dispatch), "a dispatch"); - let vertex = text.replace("VK_SHADER_STAGE_FRAGMENT_BIT", "VK_SHADER_STAGE_VERTEX_BIT"); - assert!(!shape(ID, ID_NAME, &vertex), "the vertex stage"); - // Anything else before the command's line. - let before = format!("Something else.\n{text}"); - assert!(!shape(ID, ID_NAME, &before), "another preface"); - } - - #[test] - fn only_the_releases_read_pass() { - assert!(read(vk::make_api_version(0, 1, 4, 357))); - assert!(read(vk::make_api_version(0, 1, 4, 363))); - assert!(!read(vk::make_api_version(0, 1, 4, 356))); - assert!(!read(vk::make_api_version(0, 1, 4, 358))); - assert!(!read(vk::make_api_version(0, 1, 5, 0))); - } -} diff --git a/crates/metal2vulkan-validation/src/candidate/runtime_case/render.rs b/crates/metal2vulkan-validation/src/candidate/runtime_case/render.rs deleted file mode 100644 index 49dd1e53a..000000000 --- a/crates/metal2vulkan-validation/src/candidate/runtime_case/render.rs +++ /dev/null @@ -1,1369 +0,0 @@ -//! A render case's draw through the Metal-like runtime, as the Metal oracle draws it -//! (`metal::platform`): the one copy the runtime lane's render census (`runtime_lane::renders`) and -//! the engine executor's runtime path (`runtime_run`) share. -//! -//! A library of the case's AIR and one of its generated companion's, each stage's function -//! specialized with its constant values, the case's own function linking the functions of its -//! linked libraries as the oracle links them, a render pipeline state of the oracle's descriptor -//! (`graphics::pipeline_descriptor`), its color targets and its separate `Depth32Float` and -//! `Stencil8` attachments loaded and stored, its depth/stencil state, references, winding and cull -//! mode, its vertex buffers, buffers, textures and sampler states bound at their slots, a patch -//! draw's factor buffer as both executors bind it (`executor_contract::tessellation`), its one -//! draw, and its output read back after the command buffer completed. A multisampled pass's -//! attachments and textures are filled sample by sample and its output read sample by sample, never -//! resolved, in the same command buffer as the oracle does (`candidate::runtime_samples`), a -//! uniform stencil cleared to its value. A case without attachments draws into the oracle's -//! one-pixel pass. -//! -//! A vertex buffer that is an out-of-bounds target (the buffer feeding an attribute the draw -//! fetches past: a vertex input's, or a patch draw's control point's or patch input's, which its -//! post-tessellation vertex function fetches), and an index buffer that is one (the draw's -//! indices run past it), lie in a -//! placement heap of its own between guards, as a kernel's buffer target does -//! (`runtime_case::guarded_buffer`), and what the draw changed there is counted once it completed -//! ([`CommittedRender::guard_counts`]). The draw is encoded before it is committed -//! ([`encoded_render`]), so the runtime path decides how the draw contains its targets from what it -//! executed before anything runs. -//! -//! A fragment case's explicit imageblock is drawn as the oracle draws it, in one pass with the -//! case's draw (`imageblock.rs`): its pass's imageblock sample length is the case pipeline's and -//! its tile 16x16, the generated initializer draws before the case and the generated resolver after -//! it where the output is an imageblock member; the case's executions are its own draw's. -//! -//! A case's rasterization-rate map is made as the oracle makes it: the pass's through -//! `new_rasterization_rate_map`, its viewport the map's screen, and a buffer of the case's own -//! stage that holds a map's parameter data through `rate_map_buffer`. -//! -//! A stage's argument buffers are made as a kernel's are (`runtime_case::bound_buffers`): each -//! member as the oracle makes it, a texture's usage its role united with the declared access of the -//! case's AIR member at its field (`runtime_case::argument_texture_usage`), written into its owner -//! at its field as Metal's argument encoder writes it, and the buffers and textures made resident -//! for reading and writing in the vertex and fragment stages (`use_resources`), as the oracle's -//! `useResource:usage:stages:` does. A stage's visible-function tables are made by the render -//! pipeline state for that stage (`newVisibleFunctionTableWithDescriptor:stage:`), each entry the -//! handle the state gives the function it holds for that stage -//! (`functionHandleWithFunction:stage:`), and bound at their index of that stage, as the oracle -//! makes and binds them; the bytes the runtime wrote to each are keyed by stage and index -//! ([`EncodedRender::tables`]). A pipeline state an argument buffer holds is its token's template's -//! state, made with `support_indirect_command_buffers` (`RenderInputs::templates`), its owner -//! holding its `gpu_resource_id` at the field as Metal's argument encoder writes it. A stage's -//! indirect command buffers are made, encoded by the host, made resident, read back and executed as -//! a kernel's are (the `commands` module): the commands each executes run after the draw, each in a -//! command buffer of its own ([`EncodedRender::executions`]). -//! -//! What a later runtime step adds (a layered multisampled target) is refused as a -//! [`CaseError::Case`] naming "a later runtime step"; the executor's route sends no such case -//! here (`runtime_run::render_prerequisites`). - -use super::commands::{encode_host_commands, encode_twin_copies, encoded_execution, CaseCommands}; -use super::imageblock::Helpers; -use super::{ - argument_samplers, argument_texture_usage, argument_textures, buffer_with, filled_texture, - guard_count, guarded_buffer, linked_functions, member_words, pipeline_states, rate_map_buffer, - read_buffer, read_texture, tables_of, CaseError, LinkedSet, TemplateState, -}; -use crate::air::reflect::FragmentImageblock; -use crate::air_library::AirLibrary; -use crate::candidate::engine::argument_buffers::owner_bytes; -use crate::candidate::engine::graphics::{ - pipeline_descriptor, Assembly, ColorTarget, RenderCase, RenderFunction, RenderOutput, -}; -use crate::candidate::engine::guards::{declared_reach, GuardCount}; -use crate::candidate::engine::resources::{pixel_format, sampler_descriptor, texture_type}; -use crate::candidate::engine::tables::TableBuffers; -use crate::candidate::engine::LinkedModule; -use crate::candidate::runtime_samples::{self, SampleFill}; -use crate::case::indirect_commands::metal_primitive_type; -use crate::case::out_of_bounds::OutOfBoundsResource; -use crate::case::TextureFormat as CaseFormat; -use crate::case::{AuthoredCase, Stage, TextureType}; -use crate::check::interface::AirInterface; -use crate::executor_contract::multisample::{sample_read, uniform_stencil, SampleRead}; -use crate::executor_contract::tessellation as patches; -use crate::literal::{select_tightly_packed_2d, texture_layout, LiteralDepthStencil}; -use metal2vulkan::bind::DrawCall; -use metal2vulkan::metal::{IndexType, PixelFormat, RenderStages, ResourceUsage, TextureUsage}; -use metal2vulkan::pipeline::RenderPipelineDescriptor; -use metal2vulkan::pipeline::Stage as ShaderStage; -use metal2vulkan_runtime::{ - Buffer, CommandBuffer, Device, Execution, Function, LoadAction, PipelineOptions, Region, - RenderCommandEncoder, RenderPassDescriptor, RenderPipelineState, ResourceOptions, ResourceRef, - SamplerState, StoreAction, Texture, TextureDescriptor, Viewport, VisibleFunctionTable, -}; -use std::collections::BTreeMap; - -mod mesh; -pub use mesh::{encoded_mesh, mesh_pipeline_state, MeshInputs}; - -/// What a render case's draw needs: the authored case, its render mapping, its AIR bitcode and its -/// generated companion's, the libraries its own function links (`engine::linked_modules`), -/// the usage the Metal oracle gives each of its textures (`runtime_case::texture_usage`), its own -/// function's AIR interface, whose argument-buffer members give each argument-buffer texture's -/// usage (`runtime_case::argument_texture_usage`), and a fragment case's explicit imageblock's -/// master, the checked reflection's (`CheckedShader::reflection`), whose members the imageblock -/// helpers write and read; and the state of each pipeline template its argument buffers name, by -/// token (`runtime_run::template_states`). -pub struct RenderInputs<'a> { - pub case: &'a AuthoredCase, - pub render: &'a RenderCase, - pub bitcode: &'a [u8], - pub companion: Option<&'a [u8]>, - pub linked: &'a [LinkedModule], - pub texture_usage: &'a BTreeMap, - pub interface: &'a AirInterface, - pub imageblock: Option<&'a FragmentImageblock>, - pub templates: &'a BTreeMap, -} - -/// Work a multisampled case's command buffer runs before its pass, as the Metal oracle's does: a -/// texture's fill, or a stencil attachment cleared to its one value by a pass of its own. -enum Prep { - Fill(SampleFill), - ClearStencil(Texture, u32), -} - -impl Prep { - fn encode(&self, command_buffer: &CommandBuffer) -> Result<(), CaseError> { - match self { - Prep::Fill(fill) => fill.encode(command_buffer), - Prep::ClearStencil(texture, value) => { - let mut pass = RenderPassDescriptor::new(); - let attachment = &mut pass.stencil_attachment; - attachment.texture = Some(texture.clone()); - attachment.load_action = LoadAction::Clear; - attachment.clear_stencil = *value; - attachment.store_action = StoreAction::Store; - command_buffer - .render_command_encoder(&pass) - .map_err(CaseError::runtime( - "the stencil clear's render_command_encoder", - ))? - .end_encoding() - .map_err(CaseError::runtime("the stencil clear's end_encoding")) - } - } - } -} - -/// A 2D multisample texture of `pixel_format`, `dimensions` and `samples` on `device`, as the -/// Metal oracle makes a multisampled attachment (`metal::platform::attachments`): `Private`, a -/// render target the per-sample readback reads (`ShaderRead`), through a view of another format -/// for a color one (`PixelFormatView`). -fn multisampled( - device: &Device, - pixel_format: PixelFormat, - [width, height]: [u32; 2], - samples: u32, -) -> Result { - let mut descriptor = TextureDescriptor::default(); - descriptor.texture_type = texture_type(TextureType::D2Multisample); - descriptor.pixel_format = pixel_format; - descriptor.width = width.into(); - descriptor.height = height.into(); - descriptor.sample_count = samples.into(); - descriptor.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; - if !matches!( - pixel_format, - PixelFormat::Depth32Float | PixelFormat::Stencil8 - ) { - descriptor.usage |= TextureUsage::PIXEL_FORMAT_VIEW; - } - descriptor.resource_options = ResourceOptions::private(); - device - .new_texture(&descriptor) - .map_err(CaseError::runtime(format!( - "a multisampled {pixel_format:?} attachment: new_texture" - ))) -} - -/// A color target of `target` on `device` holding its bytes: 2D, or a 2D array of one slice in a -/// layered pass, `Shared`, `RenderTarget` usage (the Metal oracle's, -/// `metal::platform::attachments`). A multisampled one is [`multisampled`], filled sample by -/// sample by its fill in `prep`. -fn target_with( - device: &Device, - target: &ColorTarget, - layered: bool, - prep: &mut Vec, -) -> Result { - if target.samples != 1 { - if layered { - return Err("a layered multisampled target, a later runtime step".into()); - } - let texture = multisampled( - device, - pixel_format(target.format), - target.dimensions, - target.samples, - )?; - let [width, height] = target.dimensions; - let layout = texture_layout( - TextureType::D2Multisample, - [width, height, 1], - target.samples, - )?; - let fill = SampleFill::new(device, &texture, target.format, layout, &target.bytes)?; - prep.push(Prep::Fill(fill)); - return Ok(texture); - } - let [width, height] = target.dimensions; - let mut descriptor = TextureDescriptor::default(); - descriptor.texture_type = texture_type(if layered { - TextureType::D2Array - } else { - TextureType::D2 - }); - descriptor.pixel_format = pixel_format(target.format); - descriptor.width = width.into(); - descriptor.height = height.into(); - descriptor.usage = TextureUsage::RENDER_TARGET; - descriptor.resource_options = ResourceOptions::shared(); - let texture = device - .new_texture(&descriptor) - .map_err(CaseError::runtime("a color target: new_texture"))?; - let row = u64::from(width) * target.format.bytes_per_pixel() as u64; - texture - .replace_region( - Region::new_2d(0, 0, width.into(), height.into()), - 0, - 0, - &target.bytes, - row, - row * u64::from(height), - ) - .map_err(CaseError::runtime("a color target: replace_region"))?; - Ok(texture) -} - -/// The depth and stencil attachments of `literal` on `device`, each authored aspect its own -/// texture holding its bytes: `Depth32Float` and `Stencil8`, 2D, `Shared`, `RenderTarget` usage -/// (the Metal oracle's separate attachments, `metal::platform::attachments`). Multisampled ones -/// are [`multisampled`]: the depth filled sample by sample, the stencil, whose samples hold one -/// value, cleared to it, each by its work in `prep`. -fn depth_stencil_with( - device: &Device, - literal: &LiteralDepthStencil, - prep: &mut Vec, -) -> Result<(Option, Option), CaseError> { - let [width, height] = literal.dimensions; - if literal.samples != 1 { - let samples = literal.samples; - let depth = literal - .depth - .as_deref() - .map(|bytes| { - let texture = multisampled( - device, - PixelFormat::Depth32Float, - literal.dimensions, - samples, - )?; - let layout = - texture_layout(TextureType::D2Multisample, [width, height, 1], samples)?; - let fill = - SampleFill::new(device, &texture, CaseFormat::Depth32Float, layout, bytes)?; - prep.push(Prep::Fill(fill)); - Ok::(texture) - }) - .transpose()?; - let stencil = literal - .stencil - .as_deref() - .map(|bytes| { - let value = uniform_stencil(bytes)?; - let texture = - multisampled(device, PixelFormat::Stencil8, literal.dimensions, samples)?; - prep.push(Prep::ClearStencil(texture.clone(), value.into())); - Ok::(texture) - }) - .transpose()?; - return Ok((depth, stencil)); - } - let aspect = |pixel_format: PixelFormat, bytes: &[u8], texel: u64| { - let mut descriptor = TextureDescriptor::default(); - descriptor.pixel_format = pixel_format; - descriptor.width = width.into(); - descriptor.height = height.into(); - descriptor.usage = TextureUsage::RENDER_TARGET; - descriptor.resource_options = ResourceOptions::shared(); - let texture = device - .new_texture(&descriptor) - .map_err(CaseError::runtime(format!( - "a {pixel_format:?} attachment: new_texture" - )))?; - let row = u64::from(width) * texel; - texture - .replace_region( - Region::new_2d(0, 0, width.into(), height.into()), - 0, - 0, - bytes, - row, - row * u64::from(height), - ) - .map_err(CaseError::runtime(format!( - "a {pixel_format:?} attachment: replace_region" - )))?; - Ok::(texture) - }; - let depth = literal - .depth - .as_deref() - .map(|bytes| aspect(PixelFormat::Depth32Float, bytes, 4)) - .transpose()?; - let stencil = literal - .stencil - .as_deref() - .map(|bytes| aspect(PixelFormat::Stencil8, bytes, 1)) - .transpose()?; - Ok((depth, stencil)) -} - -/// A multisampled pass's render-target, depth or stencil output, as the Metal oracle reads it: the -/// attachment, how it is read sample by sample, its extent, and the region selected of every -/// sample, never resolved. `None` for a pass of one sample, whose outputs are copied, and for any -/// other output. -type SampleOutput<'a> = (&'a Texture, SampleRead, [u32; 2], [u32; 2], [u32; 2]); - -fn multisampled_output<'a>( - inputs: &RenderInputs<'_>, - targets: &'a BTreeMap, - depth: Option<&'a Texture>, - stencil: Option<&'a Texture>, -) -> Result>, CaseError> { - if inputs.case.raster_samples() == 1 { - return Ok(None); - } - let render = inputs.render; - let depth_stencil = || { - render - .depth_stencil - .as_ref() - .ok_or("the output's depth/stencil is not declared") - }; - let attached = |texture: Option<&'a Texture>, what: &str| { - texture.ok_or_else(|| format!("the output's {what} is not attached")) - }; - Ok(Some(match render.output { - RenderOutput::RenderTarget { - index, - origin, - dimensions, - } => { - let target = render - .color_targets - .get(&index) - .ok_or_else(|| format!("the output target {index} is not declared"))?; - ( - attached(targets.get(&index), "target")?, - sample_read(target.format)?, - target.dimensions, - origin, - dimensions, - ) - } - RenderOutput::Depth { origin, dimensions } => ( - attached(depth, "depth")?, - SampleRead::Depth, - depth_stencil()?.dimensions, - origin, - dimensions, - ), - RenderOutput::Stencil { origin, dimensions } => ( - attached(stencil, "stencil")?, - SampleRead::Stencil, - depth_stencil()?.dimensions, - origin, - dimensions, - ), - _ => return Ok(None), - })) -} - -/// `length` bytes of each of `dimensions` texels from `origin` of `texture`'s level 0, rows in -/// order. -fn texels_of( - texture: &Texture, - origin: [u32; 2], - dimensions: [u32; 2], - texel: u64, -) -> Result, CaseError> { - let [width, height] = dimensions.map(u64::from); - let mut bytes = vec![0u8; (width * height * texel) as usize]; - texture - .get_bytes( - &mut bytes, - width * texel, - width * height * texel, - Region::new_2d(origin[0].into(), origin[1].into(), width, height), - 0, - 0, - ) - .map_err(CaseError::runtime("get_bytes"))?; - Ok(bytes) -} - -/// The functions of `inputs`' pipeline on `device`, vertex then fragment: its own from its -/// library, linking the functions of its linked libraries (each made with the own function's -/// constant values, [`LinkedSet`]); its companion's from the companion's. -fn functions( - device: &Device, - inputs: &RenderInputs<'_>, -) -> Result<(Function, Option, LinkedSet), CaseError> { - let library = |bitcode: &[u8]| { - device - .new_library_with_air(bitcode) - .map_err(CaseError::runtime("new_library_with_air")) - }; - let own = library(inputs.bitcode)?; - let companion = inputs.companion.map(library).transpose()?; - let render = inputs.render; - let generated = render.companion_stage(); - let function = |stage: ShaderStage, function: &RenderFunction| { - let library = match generated { - Some(generated) if generated == stage => companion - .as_ref() - .ok_or("a companion without its library")?, - _ => &own, - }; - library - .new_function_with_name_constant_values(&function.entry, &function.constants) - .map_err(CaseError::runtime(format!( - "function {}: new_function_with_name_constant_values", - function.entry - ))) - }; - let vertex = function(ShaderStage::Vertex, &render.vertex)?; - let fragment = render - .fragment - .as_ref() - .map(|fragment| function(ShaderStage::Fragment, fragment)) - .transpose()?; - // The case's own function is the stage the companion did not generate. - let own_stage = match (generated, &render.fragment) { - (Some(ShaderStage::Vertex), Some(fragment)) => fragment, - _ => &render.vertex, - }; - let linked = linked_functions(device, inputs.linked, &own_stage.constants)?; - Ok((vertex, fragment, linked)) -} - -/// The render pipeline descriptor of `inputs`, its functions made on `device`: the oracle's -/// descriptor of its functions, the case's own one linking its linked functions. -pub fn render_pipeline_descriptor( - device: &Device, - inputs: &RenderInputs<'_>, -) -> Result { - Ok(descriptor_and_links(device, inputs)?.0) -} - -/// [`render_pipeline_descriptor`], with the functions its own function links, which its -/// visible-function tables' entries name ([`LinkedSet`]). -fn descriptor_and_links( - device: &Device, - inputs: &RenderInputs<'_>, -) -> Result<(RenderPipelineDescriptor, LinkedSet), CaseError> { - let (vertex, fragment, linked) = functions(device, inputs)?; - let generated = inputs.render.companion_stage(); - let descriptor_of = |stage: ShaderStage, function: &Function| { - let descriptor = function.function_descriptor(); - if generated == Some(stage) { - descriptor - } else { - descriptor.with_linked(linked.functions.clone()) - } - }; - let descriptor = pipeline_descriptor( - inputs.render, - descriptor_of(ShaderStage::Vertex, &vertex), - fragment - .as_ref() - .map(|fragment| descriptor_of(ShaderStage::Fragment, fragment)), - ) - .map_err(|error| format!("the descriptor: {error}"))?; - Ok((descriptor, linked)) -} - -/// The render pipeline state of `inputs` on `device`, of [`render_pipeline_descriptor`]'s -/// descriptor under the default pipeline options. -pub fn render_pipeline_state( - device: &Device, - inputs: &RenderInputs<'_>, -) -> Result { - let descriptor = render_pipeline_descriptor(device, inputs)?; - device - .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) - .map_err(CaseError::runtime("new_render_pipeline_state")) -} - -/// What one stage of a case binds, made on a device: its buffers and textures by Metal slot, the -/// members of its argument buffers by owner slot and field offset, and its visible-function tables -/// by Metal buffer index. -#[derive(Default)] -struct StageBound { - buffers: BTreeMap, - textures: BTreeMap, - argument_buffers: BTreeMap<(u32, u32), Buffer>, - argument_textures: BTreeMap<(u32, u32), Texture>, - argument_samplers: BTreeMap<(u32, u32), SamplerState>, - commands: CaseCommands, - tables: BTreeMap, -} - -impl StageBound { - /// The word each argument-buffer member's owner holds at its field, as Metal's argument - /// encoder writes it (`runtime_case::bound_buffers`): a buffer's `gpu_address`, a texture's, - /// sampler state's, command buffer's or pipeline state's `gpu_resource_id`. - fn member_words(&self) -> Result, CaseError> { - let buffers = self - .argument_buffers - .iter() - .map(|(&key, buffer)| (key, buffer.gpu_address().0)); - let textures = self - .argument_textures - .iter() - .map(|(&key, texture)| (key, texture.gpu_resource_id().0)); - let samplers = self - .argument_samplers - .iter() - .map(|(&key, sampler)| (key, sampler.gpu_resource_id().0)); - member_words( - buffers - .chain(textures) - .chain(samplers) - .chain(self.commands.words()), - ) - } - - /// The members the draw makes resident: each argument-buffer buffer, texture and command - /// buffer (a sampler or pipeline state is no resource). - fn members(&self) -> impl Iterator> { - self.argument_buffers - .values() - .map(Buffer::as_resource) - .chain(self.argument_textures.values().map(Texture::as_resource)) - .chain(self.commands.resources()) - } -} - -/// What each stage of one pipeline makes its resources with: the authored case, the usage the Metal -/// oracle gives each of the case's own textures, its own function's AIR interface, the state of -/// each pipeline template its argument buffers name, and the pipeline state and linked functions -/// that make each stage's visible-function tables. -struct StageContext<'a> { - case: &'a AuthoredCase, - texture_usage: &'a BTreeMap, - interface: &'a AirInterface, - templates: &'a BTreeMap, - pipeline: &'a RenderPipelineState, - linked: &'a LinkedSet, -} - -/// One stage's resources made on a device ([`StageContext::bound`]): what it binds, its sampler -/// states by slot, and the bytes the runtime wrote to its visible-function tables. -struct MadeStage { - bound: StageBound, - samplers: Vec<(u32, SamplerState)>, - words: TableBuffers, -} - -impl StageContext<'_> { - /// `function`'s resources at `stage`, made on `device` as the Metal oracle makes them: its - /// argument buffers' members, its command buffers and the pipeline states its argument buffers - /// hold, its visible-function tables, its buffers holding their members' words, the host's - /// commands encoded, its textures and its sampler states. The fills its textures need join - /// `prep`. - fn bound( - &self, - device: &Device, - stage: ShaderStage, - function: &RenderFunction, - prep: &mut Vec, - ) -> Result { - let resources = &function.resources; - let mut stage_bound = StageBound::default(); - let mut fills = Vec::new(); - // Its argument buffers' members, as a kernel's are made (`runtime_case::CaseResources`): - // an argument-buffer texture's usage is its role united with the declared access of the - // case's own function's AIR member at its field. - let argument_usage = if Some(stage) == case_stage(self.case) { - argument_texture_usage(&resources.argument_buffer_textures, self.interface)? - } else { - BTreeMap::new() - }; - // A command buffer's field holds the command buffer, not the record storage the mapped - // case states for the executor. - stage_bound.argument_buffers = resources - .argument_buffer_buffers - .iter() - .filter(|(key, _)| !resources.command_buffers.contains_key(key)) - .map(|(&key, bytes)| Ok((key, buffer_with(device, bytes)?))) - .collect::>()?; - stage_bound.argument_textures = argument_textures( - device, - &resources.argument_buffer_textures, - &argument_usage, - &mut fills, - )?; - stage_bound.argument_samplers = - argument_samplers(device, &resources.argument_buffer_samplers)?; - stage_bound.commands = CaseCommands::of(device, &resources.command_buffers)?; - stage_bound.commands.states = pipeline_states(&resources.objects, self.templates)?; - let fields = stage_bound.member_words()?; - // Its visible-function tables, made by the pipeline state for the stage, as the oracle - // makes them (`newVisibleFunctionTableWithDescriptor:stage:`). - let made = tables_of( - (stage, &resources.function_tables), - self.linked, - |descriptor| { - self.pipeline - .new_visible_function_table(descriptor, render_stage(stage)) - }, - |function| self.pipeline.function_handle(function, render_stage(stage)), - )?; - stage_bound.tables = made.tables; - for &index in resources.buffers.keys() { - // A buffer of the case's own stage that holds a rasterization-rate map's parameter - // data is made as the oracle makes it (`rate_map_buffer`). - let map = (Some(stage) == case_stage(self.case)) - .then(|| { - self.case - .buffers - .iter() - .find(|buffer| buffer.binding == index) - }) - .flatten() - .and_then(|buffer| buffer.rasterization_rate_map.as_ref()); - // An argument buffer's owner holds each member's word at its field. - let buffer = match map { - Some(map) => rate_map_buffer(device, map)?, - None => buffer_with(device, &owner_bytes(&resources.buffers, index, &fields)?)?, - }; - stage_bound.buffers.insert(index, buffer); - } - // The host's commands, before the draw runs. - encode_host_commands( - &resources.command_buffers, - &stage_bound.commands, - &stage_bound.buffers, - self.templates, - )?; - for (&slot, literal) in &resources.textures { - let usage = self - .texture_usage - .get(&slot) - .copied() - .ok_or_else(|| format!("texture {slot} has no usage"))?; - let texture = filled_texture(device, literal, usage, &mut fills)?; - stage_bound.textures.insert(slot, texture); - } - prep.extend(fills.into_iter().map(Prep::Fill)); - let samplers = resources - .samplers - .iter() - .map(|(&slot, sampler)| { - let state = device - .new_sampler_state(&sampler_descriptor(sampler)) - .map_err(CaseError::runtime("new_sampler_state"))?; - Ok((slot, state)) - }) - .collect::>()?; - Ok(MadeStage { - bound: stage_bound, - samplers, - words: made.words, - }) - } -} - -/// Bind each stage's buffers, textures, visible-function tables and sampler states at their -/// indices through that stage's setters (`setVertex*`, `setFragment*`, `setObject*`, `setMesh*`). -/// Metal has no object or mesh setter for a visible-function table, so neither stage binds one. -fn bind_stages( - encoder: &mut RenderCommandEncoder, - bound: &BTreeMap, - samplers: &[(ShaderStage, u32, SamplerState)], -) -> Result<(), CaseError> { - for (&stage, stage_bound) in bound { - for (&index, buffer) in &stage_bound.buffers { - let buffer = Some(buffer); - match stage { - ShaderStage::Fragment => encoder.set_fragment_buffer(buffer, 0, index), - ShaderStage::Object => encoder.set_object_buffer(buffer, 0, index), - ShaderStage::Mesh => encoder.set_mesh_buffer(buffer, 0, index), - _ => encoder.set_vertex_buffer(buffer, 0, index), - } - .map_err(CaseError::runtime("set_*_buffer"))?; - } - for (&index, texture) in &stage_bound.textures { - let texture = Some(texture); - match stage { - ShaderStage::Fragment => encoder.set_fragment_texture(texture, index), - ShaderStage::Object => encoder.set_object_texture(texture, index), - ShaderStage::Mesh => encoder.set_mesh_texture(texture, index), - _ => encoder.set_vertex_texture(texture, index), - } - .map_err(CaseError::runtime("set_*_texture"))?; - } - for (&index, table) in &stage_bound.tables { - match stage { - ShaderStage::Fragment => { - encoder.set_fragment_visible_function_table(Some(table), index) - } - ShaderStage::Object | ShaderStage::Mesh => { - return Err(format!( - "{stage:?} visible-function table {index}: no object or mesh setter binds one" - ) - .into()) - } - _ => encoder.set_vertex_visible_function_table(Some(table), index), - } - .map_err(CaseError::runtime("set_*_visible_function_table"))?; - } - } - for &(stage, slot, ref state) in samplers { - let state = Some(state); - match stage { - ShaderStage::Fragment => encoder.set_fragment_sampler_state(state, slot), - ShaderStage::Object => encoder.set_object_sampler_state(state, slot), - ShaderStage::Mesh => encoder.set_mesh_sampler_state(state, slot), - _ => encoder.set_vertex_sampler_state(state, slot), - } - .map_err(CaseError::runtime("set_*_sampler_state"))?; - } - Ok(()) -} - -/// The render stage of `stage`'s function, whose tables the pipeline state makes and whose handles -/// it gives. -fn render_stage(stage: ShaderStage) -> RenderStages { - match stage { - ShaderStage::Fragment => RenderStages::FRAGMENT, - ShaderStage::Object => RenderStages::OBJECT, - ShaderStage::Mesh => RenderStages::MESH, - _ => RenderStages::VERTEX, - } -} - -/// What a render case's draw reads its output from, and the guards around its out-of-bounds -/// targets, once its command buffer completed. -struct Drawn { - targets: BTreeMap, - depth: Option, - stencil: Option, - bound: BTreeMap, - /// A multisampled output's readback, with its extent, origin, dimensions and texel bytes. - readback: Option<(runtime_samples::SampleReadback, [[u32; 2]; 3], usize)>, - /// The vertex or index buffer of each out-of-bounds target placed between guards, by target. - guarded: BTreeMap, - /// A fragment case's imageblock helpers, whose resolver's buffer holds an imageblock output. - imageblock: Option, -} - -/// A render case's draw encoded on its device ([`encoded_render`]), not yet committed: its -/// command buffer, what the draw executed (the command buffer's executions after its -/// preparation's and before its readback's), and the bytes the runtime wrote to each -/// visible-function table it binds, by stage and Metal buffer index, as the executor's artifact -/// records a table's buffer (`tables::TableBuffers`). -pub struct EncodedRender { - pub command_buffer: CommandBuffer, - pub executions: Vec, - pub tables: TableBuffers, - drawn: Drawn, -} - -/// A render case's draw committed on its device ([`EncodedRender::commit`]): its command buffer, -/// what the draw executed, its tables' bytes, and what its output is read from once the command -/// buffer completed ([`CommittedRender::output`]). -pub struct CommittedRender { - pub command_buffer: CommandBuffer, - pub executions: Vec, - pub tables: TableBuffers, - drawn: Drawn, -} - -/// Encode `inputs`' draw on `device`: its pipeline state, attachments, vertex and index buffers (a -/// target's between guards), resources holding their bytes, argument buffers holding their -/// members' words and tables holding their entries' handles, one command buffer with the fills its -/// multisampled textures and attachments need, one render encoder with the case's state and its -/// one draw (between a fragment imageblock's helpers' draws), ended, and a multisampled output's -/// readback. -pub fn encoded_render( - device: &Device, - inputs: &RenderInputs<'_>, -) -> Result { - let render = inputs.render; - let (descriptor, linked) = descriptor_and_links(device, inputs)?; - let pipeline = device - .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) - .map_err(CaseError::runtime("new_render_pipeline_state"))?; - // A fragment imageblock's initializer and resolver, as the oracle draws them. - let imageblock = match (&render.imageblock, inputs.imageblock) { - (None, _) => None, - (Some(cells), Some(master)) => { - let resolves = matches!(render.output, RenderOutput::Imageblock { .. }); - Some(Helpers::new(device, &descriptor, master, cells, resolves)?) - } - (Some(_), None) => return Err("an imageblock without its reflected master".into()), - }; - let layered = render.render_target_array_length > 0; - let mut prep = Vec::new(); - let targets = render - .color_targets - .iter() - .map(|(&index, target)| Ok((index, target_with(device, target, layered, &mut prep)?))) - .collect::, CaseError>>()?; - let (depth, stencil) = match &render.depth_stencil { - Some(literal) => depth_stencil_with(device, literal, &mut prep)?, - None => (None, None), - }; - let mut pass = RenderPassDescriptor::new(); - for (&index, texture) in &targets { - let attachment = &mut pass.color_attachments[index as usize]; - attachment.texture = Some(texture.clone()); - attachment.load_action = LoadAction::Load; - attachment.store_action = StoreAction::Store; - } - // Each aspect loaded and stored, as the Metal oracle's are. - pass.depth_attachment.texture = depth.clone(); - pass.depth_attachment.load_action = LoadAction::Load; - pass.depth_attachment.store_action = StoreAction::Store; - pass.stencil_attachment.texture = stencil.clone(); - pass.stencil_attachment.load_action = LoadAction::Load; - pass.stencil_attachment.store_action = StoreAction::Store; - pass.render_target_array_length = render.render_target_array_length.into(); - let samples = inputs.case.raster_samples(); - if targets.is_empty() && depth.is_none() && stencil.is_none() { - // The Metal oracle's pass without attachments (`metal::platform`): one pixel, of the - // case's sample count. - pass.render_target_width = 1; - pass.render_target_height = 1; - pass.default_raster_sample_count = samples.into(); - } - // The case's rasterization-rate map, made as the oracle makes it. - if let Some(literal) = &inputs.case.render_pass_rate_map { - let map = device - .new_rasterization_rate_map(&literal.descriptor()) - .map_err(CaseError::runtime("new_rasterization_rate_map"))?; - pass.rasterization_rate_map = Some(map); - } - if let Some(helpers) = &imageblock { - helpers.prepare_pass(&mut pass, &pipeline)?; - } - // A vertex buffer that is an out-of-bounds target (a vertex input's, a control point's or a - // patch input's) lies in a heap of its own between guards. - let mut vertex_buffers = Vec::new(); - let mut guarded = BTreeMap::new(); - for input in &render.vertex_buffers { - let target = OutOfBoundsResource::AttributeBuffer { - location: input.location, - }; - let buffer = match declared_reach(&render.out_of_bounds, target) { - Some(reach) => { - let buffer = guarded_buffer(device, &input.bytes, reach)?; - guarded.insert(target, buffer.clone()); - buffer - } - None => buffer_with(device, &input.bytes)?, - }; - // A dynamic layout's buffer is bound with the stride form. - let stride = input.dynamic.then_some(input.stride); - vertex_buffers.push((input.buffer_index, buffer, stride)); - } - let mut bound: BTreeMap = BTreeMap::new(); - let mut samplers: Vec<(ShaderStage, u32, SamplerState)> = Vec::new(); - let mut tables = TableBuffers::new(); - let context = StageContext { - case: inputs.case, - texture_usage: inputs.texture_usage, - interface: inputs.interface, - templates: inputs.templates, - pipeline: &pipeline, - linked: &linked, - }; - for (stage, function) in render.stages() { - let made = context.bound(device, stage, function, &mut prep)?; - tables.extend(made.words); - samplers.extend( - made.samplers - .into_iter() - .map(|(slot, state)| (stage, slot, state)), - ); - bound.insert(stage, made.bound); - } - // An index buffer that is an out-of-bounds target lies in a heap of its own between guards - // too. - let index_buffer = match &render.index_buffer { - Some(bytes) => Some( - match declared_reach(&render.out_of_bounds, OutOfBoundsResource::IndexBuffer) { - Some(reach) => { - let buffer = guarded_buffer(device, bytes, reach)?; - guarded.insert(OutOfBoundsResource::IndexBuffer, buffer.clone()); - buffer - } - None => buffer_with(device, bytes)?, - }, - ), - None => None, - }; - let queue = device - .new_command_queue() - .map_err(CaseError::runtime("new_command_queue"))?; - let command_buffer = queue - .command_buffer() - .map_err(CaseError::runtime("command_buffer"))?; - for work in &prep { - work.encode(&command_buffer)?; - } - // The case's own executions, between its preparation's and its readback's (each ended - // encoder's join the command buffer's in encoding order). - let prepared = command_buffer.executions().len(); - let mut encoder = command_buffer - .render_command_encoder(&pass) - .map_err(CaseError::runtime("render_command_encoder"))?; - // A rate-mapped pass's viewport is the map's screen, as the oracle sets it. - if let Some(literal) = &inputs.case.render_pass_rate_map { - let [width, height] = literal.screen_size.map(f64::from); - encoder - .set_viewport(Viewport::new(0.0, 0.0, width, height, 0.0, 1.0)) - .map_err(CaseError::runtime("set_viewport"))?; - } - if let Some(helpers) = &imageblock { - helpers.initialize(&mut encoder)?; - } - encoder - .set_render_pipeline_state(&pipeline) - .map_err(CaseError::runtime("set_render_pipeline_state"))?; - // The argument buffers' members, resident for reading and writing in the vertex and fragment - // stages, as the oracle's `useResource:usage:stages:` makes them. - let members: Vec> = bound.values().flat_map(StageBound::members).collect(); - if !members.is_empty() { - encoder - .use_resources( - &members, - ResourceUsage::READ | ResourceUsage::WRITE, - RenderStages::VERTEX | RenderStages::FRAGMENT, - ) - .map_err(CaseError::runtime("use_resources"))?; - } - // The draw's depth/stencil state, references, winding and cull mode, as the Metal oracle - // sets them. - let state = &render.depth_stencil_state; - let depth_stencil_state = device - .new_depth_stencil_state(&state.descriptor) - .map_err(CaseError::runtime("new_depth_stencil_state"))?; - encoder - .set_depth_stencil_state(&depth_stencil_state) - .map_err(CaseError::runtime("set_depth_stencil_state"))?; - encoder.set_stencil_reference_values(state.front_reference, state.back_reference); - encoder.set_front_facing_winding(state.winding); - encoder.set_cull_mode(render.cull_mode); - for (slot, buffer, stride) in &vertex_buffers { - match stride { - Some(stride) => encoder - .set_vertex_buffer_with_stride(Some(buffer), 0, (*stride).into(), *slot) - .map_err(CaseError::runtime("set_vertex_buffer_with_stride"))?, - None => encoder - .set_vertex_buffer(Some(buffer), 0, *slot) - .map_err(CaseError::runtime("set_vertex_buffer"))?, - } - } - bind_stages(&mut encoder, &bound, &samplers)?; - let primitive = match &render.assembly { - Assembly::Primitives(primitive) => Some(metal_primitive_type(*primitive)), - Assembly::Patches { factors, .. } => { - let factors = buffer_with(device, factors)?; - encoder - .set_tessellation_factor_buffer( - Some(&factors), - patches::FACTOR_OFFSET, - patches::FACTOR_INSTANCE_STRIDE, - ) - .map_err(CaseError::runtime("set_tessellation_factor_buffer"))?; - None - } - }; - match (primitive, render.draw, &index_buffer) { - ( - None, - DrawCall::Patches { - control_points, - patch_start, - patch_count, - patch_index: None, - instance_count, - base_instance, - control_point_index: None, - }, - None, - ) => encoder - .draw_patches( - control_points, - patch_start, - patch_count, - None, - 0, - instance_count, - base_instance, - ) - .map_err(CaseError::runtime("draw_patches"))?, - ( - Some(primitive_type), - DrawCall::Primitives { - vertex_start, - vertex_count, - instance_count, - base_instance, - }, - None, - ) => encoder - .draw_primitives( - primitive_type, - vertex_start, - vertex_count, - instance_count, - base_instance, - ) - .map_err(CaseError::runtime("draw_primitives"))?, - ( - Some(primitive_type), - DrawCall::Indexed { - index_count, - index_offset, - instance_count, - base_vertex, - base_instance, - .. - }, - Some(buffer), - ) => { - let index_type = match inputs - .case - .draw - .as_ref() - .and_then(|d| d.index_buffer.as_ref()) - { - Some(literal) => match literal.index_type { - crate::case::IndexType::Uint16 => IndexType::UInt16, - crate::case::IndexType::Uint32 => IndexType::UInt32, - }, - None => return Err("an indexed draw without its literal".into()), - }; - encoder - .draw_indexed_primitives( - primitive_type, - index_count, - index_type, - buffer, - index_offset, - instance_count, - base_vertex, - base_instance, - ) - .map_err(CaseError::runtime("draw_indexed_primitives"))? - } - (_, draw, _) => return Err(format!("the draw {draw:?}, a later runtime step").into()), - } - if let Some(helpers) = &imageblock { - helpers.resolve(&mut encoder)?; - } - encoder - .end_encoding() - .map_err(CaseError::runtime("end_encoding"))?; - // Each `Private` command buffer copied into its twin, so its commands read back. - for stage_bound in bound.values() { - encode_twin_copies(&command_buffer, &stage_bound.commands)?; - } - let mut executions = command_buffer.executions().split_off(prepared); - // The case's own draw's, not its imageblock helpers'. - if let Some(helpers) = &imageblock { - let (before, after) = helpers.draws(); - if executions.len() != before + 1 + after { - return Err(format!( - "the pass recorded {} executions of the case's draw and {} helper draws", - executions.len(), - before + after - ) - .into()); - } - executions = executions.split_off(before); - executions.truncate(1); - } - let readback = match multisampled_output(inputs, &targets, depth.as_ref(), stencil.as_ref())? { - Some((texture, read, extent, origin, dimensions)) => Some(( - runtime_samples::encode(device, &command_buffer, texture, read, extent, samples)?, - [extent, origin, dimensions], - read.texel_bytes() * samples as usize, - )), - None => None, - }; - Ok(EncodedRender { - command_buffer, - executions, - tables, - drawn: Drawn { - targets, - depth, - stencil, - bound, - readback, - guarded, - imageblock, - }, - }) -} - -impl EncodedRender { - /// Each command buffer the draw's stages execute (`render`'s), in stage and key order, encoded - /// on a command buffer of its own of the draw's queue and not committed - /// ([`encoded_execution`]): with the buffers of the stage that holds it, and every buffer and - /// argument-buffer buffer of the draw resident; each parent pipeline its token's template's - /// among `templates`. Committed after the draw's command buffer, each runs once the draw - /// completed. - pub fn executions( - &self, - render: &RenderCase, - templates: &BTreeMap, - ) -> Result, CaseError> { - let bound = &self.drawn.bound; - let resident: Vec> = bound - .values() - .flat_map(|stage| { - stage - .buffers - .values() - .chain(stage.argument_buffers.values()) - }) - .map(Buffer::as_resource) - .collect(); - let mut executions = Vec::new(); - for (stage, function) in render.stages() { - let Some(stage_bound) = bound.get(&stage) else { - continue; - }; - for (&key, resource) in &function.resources.command_buffers { - if resource.execute.is_some() { - executions.push(encoded_execution( - self.command_buffer.command_queue(), - (&stage_bound.buffers, &resident), - &stage_bound.commands, - (key, resource), - templates, - )?); - } - } - } - Ok(executions) - } - - /// Commit the encoded draw. - pub fn commit(self) -> Result { - let EncodedRender { - command_buffer, - executions, - tables, - drawn, - } = self; - command_buffer - .commit() - .map_err(CaseError::runtime("commit"))?; - Ok(CommittedRender { - command_buffer, - executions, - tables, - drawn, - }) - } -} - -/// [`encoded_render`], committed. Nothing is committed when a call is refused. -pub fn commit_render( - device: &Device, - inputs: &RenderInputs<'_>, -) -> Result { - encoded_render(device, inputs)?.commit() -} - -impl CommittedRender { - /// Read back each stage's command buffers once the draw completed - /// (`CaseCommands::check_commands`). - pub fn check_commands(&self) -> Result<(), CaseError> { - self.drawn - .bound - .values() - .try_for_each(|stage| stage.commands.check_commands()) - } - - /// What the draw changed around each of its out-of-bounds targets it placed between guards - /// (`runtime_case::guard_count`), by target, once the command buffer completed: each vertex - /// and index buffer target's. - pub fn guard_counts(&self) -> Result, CaseError> { - self.drawn - .guarded - .iter() - .map(|(&target, buffer)| Ok((target, guard_count(buffer)?))) - .collect() - } - - /// The bytes `inputs`' output selects, once the command buffer completed. - pub fn output(&self, inputs: &RenderInputs<'_>) -> Result, CaseError> { - let render = inputs.render; - if let Some((readback, [extent, origin, dimensions], texel)) = &self.drawn.readback { - return Ok(select_tightly_packed_2d( - &readback.bytes()?, - *extent, - *origin, - *dimensions, - *texel, - )?); - } - self.drawn.read( - &render.output, - |stage| render.function(stage), - &render.color_targets, - ) - } -} - -impl Drawn { - /// The bytes `output` selects of what the draw left, once the command buffer completed: a - /// stage's resource, of the function `function_of` gives at its stage, or a region of a color - /// target of `color_targets`, the depth or the stencil attachment, or the imageblock. - fn read<'a>( - &self, - output: &RenderOutput, - function_of: impl Fn(ShaderStage) -> Option<&'a RenderFunction>, - color_targets: &BTreeMap, - ) -> Result, CaseError> { - let stage_of = |stage: ShaderStage| { - self.bound - .get(&stage) - .ok_or_else(|| format!("the output's stage {stage:?} binds nothing")) - }; - match *output { - RenderOutput::None => Ok(Vec::new()), - RenderOutput::Buffer { - stage, - binding, - offset, - length, - } => read_buffer( - stage_of(stage)? - .buffers - .get(&binding) - .ok_or_else(|| format!("the output buffer {binding} is not bound"))?, - offset, - length, - ), - RenderOutput::Texture { - stage, - binding, - origin, - dimensions, - } => read_texture( - stage_of(stage)? - .textures - .get(&binding) - .ok_or_else(|| format!("the output texture {binding} is not bound"))?, - function_of(stage) - .and_then(|function| function.resources.textures.get(&binding)) - .ok_or_else(|| format!("the output texture {binding} is not declared"))?, - origin, - dimensions, - ), - RenderOutput::ArgumentBufferBuffer { - stage, - owner, - field_offset, - offset, - length, - } => read_buffer( - stage_of(stage)? - .argument_buffers - .get(&(owner, field_offset)) - .ok_or_else(|| { - format!("no argument-buffer buffer at {owner}+{field_offset}") - })?, - offset, - length, - ), - RenderOutput::ArgumentBufferTexture { - stage, - owner, - field_offset, - origin, - dimensions, - } => read_texture( - stage_of(stage)? - .argument_textures - .get(&(owner, field_offset)) - .ok_or_else(|| { - format!("no argument-buffer texture at {owner}+{field_offset}") - })?, - function_of(stage) - .and_then(|function| { - function - .resources - .argument_buffer_textures - .get(&(owner, field_offset)) - }) - .ok_or_else(|| { - format!("argument-buffer texture {owner}+{field_offset} undeclared") - })?, - origin, - dimensions, - ), - RenderOutput::RenderTarget { - index, - origin, - dimensions, - } => { - let texture = self - .targets - .get(&index) - .ok_or_else(|| format!("the output target {index} is not attached"))?; - let pixel = color_targets - .get(&index) - .ok_or_else(|| format!("the output target {index} is not declared"))? - .format - .bytes_per_pixel() as u64; - texels_of(texture, origin, dimensions, pixel) - } - RenderOutput::Depth { origin, dimensions } => { - let texture = self - .depth - .as_ref() - .ok_or("the output's depth is not attached")?; - texels_of(texture, origin, dimensions, 4) - } - RenderOutput::Stencil { origin, dimensions } => { - let texture = self - .stencil - .as_ref() - .ok_or("the output's stencil is not attached")?; - texels_of(texture, origin, dimensions, 1) - } - RenderOutput::Imageblock { - member, - origin, - dimensions, - } => Ok(self - .imageblock - .as_ref() - .ok_or("an imageblock output without its helpers")? - .resolved()? - .select(member, origin, dimensions)?), - } - } -} - -/// The stage of `case`'s own function, whose buffers the case authors: none for a kernel. -fn case_stage(case: &AuthoredCase) -> Option { - match case.stage { - Stage::Vertex => Some(ShaderStage::Vertex), - Stage::Fragment => Some(ShaderStage::Fragment), - Stage::Object => Some(ShaderStage::Object), - Stage::Mesh => Some(ShaderStage::Mesh), - Stage::Kernel => None, - } -} diff --git a/crates/metal2vulkan-validation/src/candidate/runtime_case/render/mesh.rs b/crates/metal2vulkan-validation/src/candidate/runtime_case/render/mesh.rs deleted file mode 100644 index 3d6d9110e..000000000 --- a/crates/metal2vulkan-validation/src/candidate/runtime_case/render/mesh.rs +++ /dev/null @@ -1,232 +0,0 @@ -//! An object or mesh case's draw through the Metal-like runtime, as the Metal oracle draws it -//! (`metal::platform::mesh`): a library of the case's AIR, the function of each stage its draw has -//! (its own and the partners it names) specialized with the case's constant values, the generated -//! stages of a case that states an observation or an object launch from a library of the -//! companion's AIR, a mesh render pipeline state of the oracle's descriptor (its color formats, or -//! the one-pixel sink where it does not rasterize, and its rasterization), its color targets loaded -//! and stored, its own stage's -//! resources made and bound as a render case's stage's are ([`StageContext::bound`], -//! [`bind_stages`]: buffers, argument buffers and their members, textures and sampler states, -//! through that stage's `setObject*` or `setMesh*` setters), and its one `draw_mesh_threadgroups` -//! or `draw_mesh_threads`. A device without `VK_EXT_mesh_shader` draws through the runtime's -//! emulation, which announces `emulated-mesh-draws`. - -use super::*; -use crate::candidate::engine::mesh::MeshCase; -use crate::case::MeshGrid; -use metal2vulkan::pipeline::{ColorAttachmentDescriptor, MeshPipelineDescriptor, StageSource}; -use metal2vulkan_runtime::Size; - -/// What an object or mesh case's draw needs: the authored case, its mesh mapping, its AIR bitcode, -/// its generated companion's (the generated stages of a case that states an observation or an -/// object launch), the -/// usage the Metal oracle gives each of its own textures (`runtime_case::texture_usage`), and its -/// own function's AIR interface, whose argument-buffer members give each argument-buffer texture's -/// usage. -pub struct MeshInputs<'a> { - pub case: &'a AuthoredCase, - pub mesh: &'a MeshCase, - pub bitcode: &'a [u8], - pub companion: Option<&'a [u8]>, - pub texture_usage: &'a BTreeMap, - pub interface: &'a AirInterface, -} - -/// The mesh render pipeline state of `mesh`'s draw on `device`, of the oracle's descriptor: the -/// function of each stage its draw has from a library of `bitcode`, its AIR, or of `companion`, the -/// generated companion's, for the generated stages, specialized with the case's constant values; -/// its color formats (or the one-pixel sink's where it does not rasterize) and its rasterization; -/// and `support_indirect_command_buffers` where `indirect`, as a pipeline template's state. -pub fn mesh_pipeline_state( - device: &Device, - mesh: &MeshCase, - (bitcode, companion): (&[u8], Option<&[u8]>), - indirect: bool, -) -> Result { - let library = device - .new_library_with_air(bitcode) - .map_err(CaseError::runtime("new_library_with_air"))?; - // The generated stages' library, which a draw that states an observation or an object launch - // has. - let generated = match (companion, mesh.generated.is_empty()) { - (Some(bitcode), false) => Some( - device - .new_library_with_air(bitcode) - .map_err(CaseError::runtime("new_library_with_air"))?, - ), - (None, true) => None, - _ => return Err("a generated companion without its library, or its stages".into()), - }; - let function = |stage: ShaderStage, function: &RenderFunction| { - let (library, what) = match &generated { - Some(generated) if mesh.generated.contains(&stage) => { - (generated, "the generated companion's ") - } - _ => (&library, ""), - }; - library - .new_function_with_name_constant_values(&function.entry, &function.constants) - .map_err(CaseError::runtime(format!( - "{what}function {}: new_function_with_name_constant_values", - function.entry - ))) - }; - let source = |function: Function| StageSource::Function(function.function_descriptor()); - let mut descriptor = - MeshPipelineDescriptor::new(source(function(ShaderStage::Mesh, &mesh.mesh)?)); - descriptor.object = mesh - .object - .as_ref() - .map(|object| function(ShaderStage::Object, object)) - .transpose()? - .map(source); - descriptor.fragment = mesh - .fragment - .as_ref() - .map(|fragment| function(ShaderStage::Fragment, fragment)) - .transpose()? - .map(source); - descriptor.rasterization_enabled = mesh.rasterization; - for (&index, target) in &mesh.color_targets { - let attachment = descriptor - .color_attachments - .get_mut(index as usize) - .ok_or_else(|| format!("color target {index} is past the descriptor's attachments"))?; - *attachment = Some(ColorAttachmentDescriptor::new(pixel_format(target.format))); - } - descriptor.support_indirect_command_buffers = indirect; - device - .new_mesh_render_pipeline_state(&descriptor, &PipelineOptions::default()) - .map_err(CaseError::runtime("new_mesh_render_pipeline_state")) -} - -/// Encode `inputs`' draw on `device`: its pipeline state ([`mesh_pipeline_state`]), color targets, -/// its own stage's resources, one command buffer with the fills its textures need, and one render -/// encoder with its one draw, ended. Committed ([`EncodedRender::commit`]), its output is read by -/// [`CommittedRender::mesh_output`]. -pub fn encoded_mesh(device: &Device, inputs: &MeshInputs<'_>) -> Result { - let mesh = inputs.mesh; - let pipeline = mesh_pipeline_state(device, mesh, (inputs.bitcode, inputs.companion), false)?; - let mut prep = Vec::new(); - let targets = mesh - .color_targets - .iter() - .map(|(&index, target)| Ok((index, target_with(device, target, false, &mut prep)?))) - .collect::, CaseError>>()?; - let mut pass = RenderPassDescriptor::new(); - for (&index, texture) in &targets { - let attachment = &mut pass.color_attachments[index as usize]; - attachment.texture = Some(texture.clone()); - attachment.load_action = LoadAction::Load; - attachment.store_action = StoreAction::Store; - } - // The case's own function links nothing: the schema refuses an object or mesh case's - // visible-function references and tables. - let own = mesh - .function(mesh.stage) - .ok_or("the case's own stage has no function")?; - let linked = linked_functions(device, &[], &own.constants)?; - let templates = BTreeMap::new(); - let context = StageContext { - case: inputs.case, - texture_usage: inputs.texture_usage, - interface: inputs.interface, - templates: &templates, - pipeline: &pipeline, - linked: &linked, - }; - let mut bound: BTreeMap = BTreeMap::new(); - let mut samplers = Vec::new(); - let mut tables = TableBuffers::new(); - for (stage, function) in mesh.stages() { - let made = context.bound(device, stage, function, &mut prep)?; - tables.extend(made.words); - samplers.extend( - made.samplers - .into_iter() - .map(|(slot, state)| (stage, slot, state)), - ); - bound.insert(stage, made.bound); - } - let queue = device - .new_command_queue() - .map_err(CaseError::runtime("new_command_queue"))?; - let command_buffer = queue - .command_buffer() - .map_err(CaseError::runtime("command_buffer"))?; - for work in &prep { - work.encode(&command_buffer)?; - } - // The case's own execution, after its preparation's. - let prepared = command_buffer.executions().len(); - let mut encoder = command_buffer - .render_command_encoder(&pass) - .map_err(CaseError::runtime("render_command_encoder"))?; - encoder - .set_render_pipeline_state(&pipeline) - .map_err(CaseError::runtime("set_render_pipeline_state"))?; - // The argument buffers' members, resident for reading and writing in the case's own stage, as - // the oracle's `useResource:usage:stages:` makes them. - let members: Vec> = bound.values().flat_map(StageBound::members).collect(); - if !members.is_empty() { - encoder - .use_resources( - &members, - ResourceUsage::READ | ResourceUsage::WRITE, - render_stage(mesh.stage), - ) - .map_err(CaseError::runtime("use_resources"))?; - } - bind_stages(&mut encoder, &bound, &samplers)?; - // An object function's threadgroup memory, as the oracle sets it; the case schema refuses a - // mesh case's. - if inputs.case.stage == crate::case::Stage::Object { - for resource in &inputs.case.threadgroup_memory { - encoder - .set_object_threadgroup_memory_length(resource.length, resource.binding) - .map_err(CaseError::runtime("set_object_threadgroup_memory_length"))?; - } - } - let size = |[x, y, z]: [u32; 3]| Size::new(x.into(), y.into(), z.into()); - let (object, threads) = ( - size(mesh.threads_per_object_threadgroup), - size(mesh.threads_per_mesh_threadgroup), - ); - match mesh.grid { - MeshGrid::Threadgroups(groups) => { - encoder.draw_mesh_threadgroups(size(groups), object, threads) - } - MeshGrid::Threads(grid) => encoder.draw_mesh_threads(size(grid), object, threads), - } - .map_err(CaseError::runtime("draw_mesh_*"))?; - encoder - .end_encoding() - .map_err(CaseError::runtime("end_encoding"))?; - let executions = command_buffer.executions().split_off(prepared); - Ok(EncodedRender { - command_buffer, - executions, - tables, - drawn: Drawn { - targets, - depth: None, - stencil: None, - bound, - readback: None, - guarded: BTreeMap::new(), - imageblock: None, - }, - }) -} - -impl CommittedRender { - /// The bytes `mesh`'s output selects, once the command buffer completed: a resource of its own - /// stage, or a region of a render target. - pub fn mesh_output(&self, mesh: &MeshCase) -> Result, CaseError> { - self.drawn.read( - &mesh.output, - |stage| mesh.function(stage), - &mesh.color_targets, - ) - } -} diff --git a/crates/metal2vulkan-validation/src/candidate/runtime_case/sparse.rs b/crates/metal2vulkan-validation/src/candidate/runtime_case/sparse.rs deleted file mode 100644 index dd9f82146..000000000 --- a/crates/metal2vulkan-validation/src/candidate/runtime_case/sparse.rs +++ /dev/null @@ -1,177 +0,0 @@ -//! A case's sparse texture through the runtime: made as the Metal oracle makes it, from a sparse -//! heap of 16-KiB pages, its mappings mapped before the work by a resource state encoder, and only -//! the authored bytes of its mapped texels uploaded. -//! -//! A mapping names texels; the runtime maps Metal's tiles, so a region that is not a whole number -//! of them (its origin a multiple of the tile, its end one or the level's edge) does not run -//! (`CaseError::Case`), as every executor refuses one of its own tiles. A slice's mip tail is its -//! level from Metal's `firstMipmapInTail`: the tail where Metal keeps the case's one level in -//! one, and that level's tiles where it does not. A tile maps alone on every device that makes -//! the texture, whatever its blocks. - -use super::{texture_descriptor, CaseError}; -use crate::case::sparse::{SparseMapping, SparseTextureResource}; -use crate::literal::LiteralTexture; -use metal2vulkan::bind::TileMapping; -use metal2vulkan::metal::TextureUsage; -use metal2vulkan_runtime::{ - BlitOption, Device, HeapDescriptor, HeapType, Origin, Region, ResourceOptions, Size, Texture, -}; -use std::time::Duration; - -/// The longest the mapping and upload may take. -const WAIT: Duration = Duration::from_secs(60); - -/// The sparse texture of `literal`, whose mappings `sparse` lists, with `usage`. -pub(super) fn texture_with( - device: &Device, - literal: &LiteralTexture, - sparse: &SparseTextureResource, - usage: TextureUsage, -) -> Result { - let label = format!("sparse texture {}", literal.binding); - let mut descriptor = texture_descriptor(literal, usage)?; - descriptor.resource_options = ResourceOptions::private(); - // Room for every tile of each slice, whatever its rows waste, and a tail each. - let room = (literal.bytes.len() as u64 * 4) - .max(1 << 20) - .next_multiple_of(16384); - let heap = device - .new_heap(&HeapDescriptor::new( - HeapType::Sparse, - room, - ResourceOptions::private(), - )) - .map_err(CaseError::runtime(format!("{label}: new_heap")))?; - let texture = heap - .new_texture(&descriptor) - .map_err(CaseError::runtime(format!("{label}: new_texture")))?; - let tile = device.sparse_tile_size(descriptor.texture_type, descriptor.pixel_format, 1); - let tile = [tile.width, tile.height, tile.depth]; - let extent = [descriptor.width, descriptor.height, descriptor.depth]; - let first_tail = texture.first_mipmap_in_tail().unwrap_or(1); - // Each mapping as Metal's tiles of level 0 and the texels it uploads. - let mut updates = Vec::new(); - for (index, mapping) in sparse.mappings.iter().enumerate() { - let (slice, origin, size) = match *mapping { - SparseMapping::Region { - slice, - origin, - size, - .. - } => (slice, origin.map(u64::from), size.map(u64::from)), - SparseMapping::MipTail { slice } => (slice, [0; 3], extent), - }; - let whole = (0..3).all(|axis| { - let end = origin[axis] + size[axis]; - origin[axis] % tile[axis] == 0 && (end % tile[axis] == 0 || end == extent[axis]) - }); - if !whole { - return Err(format!( - "{label} mapping {index}: texels {origin:?} + {size:?} are not whole tiles of \ - {tile:?}" - ) - .into()); - } - let tiles = Region::new_3d( - origin[0] / tile[0], - origin[1] / tile[1], - origin[2] / tile[2], - (origin[0] + size[0]).div_ceil(tile[0]) - origin[0] / tile[0], - (origin[1] + size[1]).div_ceil(tile[1]) - origin[1] / tile[1], - (origin[2] + size[2]).div_ceil(tile[2]) - origin[2] / tile[2], - ); - // Metal keeps the level whole in its tail: the tail's update, for the whole level only. - let tiles = if first_tail == 0 { - if origin != [0; 3] || size != extent { - return Err(format!( - "{label} mapping {index}: texels {origin:?} + {size:?} are part of a level \ - Metal keeps in its mip tail" - ) - .into()); - } - Region::new_2d(0, 0, 0, 0) - } else { - tiles - }; - updates.push((u64::from(slice), tiles, origin, size)); - } - let queue = device - .new_command_queue() - .map_err(CaseError::runtime(format!("{label}: new_command_queue")))?; - let command_buffer = queue - .command_buffer() - .map_err(CaseError::runtime(format!("{label}: command_buffer")))?; - let mut encoder = - command_buffer - .resource_state_command_encoder() - .map_err(CaseError::runtime(format!( - "{label}: resource_state_command_encoder" - )))?; - for &(slice, tiles, ..) in &updates { - encoder - .update_texture_mapping(&texture, TileMapping::Map, tiles, 0, slice) - .map_err(CaseError::runtime(format!( - "{label}: update_texture_mapping" - )))?; - } - encoder - .end_encoding() - .map_err(CaseError::runtime(format!("{label}: end_encoding")))?; - // The mapped texels' authored bytes, rows tightly packed as the literal holds them. - let texel = literal.format.bytes_per_pixel() as u64; - let row = extent[0] * texel; - let image = row * extent[1]; - let slice_bytes = image * extent[2]; - let source = device - .new_buffer( - (literal.bytes.len() as u64).max(1), - ResourceOptions::shared(), - ) - .map_err(CaseError::runtime(format!("{label}: new_buffer")))?; - let contents = source - .contents() - .ok_or_else(|| format!("{label}: a Shared buffer without host bytes"))?; - // SAFETY: the buffer holds the literal's bytes, and no command uses it yet. - unsafe { - std::ptr::copy_nonoverlapping( - literal.bytes.as_ptr(), - contents.as_ptr(), - literal.bytes.len(), - ) - }; - let mut blit = command_buffer - .blit_command_encoder() - .map_err(CaseError::runtime(format!("{label}: blit_command_encoder")))?; - for &(slice, _, origin, size) in &updates { - let offset = slice * slice_bytes + origin[2] * image + origin[1] * row + origin[0] * texel; - let per_image = if extent[2] > 1 { image } else { 0 }; - blit.copy_from_buffer_to_texture( - &source, - offset, - row, - per_image, - Size::new(size[0], size[1], size[2]), - &texture, - slice, - 0, - Origin::new(origin[0], origin[1], origin[2]), - BlitOption::None, - ) - .map_err(CaseError::runtime(format!( - "{label}: copy_from_buffer_to_texture" - )))?; - } - blit.end_encoding() - .map_err(CaseError::runtime(format!("{label}: end_encoding")))?; - command_buffer - .commit() - .map_err(CaseError::runtime(format!("{label}: commit")))?; - command_buffer - .wait_until_completed_for(WAIT) - .map_err(|_| format!("{label}: the mapping did not complete in {WAIT:?}"))?; - if let Some(error) = command_buffer.error() { - return Err(format!("{label}: the mapping failed: {error:?}").into()); - } - Ok(texture) -} diff --git a/crates/metal2vulkan-validation/src/candidate/runtime_case/tile.rs b/crates/metal2vulkan-validation/src/candidate/runtime_case/tile.rs deleted file mode 100644 index 62ebc10f8..000000000 --- a/crates/metal2vulkan-validation/src/candidate/runtime_case/tile.rs +++ /dev/null @@ -1,218 +0,0 @@ -//! A tile kernel's dispatch through the Metal-like runtime, as the Metal oracle dispatches it -//! (`metal::platform::tile`): the one copy the runtime lane's tile census -//! (`runtime_lane::tile_dispatches`) and the engine executor's runtime path (`runtime_run`) -//! share. -//! -//! A tile pipeline state of the oracle's descriptor ([`tile_descriptor`]: the tile function, the -//! functions it links, the pass's attachments' formats, one sample), the pass's attachments, each -//! a `Shared` 2D render target of its authored format, extent and contents that loads and stores, -//! in a pass of the case's area whose tile is the case's imageblock and whose -//! `imageblockSampleLength` is the state's, as the oracle asks it; the case's buffers, textures, -//! sampler states and visible-function tables set on the encoder's tile stage, one -//! `dispatch_threads_per_tile` of the case's threads per tile, and the output read back after the -//! command buffer completed. Its argument buffers are made as a compute dispatch's are -//! (`runtime_case::bound_buffers`), their buffers and textures resident for reading and writing -//! in the tile stage, as the oracle's `useResource:usage:stages:` makes them; its tables are made -//! by the tile state for the tile stage ([`tile_tables`]). -//! -//! The oracle draws a triangle over the pass first, whose fragment writes no color, so that -//! Metal's imageblock holds every pixel (`ImplicitImageblockCoverage::FullSingleSample`); it -//! changes no pixel, so the runtime path draws none. The oracle's threadgroup memory lengths are -//! not set: the compile layer refuses a tile function's threadgroup memory, so the state's creation -//! refuses a case whose function reads one. A tile dispatch's command buffers and the pipeline -//! states its argument buffers hold are refused as a [`CaseError::Case`] naming "a later runtime -//! step"; the executor's route sends no such case here (`runtime_run::kernel_prerequisites`). - -use super::{ - bound_buffers, tables_of, texture_with, CaseError, CaseResources, CaseTables, Encoded, - LinkedSet, -}; -use crate::candidate::engine::{ComputeCase, TilePass}; -use metal2vulkan::bind::Dispatch; -use metal2vulkan::metal::{RenderStages, ResourceUsage, TextureUsage}; -use metal2vulkan::pipeline::{ - LinkedFunctions, Stage as ShaderStage, StageSource, TileRenderPipelineDescriptor, -}; -use metal2vulkan_runtime::{ - Buffer, Device, Function, LoadAction, RenderPassDescriptor, RenderPipelineState, ResourceRef, - Size, StoreAction, Texture, VisibleFunctionTable, -}; -use std::collections::BTreeMap; - -/// The descriptor of a tile kernel's pipeline state over `pass`, as the Metal oracle states it: -/// its tile `function` (made with the case's constant values) linking `linked`, each attachment's -/// pixel format at its color index, one sample, and `threadgroupSizeMatchesTileSize` off. The -/// oracle's `requiredThreadsPerThreadgroup` sizes Metal's pipeline for the case's threads; the -/// runtime's tile pipeline runs every measured threadgroup up to 32 by 32, so the descriptor states -/// none. -pub fn tile_descriptor( - function: &Function, - linked: LinkedFunctions, - pass: &TilePass, -) -> TileRenderPipelineDescriptor { - let mut descriptor = TileRenderPipelineDescriptor::new(StageSource::Function( - function.function_descriptor().with_linked(linked), - )); - for (index, format) in pass.formats() { - if let Some(slot) = descriptor.color_attachment_formats.get_mut(index as usize) { - *slot = Some(format); - } - } - descriptor -} - -/// The visible-function tables of tile kernel `case` for its tile state `pipeline`, as -/// `runtime_case::visible_function_tables` makes a kernel's: each made by the state for the tile -/// stage and each entry the handle the state gives the function it holds among `linked` for that -/// stage, as the oracle makes them (`newVisibleFunctionTableWithDescriptor:stage:`); the bytes -/// keyed by the kernel stage, as the executor keys a tile kernel's. -pub fn tile_tables( - pipeline: &RenderPipelineState, - case: &ComputeCase, - linked: &LinkedSet, -) -> Result { - tables_of( - (ShaderStage::Kernel, &case.function_tables), - linked, - |descriptor| pipeline.new_visible_function_table(descriptor, RenderStages::TILE), - |function| pipeline.function_handle(function, RenderStages::TILE), - ) -} - -/// Encode tile kernel `case`'s dispatch on `device` with `pipeline` (the tile pipeline state of -/// its entry, [`tile_descriptor`]), its visible-function `tables` ([`tile_tables`]), and the -/// textures' `usage` and `argument_usage` ([`CaseResources::of`]): its resources holding their -/// bytes, its pass's attachments holding theirs, one command buffer with the fills of its -/// multisampled textures, then one render encoder of the pass and its one tile dispatch (the -/// module's rule), ended. [`Encoded::commit`] runs it. -pub fn encoded_tile( - device: &Device, - case: &ComputeCase, - usage: &BTreeMap, - argument_usage: &BTreeMap<(u32, u32), TextureUsage>, - pipeline: &RenderPipelineState, - tables: BTreeMap, -) -> Result { - let pass = case.tile.as_ref().ok_or("the case runs in no tile pass")?; - if !case.command_buffers.is_empty() || !case.objects.is_empty() { - return Err(CaseError::Case( - "a tile dispatch's command buffers and pipeline states: a later runtime step" - .to_owned(), - )); - } - let Dispatch::Threadgroups { - threads_per_group, .. - } = case.dispatch - else { - return Err(format!("a tile pass's dispatch {:?}", case.dispatch).into()); - }; - let [tile_width, tile_height] = case.imageblock.ok_or("a tile pass without a tile size")?; - let mut resources = CaseResources::of(device, case, usage, argument_usage)?; - resources.tables = tables; - let buffers = bound_buffers(device, case, &resources)?; - let attachments = pass - .attachments - .iter() - .map(|(&index, literal)| { - Ok(( - index, - texture_with(device, literal, TextureUsage::RENDER_TARGET)?, - )) - }) - .collect::, CaseError>>()?; - let mut descriptor = RenderPassDescriptor::new(); - for (&index, texture) in &attachments { - let attachment = descriptor - .color_attachments - .get_mut(index as usize) - .ok_or_else(|| format!("a tile pass's attachment {index}"))?; - attachment.texture = Some(texture.clone()); - attachment.load_action = LoadAction::Load; - attachment.store_action = StoreAction::Store; - } - descriptor.tile_width = tile_width.into(); - descriptor.tile_height = tile_height.into(); - descriptor.imageblock_sample_length = pipeline - .imageblock_sample_length() - .map_err(CaseError::runtime("imageblock_sample_length"))?; - descriptor.render_target_width = pass.area[0].into(); - descriptor.render_target_height = pass.area[1].into(); - let queue = device - .new_command_queue() - .map_err(CaseError::runtime("new_command_queue"))?; - let command_buffer = queue - .command_buffer() - .map_err(CaseError::runtime("command_buffer"))?; - for fill in &resources.fills { - fill.encode(&command_buffer)?; - } - let filled = command_buffer.executions().len(); - let mut encoder = command_buffer - .render_command_encoder(&descriptor) - .map_err(CaseError::runtime("render_command_encoder"))?; - encoder - .set_render_pipeline_state(pipeline) - .map_err(CaseError::runtime("set_render_pipeline_state"))?; - for (&index, buffer) in &buffers { - encoder - .set_tile_buffer(Some(buffer), 0, index) - .map_err(CaseError::runtime(format!("set_tile_buffer {index}")))?; - } - for (&index, table) in &resources.tables { - encoder - .set_tile_visible_function_table(Some(table), index) - .map_err(CaseError::runtime(format!( - "set_tile_visible_function_table {index}" - )))?; - } - // The argument buffers' members, resident for reading and writing in the tile stage, as the - // oracle's `useResource:usage:stages:` makes them. - let members: Vec> = resources - .argument_buffers - .values() - .map(Buffer::as_resource) - .chain( - resources - .argument_textures - .values() - .map(Texture::as_resource), - ) - .collect(); - if !members.is_empty() { - encoder - .use_resources( - &members, - ResourceUsage::READ | ResourceUsage::WRITE, - RenderStages::TILE, - ) - .map_err(CaseError::runtime("use_resources"))?; - } - for (&index, texture) in &resources.textures { - encoder - .set_tile_texture(Some(texture), index) - .map_err(CaseError::runtime(format!("set_tile_texture {index}")))?; - } - for (&index, sampler) in &resources.samplers { - encoder - .set_tile_sampler_state(Some(sampler), index) - .map_err(CaseError::runtime(format!( - "set_tile_sampler_state {index}" - )))?; - } - let [width, height, depth] = threads_per_group.map(u64::from); - encoder - .dispatch_threads_per_tile(Size::new(width, height, depth)) - .map_err(CaseError::runtime("dispatch_threads_per_tile"))?; - encoder - .end_encoding() - .map_err(CaseError::runtime("end_encoding"))?; - // Each ended encoder's executions join the command buffer's in encoding order. - let executions = command_buffer.executions().split_off(filled); - Ok(Encoded { - command_buffer, - buffers, - resources, - attachments, - executions, - }) -} diff --git a/crates/metal2vulkan-validation/src/candidate/runtime_samples.rs b/crates/metal2vulkan-validation/src/candidate/runtime_samples.rs deleted file mode 100644 index 1f3e41f21..000000000 --- a/crates/metal2vulkan-validation/src/candidate/runtime_samples.rs +++ /dev/null @@ -1,484 +0,0 @@ -//! A multisampled texture filled sample by sample through the Metal-like runtime, as the Metal -//! oracle fills one (`metal::platform::textures`'s multisample initializer): Metal writes no -//! multisampled texture from the CPU, so a render pass per slice draws the fullscreen triangle at -//! sample rate and each invocation writes its own sample's value from a buffer of every pixel's -//! samples in order. The functions are the owned fixture `rt6_samples`'s (the oracle's source with -//! the extent's width and the sample count read from a buffer, where the oracle writes them into -//! its source), one fragment function per format the oracle fills. -//! -//! A fill is encoded into the command buffer whose work reads the texture, ahead of that work -//! ([`SampleFill::encode`]): Metal runs a command buffer's passes in order, so nothing waits on -//! the fill alone and one wait covers it. -//! -//! A multisampled attachment is read back sample by sample the same way ([`encode`], as the -//! oracle's `metal::platform` `sample_readback` reads one): Metal copies no multisampled texture -//! to a buffer, so a dispatch of one thread per sample (threadgroups of one, the grid the pixels -//! by the samples) reads each sample and writes the texel's words at its place in the -//! sample-minor layout, with the fixture's kernels. A `Depth32Float` attachment is read as its -//! bits, a `Stencil8` one as its first component. A color one is read through an unsigned view -//! with its own components and bits (`color_view`), whose kernel packs them into the words the -//! oracle's view of the texel size gives: the bytes are the oracle's, and no device needs -//! Vulkan's `imageViewFormatReinterpretation` (MoltenVK withholds it). Nothing is resolved. - -use super::engine::resources::pixel_format; -use super::runtime_case::{buffer_with, read_buffer, texture_descriptor, CaseError}; -use crate::air_library::AirLibrary; -use crate::case::TextureFormat; -use crate::executor_contract::multisample::{readback_bytes, unpack_words, SampleRead}; -use crate::literal::{LiteralTexture, TextureLayout}; -use metal2vulkan::metal::state::DepthStencilDescriptor; -use metal2vulkan::metal::{CompareFunction, PixelFormat, PrimitiveType, TextureUsage}; -use metal2vulkan::pipeline::FunctionDescriptor; -use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; -use metal2vulkan_devtools::{engine_dir, llvm_assemble}; -use metal2vulkan_runtime::{ - Buffer, CommandBuffer, DepthStencilState, Device, Library, LoadAction, PipelineOptions, - RenderPassDescriptor, RenderPipelineState, ResourceOptions, Size, StoreAction, Texture, -}; -use std::sync::OnceLock; - -/// The owned fixture's opaque-pointer text. -const FIXTURE: &str = "rt6_samples.ll"; - -/// The fixture's vertex function: the oracle's fullscreen triangle. -const VERTEX: &str = "rt6_fill_vertex"; - -/// The fixture's library on `device`, its bitcode assembled once per process. -pub fn library(device: &Device) -> Result { - static BITCODE: OnceLock, String>> = OnceLock::new(); - let bitcode = BITCODE - .get_or_init(|| { - llvm_assemble(&engine_dir().join(FIXTURE)) - .map_err(|error| format!("llvm-as of {FIXTURE}: {error:?}")) - }) - .as_ref() - .map_err(|error| CaseError::from(error.clone()))?; - device - .new_library_with_air(bitcode) - .map_err(CaseError::helper(format!( - "{FIXTURE}: new_library_with_air" - ))) -} - -/// A buffer of the shape the fixture's functions read: the extent's `width` and the `samples` of -/// each pixel. -pub fn shape(device: &Device, width: u32, samples: u32) -> Result { - let mut bytes = width.to_le_bytes().to_vec(); - bytes.extend_from_slice(&samples.to_le_bytes()); - buffer_with(device, &bytes) -} - -/// The fixture's fragment function that fills a texture of `format`, as the oracle's -/// initializer fills it: a sampled-only format and the 64-bit one are no multisampled texture's. -fn fill_function(format: TextureFormat) -> Result<&'static str, String> { - Ok(match format { - TextureFormat::R8Unorm => "rt6_fill_r8unorm", - TextureFormat::Rgba8Unorm => "rt6_fill_rgba8unorm", - TextureFormat::Rgba8Uint => "rt6_fill_rgba8uint", - TextureFormat::Rgba8Sint => "rt6_fill_rgba8sint", - TextureFormat::R16Float => "rt6_fill_r16float", - TextureFormat::R16Uint => "rt6_fill_r16uint", - TextureFormat::Rg16Float => "rt6_fill_rg16float", - TextureFormat::Rg32Float => "rt6_fill_rg32float", - TextureFormat::Rgba16Float => "rt6_fill_rgba16float", - TextureFormat::Rgba16Uint => "rt6_fill_rgba16uint", - TextureFormat::Rgba16Sint => "rt6_fill_rgba16sint", - TextureFormat::R32Uint => "rt6_fill_r32uint", - TextureFormat::R32Sint => "rt6_fill_r32sint", - TextureFormat::R32Float => "rt6_fill_r32float", - TextureFormat::Rgba32Uint => "rt6_fill_rgba32uint", - TextureFormat::Rgba32Sint => "rt6_fill_rgba32sint", - TextureFormat::Rgba32Float => "rt6_fill_rgba32float", - TextureFormat::Depth32Float => "rt6_fill_depth32float", - TextureFormat::R8Snorm - | TextureFormat::Rgba8Snorm - | TextureFormat::R16Unorm - | TextureFormat::Rgba16Unorm - | TextureFormat::R16Snorm - | TextureFormat::Rg16Snorm - | TextureFormat::Rgba16Snorm - | TextureFormat::Rgba8UnormSrgb - | TextureFormat::Bgra8Unorm - | TextureFormat::Bgra8UnormSrgb - | TextureFormat::R8UnormSrgb - | TextureFormat::Rg8Unorm - | TextureFormat::Rg8UnormSrgb - | TextureFormat::Rg8Snorm - | TextureFormat::Rg16Unorm - | TextureFormat::A8Unorm - | TextureFormat::B5g6r5Unorm - | TextureFormat::A1bgr5Unorm - | TextureFormat::Abgr4Unorm - | TextureFormat::Bgr5a1Unorm - | TextureFormat::Rgb10a2Unorm - | TextureFormat::Bgr10a2Unorm - | TextureFormat::Rg11b10Float - | TextureFormat::Rgb9e5Float => { - return Err(format!( - "{format:?} is a sampled-only format, which no case multisamples" - )) - } - TextureFormat::Rg32Uint => { - return Err(format!( - "{format:?} is the ulong texture format, which no case multisamples" - )) - } - }) -} - -/// The fixture's function `name` on `device`. -fn entry(device: &Device, name: &str) -> Result { - library(device)? - .new_function_with_name(name) - .map(|f| f.function_descriptor()) - .map_err(CaseError::helper(format!("{FIXTURE}: function {name}"))) -} - -/// The render pipeline [`SampleFill::new`] makes the state of its fill of a texture of `format` -/// and `samples` of, for a test that expects what the making announces. -pub fn fill_descriptor( - device: &Device, - format: TextureFormat, - samples: u32, -) -> Result { - let function = fill_function(format)?; - let mut descriptor = - RenderPipelineDescriptor::new(StageSource::Function(entry(device, VERTEX)?)); - descriptor.fragment = Some(StageSource::Function(entry(device, function)?)); - if format == TextureFormat::Depth32Float { - descriptor.depth_format = Some(PixelFormat::Depth32Float); - } else { - descriptor.color_attachments[0] = - Some(ColorAttachmentDescriptor::new(pixel_format(format))); - } - descriptor.raster_sample_count = samples; - Ok(descriptor) -} - -/// The kernel [`encode`] reads a texture of `format` as `read` with, for a test that expects -/// what the making of its state announces. -pub fn read_function( - device: &Device, - format: PixelFormat, - read: SampleRead, -) -> Result { - let kernel = match read { - SampleRead::Color(_) => color_view(format)?.1, - SampleRead::Depth => "rt6_read_depth", - SampleRead::Stencil => "rt6_read_stencil", - }; - entry(device, kernel) -} - -/// The view [`encode`] reads a color texture of `format` through: an unsigned format of its -/// components and bits, which is `format` itself for an unsigned one. A texture made without -/// `PixelFormatView` usage holds a view of another format apart (`shadowed-texture-view`). -pub fn read_view(format: PixelFormat) -> Result { - Ok(color_view(format)?.0) -} - -/// The fill of one multisampled texture: its pipeline, the buffers it reads, and the slices it -/// writes ([`SampleFill::new`]). -pub struct SampleFill { - texture: Texture, - pipeline: RenderPipelineState, - /// A depth texture's state: every sample written, whatever it held (`Always`). - depth_state: Option, - values: Buffer, - shape: Buffer, - layers: u32, - layer_bytes: u64, -} - -impl SampleFill { - /// The fill of `texture`, a multisampled render target of `format` and `layout`, with - /// `bytes`: each slice's pixels, rows in order, each pixel's samples in order. - pub fn new( - device: &Device, - texture: &Texture, - format: TextureFormat, - layout: TextureLayout, - bytes: &[u8], - ) -> Result { - let function = fill_function(format)?; - let depth = format == TextureFormat::Depth32Float; - let descriptor = fill_descriptor(device, format, layout.sample_count)?; - let pipeline = device - .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) - .map_err(CaseError::helper(format!( - "{function}: new_render_pipeline_state" - )))?; - let depth_state = depth - .then(|| { - let mut state = DepthStencilDescriptor::default(); - state.depth_compare_function = CompareFunction::Always; - state.depth_write_enabled = true; - device - .new_depth_stencil_state(&state) - .map_err(CaseError::runtime("new_depth_stencil_state")) - }) - .transpose()?; - let layer_bytes = [ - layout.width, - layout.height, - layout.sample_count, - format.bytes_per_pixel() as u32, - ] - .into_iter() - .try_fold(1u64, |n, f| n.checked_mul(u64::from(f))) - .ok_or("a multisampled texture's slice size overflows")?; - let needed = layer_bytes * u64::from(layout.array_layers); - if (bytes.len() as u64) < needed || needed == 0 { - return Err(format!( - "a multisampled texture supplies {} bytes but its extent needs {needed}", - bytes.len() - ) - .into()); - } - Ok(SampleFill { - texture: texture.clone(), - pipeline, - depth_state, - values: buffer_with(device, bytes)?, - shape: shape(device, layout.width, layout.sample_count)?, - layers: layout.array_layers, - layer_bytes, - }) - } - - /// Encode the fill into `command_buffer`: per slice, a render pass that loads nothing and - /// stores every sample, drawing the fullscreen triangle once. - pub fn encode(&self, command_buffer: &CommandBuffer) -> Result<(), CaseError> { - self.encode_into(command_buffer, None) - } - - /// [`SampleFill::encode`] of a color texture whose passes also resolve each slice into the - /// same slice of `resolve` (`StoreAndMultisampleResolve`): a draw's samples resolved by the - /// store action of the pass that wrote them. - pub fn encode_resolving( - &self, - command_buffer: &CommandBuffer, - resolve: &Texture, - ) -> Result<(), CaseError> { - self.encode_into(command_buffer, Some(resolve)) - } - - /// The fill's passes, each resolving its color slice into `resolve` where given. - fn encode_into( - &self, - command_buffer: &CommandBuffer, - resolve: Option<&Texture>, - ) -> Result<(), CaseError> { - for layer in 0..self.layers { - let mut pass = RenderPassDescriptor::new(); - let texture = Some(self.texture.clone()); - if self.depth_state.is_some() { - let attachment = &mut pass.depth_attachment; - attachment.texture = texture; - attachment.slice = layer.into(); - attachment.load_action = LoadAction::DontCare; - attachment.store_action = StoreAction::Store; - } else { - let attachment = &mut pass.color_attachments[0]; - attachment.texture = texture; - attachment.slice = layer.into(); - attachment.load_action = LoadAction::DontCare; - attachment.store_action = StoreAction::Store; - if let Some(resolve) = resolve { - attachment.resolve_texture = Some(resolve.clone()); - attachment.resolve_slice = layer.into(); - attachment.store_action = StoreAction::StoreAndMultisampleResolve; - } - } - let mut encoder = - command_buffer - .render_command_encoder(&pass) - .map_err(CaseError::runtime( - "the sample fill's render_command_encoder", - ))?; - let fill = CaseError::runtime; - encoder - .set_render_pipeline_state(&self.pipeline) - .map_err(fill("the sample fill's set_render_pipeline_state"))?; - if let Some(state) = &self.depth_state { - encoder - .set_depth_stencil_state(state) - .map_err(fill("the sample fill's set_depth_stencil_state"))?; - } - encoder - .set_fragment_buffer(Some(&self.values), u64::from(layer) * self.layer_bytes, 0) - .map_err(fill("the sample fill's set_fragment_buffer"))?; - encoder - .set_fragment_buffer(Some(&self.shape), 0, 1) - .map_err(fill("the sample fill's set_fragment_buffer"))?; - encoder - .draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0) - .map_err(fill("the sample fill's draw_primitives"))?; - encoder - .end_encoding() - .map_err(fill("the sample fill's end_encoding"))?; - } - Ok(()) - } -} - -/// The multisampled texture of `literal` on `device`, made as the Metal oracle makes it: its -/// type, pixel format, extent and samples, `Private` (Metal keeps no multisampled texture in -/// shared memory), `usage` and `RenderTarget`; with the fill that writes the literal's bytes into -/// it, for the command buffer that reads it. -pub fn multisampled_texture_with( - device: &Device, - literal: &LiteralTexture, - usage: TextureUsage, -) -> Result<(Texture, SampleFill), CaseError> { - let layout = literal.layout()?; - let mut descriptor = texture_descriptor(literal, usage | TextureUsage::RENDER_TARGET)?; - descriptor.sample_count = layout.sample_count.into(); - descriptor.resource_options = ResourceOptions::private(); - let texture = device - .new_texture(&descriptor) - .map_err(CaseError::runtime(format!( - "texture {}: new_texture", - literal.binding - )))?; - let fill = SampleFill::new(device, &texture, literal.format, layout, &literal.bytes)?; - Ok((texture, fill)) -} - -/// One attachment's readback, encoded: the words its dispatch writes, read once the command -/// buffer completed ([`SampleReadback::bytes`]). -pub struct SampleReadback { - words: Buffer, - read: SampleRead, - extent: [u32; 2], - samples: u32, -} - -/// The unsigned view of a color attachment of `format` with the same components and bits, the -/// fixture's kernel that packs a texel of it into words, and how many words it writes. Only the -/// formats the fill writes ([`fill_function`]) are read. -fn color_view(format: PixelFormat) -> Result<(PixelFormat, &'static str, usize), String> { - use PixelFormat as P; - Ok(match format { - P::R8Unorm => (P::R8Uint, "rt6_read_words1", 1), - P::RGBA8Unorm | P::RGBA8Uint | P::RGBA8Sint => (P::RGBA8Uint, "rt6_read_bytes4", 1), - P::R16Float | P::R16Uint => (P::R16Uint, "rt6_read_words1", 1), - P::RG16Float => (P::RG16Uint, "rt6_read_halves2", 1), - P::RGBA16Float | P::RGBA16Uint | P::RGBA16Sint => (P::RGBA16Uint, "rt6_read_halves4", 2), - P::R32Float | P::R32Uint | P::R32Sint => (P::R32Uint, "rt6_read_words1", 1), - P::RG32Float => (P::RG32Uint, "rt6_read_words2", 2), - P::RGBA32Float | P::RGBA32Uint | P::RGBA32Sint => (P::RGBA32Uint, "rt6_read_words4", 4), - other => { - return Err(format!( - "a multisampled {other:?} attachment, which nothing fills" - )) - } - }) -} - -/// Encode into `command_buffer` the readback of every sample of `texture`, a multisampled -/// attachment of `extent` and `samples`, read as `read`. -pub fn encode( - device: &Device, - command_buffer: &CommandBuffer, - texture: &Texture, - read: SampleRead, - extent: [u32; 2], - samples: u32, -) -> Result { - let (source, kernel) = match read { - SampleRead::Color(_) => { - let (view, kernel, words) = color_view(texture.pixel_format())?; - if words != read.words() { - return Err(format!( - "{kernel} writes {words} words of a texel, the oracle's view {}", - read.words() - ) - .into()); - } - let view = texture - .new_texture_view(view) - .map_err(CaseError::runtime(format!("{kernel}: new_texture_view")))?; - (view, kernel) - } - SampleRead::Depth => (texture.clone(), "rt6_read_depth"), - SampleRead::Stencil => (texture.clone(), "rt6_read_stencil"), - }; - encode_through( - device, - command_buffer, - &source, - kernel, - read, - extent, - samples, - ) -} - -/// Encode into `command_buffer` the readback of every sample of `source`, a multisampled texture -/// or a view of one, of `extent` and `samples`, by the fixture's kernel `name`, which writes the -/// words of `read`. -pub fn encode_through( - device: &Device, - command_buffer: &CommandBuffer, - source: &Texture, - name: &'static str, - read: SampleRead, - extent: [u32; 2], - samples: u32, -) -> Result { - let function = library(device)? - .new_function_with_name(name) - .map_err(CaseError::helper(format!("function {name}")))?; - let pipeline = device - .new_compute_pipeline_state_with_function(&function, &PipelineOptions::default()) - .map_err(CaseError::helper(format!( - "{name}: new_compute_pipeline_state" - )))?; - let length = readback_bytes(extent, samples, read)? as u64; - let words = device - .new_buffer(length, ResourceOptions::shared()) - .map_err(CaseError::runtime(format!("{name}: new_buffer")))?; - let shape = shape(device, extent[0], samples)?; - let mut encoder = command_buffer - .compute_command_encoder() - .map_err(CaseError::runtime(format!( - "{name}: compute_command_encoder" - )))?; - let call = |what: &str| CaseError::runtime(format!("{name}: {what}")); - encoder - .set_compute_pipeline_state(&pipeline) - .map_err(call("set_compute_pipeline_state"))?; - encoder - .set_texture(Some(source), 0) - .map_err(call("set_texture"))?; - encoder - .set_buffer(Some(&words), 0, 0) - .map_err(call("set_buffer"))?; - encoder - .set_buffer(Some(&shape), 0, 1) - .map_err(call("set_buffer"))?; - // One thread per sample, one per threadgroup: no grid edge to guard. - encoder - .dispatch_threadgroups( - Size::new(extent[0].into(), extent[1].into(), samples.into()), - Size::new(1, 1, 1), - ) - .map_err(call("dispatch_threadgroups"))?; - encoder.end_encoding().map_err(call("end_encoding"))?; - Ok(SampleReadback { - words, - read, - extent, - samples, - }) -} - -impl SampleReadback { - /// Every sample's bytes in the attachment layout, once the command buffer completed. - pub fn bytes(&self) -> Result, CaseError> { - let length = readback_bytes(self.extent, self.samples, self.read)? as u64; - let words = read_buffer(&self.words, 0, length)?; - Ok(unpack_words(&words, self.extent, self.samples, self.read)?) - } -} diff --git a/crates/metal2vulkan-validation/src/candidate/unadvertised_stage.rs b/crates/metal2vulkan-validation/src/candidate/unadvertised_stage.rs index 4ab829a54..1ed046687 100644 --- a/crates/metal2vulkan-validation/src/candidate/unadvertised_stage.rs +++ b/crates/metal2vulkan-validation/src/candidate/unadvertised_stage.rs @@ -15,11 +15,9 @@ //! "`` is used in `` which is not supported in subgroupSupportedStages //! (``).", read in Vulkan-ValidationLayers v1.4.357 (its library's strings), with the //! stages `[VK_SHADER_STAGE_VERTEX_BIT]` at `vkCreateShaderModule`, as the lanes saw it, or -//! `VK_SHADER_STAGE_VERTEX_BIT`. A sink passes it only where the device's profile takes the -//! deviation: the runtime lanes' sink once the runtime announced -//! `Degradation::UnadvertisedVertexSimdgroups` (`runtime_case.rs`), the executor's context where -//! the profile it opened takes the deviation (`platform/device.rs`). Every other subgroup-stage -//! message, and this one anywhere else, still fails. +//! `VK_SHADER_STAGE_VERTEX_BIT`. The executor's context's sink passes it only where the profile it +//! opened takes the deviation (`platform/device.rs`). Every other subgroup-stage message, and this +//! one anywhere else, still fails. /// The message's id name. pub(crate) const ID_NAME: &str = "VUID-RuntimeSpirv-None-06343"; diff --git a/crates/metal2vulkan-validation/src/candidate/unsupported_set.rs b/crates/metal2vulkan-validation/src/candidate/unsupported_set.rs index cc117e0aa..a6ad766be 100644 --- a/crates/metal2vulkan-validation/src/candidate/unsupported_set.rs +++ b/crates/metal2vulkan-validation/src/candidate/unsupported_set.rs @@ -4,8 +4,8 @@ //! MoltenVK answers the query `sum of descriptorCount < maxPerSetDescriptors` (1212 on Apple's //! GPUs), though it encodes an update-after-bind set in a Metal argument buffer and runs one of //! 65536 elements and more as Metal runs the argument buffer -//! (`RuntimeDriverDefect::SetLayoutSupportUnderstated`). The runtime makes a heap's set 1 there -//! past that answer, announced (`Degradation::SetPastLayoutSupport`). The layer asks the query for +//! (`RuntimeDriverDefect::SetLayoutSupportUnderstated`). The executor's context makes a heap's +//! set 1 there past that answer (`platform/device.rs`). The layer asks the query for //! every layout past `maxPerSetDescriptors` and reports one it refuses, as Vulkan says it must //! (`VUID-vkCreateDescriptorSetLayout-support-09582`, "If the descriptor layout exceeds the limits //! reported through the physical device limits, then vkGetDescriptorSetLayoutSupport must have @@ -17,9 +17,9 @@ //! vkGetDescriptorSetLayoutSupport which reported this layout is not supported", read in //! Vulkan-ValidationLayers 1.4.363 (`CoreChecks::ValidateDescriptorSetLayoutSupport`), at //! `vkCreateDescriptorSetLayout`, as the lanes saw it on MoltenVK 1.4.2, alone or after the -//! layer's note on its last report (`duplicate_message_limit`). The runtime lanes' sink -//! passes it only once the runtime announced `Degradation::SetPastLayoutSupport` -//! (`runtime_case.rs`). Every other message, and this one before the notice, still fails. +//! layer's note on its last report (`duplicate_message_limit`). The executor's context's sink +//! passes it only on a device whose driver runs such a layout (`platform/device.rs`). Every other +//! message, and this one anywhere else, still fails. /// The message's id name. pub(crate) const ID_NAME: &str = "VUID-vkCreateDescriptorSetLayout-support-09582"; diff --git a/crates/metal2vulkan-validation/src/executor_contract.rs b/crates/metal2vulkan-validation/src/executor_contract.rs index e5e66432f..1ed3b4848 100644 --- a/crates/metal2vulkan-validation/src/executor_contract.rs +++ b/crates/metal2vulkan-validation/src/executor_contract.rs @@ -685,6 +685,7 @@ pub fn unsupported_source_requirements( ) -> BTreeSet { let mut requirements = unsupported_reflection_requirements(reflection); requirements.extend(engine_source_requirements(reflection)); + requirements.extend(mesh::mesh_pipeline_requirement(reflection)); requirements.extend(rate_map::rate_map_placement_requirement( source_ll, reflection, )); @@ -843,7 +844,9 @@ pub fn checked_requirements( /// Why the executor pair cannot evidence a case with `requirements`, or `None`: one that stops the /// Metal oracle leaves no observation to compare with, and one that stops the candidate leaves -/// nothing to compare. A case both run is checkable. A requirement whose limit is Metal's own is +/// nothing to compare, but for a requirement whose cases stay Metal-qualified +/// ([`ToolingRequirement::qualifies_on_metal`]): such a case is checkable on Metal alone, and the +/// candidate refuses it. A case both run is checkable. A requirement whose limit is Metal's own is /// named as such: no tooling can give the oracle that case. pub fn evidence_gap(requirements: &BTreeSet) -> Option { fn joined(requirements: impl IntoIterator) -> String { @@ -853,12 +856,6 @@ pub fn evidence_gap(requirements: &BTreeSet) -> Option>() .join(",") } - let names = |executor| { - joined(ToolingRequirement::stopping( - requirements.iter().copied(), - executor, - )) - }; let (metal_limit, tooling): (Vec<_>, Vec<_>) = ToolingRequirement::stopping(requirements.iter().copied(), Executor::MetalOracle) .into_iter() @@ -880,7 +877,11 @@ pub fn evidence_gap(requirements: &BTreeSet) -> Option bool { }) } +/// [`ToolingRequirement::MeshRenderPipeline`] for a row or case whose entry's reflection is +/// `reflection`, where it is an object or mesh function: the engine's candidate draws no mesh +/// render pipeline. Classification and the case checker read it with the source's other +/// requirements (`executor_contract::unsupported_source_requirements`). +pub fn mesh_pipeline_requirement(reflection: &ShaderInterface) -> Option { + matches!(reflection.stage, ShaderStage::Object | ShaderStage::Mesh) + .then_some(ToolingRequirement::MeshRenderPipeline) +} + /// The mesh requirements of a row or case (`draw` `None` for a row) whose entry's reflection is /// `reflection`: [`ToolingRequirement::MeshCompanion`] where [`missing_stages`] names a stage. /// Empty for any other stage. An object function's threadgroup memory needs nothing: both @@ -550,5 +562,17 @@ mod tests { let reflection = inspect(&kernel, Stage::Kernel, "copy_word", &[]).unwrap(); assert_eq!(reflection.mesh_stage, None); assert!(mesh_requirements(&kernel, &reflection, None).is_empty()); + assert_eq!(mesh_pipeline_requirement(&reflection), None); + for (stage, entry) in [ + (Stage::Object, "mesh_draws_object"), + (Stage::Mesh, "mesh_draws_mesh"), + ] { + let (_, reflection) = reflected(&module, stage, entry); + assert_eq!( + mesh_pipeline_requirement(&reflection), + Some(ToolingRequirement::MeshRenderPipeline), + "{entry}" + ); + } } } diff --git a/crates/metal2vulkan-validation/src/gpu.rs b/crates/metal2vulkan-validation/src/gpu.rs index ed9678caa..71d941dd6 100644 --- a/crates/metal2vulkan-validation/src/gpu.rs +++ b/crates/metal2vulkan-validation/src/gpu.rs @@ -46,11 +46,10 @@ mod tests { } /// Every device open goes through one of the functions that check the hang tripwire first: - /// validation's Vulkan context, the Metal platform, the device validation makes through the - /// runtime (`candidate::runtime_case::open_device`, the executor's runtime path's), and the new - /// runtime's device in the player and in the replay tests, each after the tripwire check in its - /// own file. A new raw open anywhere else in the crate fails here, before it can run, and so - /// does a new-runtime open ahead of its check. + /// validation's Vulkan context, the Metal platform, and the new runtime's device in the player + /// and in the replay tests, each after the tripwire check in its own file. A new raw open + /// anywhere else in the crate fails here, before it can run, and so does a new-runtime open + /// ahead of its check. #[test] fn device_opens_exist_only_behind_the_tripwire_check() { let root = metal2vulkan_devtools::validation_dir(); @@ -64,9 +63,6 @@ mod tests { concat!(".create_", "instance("), concat!(".enumerate_", "physical_devices("), concat!(".create_", "device("), - // The runtime's own device creation (`metal2vulkan_runtime`). - concat!("::system_", "default"), - concat!("Device::", "all"), // The new runtime's device creation (`metal2vulkan_rt`). concat!("metal2vulkan_rt::Device", "::new("), ]; @@ -75,14 +71,12 @@ mod tests { ("src/candidate/platform/device.rs", opens[3], 1), ("src/candidate/platform/device.rs", opens[4], 1), ("src/metal/platform.rs", opens[0], 1), - ("src/candidate/runtime_case.rs", opens[5], 1), - ("src/candidate/runtime_case.rs", opens[6], 1), // The new runtime's device: the player's and the replay tests'. - ("src/bin/command-replay.rs", opens[7], 1), - ("src/replay/rt_replay.rs", opens[7], 1), + ("src/bin/command-replay.rs", opens[5], 1), + ("src/replay/rt_replay.rs", opens[5], 1), ]; let checked = concat!("refuse_if", "_tripped("); - for (file, open, _) in allowed.iter().filter(|(_, open, _)| *open == opens[7]) { + for (file, open, _) in allowed.iter().filter(|(_, open, _)| *open == opens[5]) { let text = std::fs::read_to_string(root.join(file)).unwrap(); let check = text.find(checked); assert!( diff --git a/crates/metal2vulkan-validation/src/gpu/wait.rs b/crates/metal2vulkan-validation/src/gpu/wait.rs index 52006b8de..6d17b244c 100644 --- a/crates/metal2vulkan-validation/src/gpu/wait.rs +++ b/crates/metal2vulkan-validation/src/gpu/wait.rs @@ -321,47 +321,6 @@ pub(crate) mod vulkan { } } -/// Bounded waits on the Metal-like runtime's command buffers (`metal2vulkan_runtime`): the -/// engine executor's runtime path. -pub(crate) mod runtime { - use super::{settle, CompletionSource, SubmissionBackend, WaitOutcome}; - use metal2vulkan_runtime::{CommandBuffer, CommandBufferError, CommandBufferStatus}; - use std::time::Duration; - - struct Committed<'a>(&'a CommandBuffer); - - impl CompletionSource for Committed<'_> { - fn wait(&mut self, timeout: Duration) -> WaitOutcome { - if self - .0 - .wait_until_completed_for(timeout.min(super::MAX_WAIT_TIMEOUT)) - .is_err() - { - return WaitOutcome::TimedOut; - } - match (self.0.status(), self.0.error()) { - (CommandBufferStatus::Completed, _) => WaitOutcome::Completed, - (_, Some(CommandBufferError::DeviceLost)) => { - WaitOutcome::SuspectedFault("the command buffer lost its device".into()) - } - (status, error) => { - WaitOutcome::Failed(format!("the command buffer ended {status:?}: {error:?}")) - } - } - } - } - - /// Wait for `command_buffer`, committed by `operation`, under the hang protocol. Returns - /// only once its work is no longer in flight. - pub(crate) fn wait_for_command_buffer( - command_buffer: &CommandBuffer, - backend: SubmissionBackend, - operation: &str, - ) -> Result<(), String> { - settle(&mut Committed(command_buffer), backend, operation) - } -} - /// Bounded waits on the new runtime's command buffers (`metal2vulkan_rt`): the replay player's /// backend over it. The runtime's own wait has no bound, so the wait is on the command buffer's /// completed handler, after the queue's wait hint has sent it. How the command buffer ended is the diff --git a/crates/metal2vulkan-validation/src/lib.rs b/crates/metal2vulkan-validation/src/lib.rs index aa83001c7..b30592287 100644 --- a/crates/metal2vulkan-validation/src/lib.rs +++ b/crates/metal2vulkan-validation/src/lib.rs @@ -5,7 +5,6 @@ pub mod acceptance; pub mod air; -pub mod air_library; pub mod air_writer; pub mod authored_compile; pub mod bitcode_audit; diff --git a/crates/metal2vulkan-validation/src/mesh_cases.rs b/crates/metal2vulkan-validation/src/mesh_cases.rs index 2c7ba881f..13df0c99b 100644 --- a/crates/metal2vulkan-validation/src/mesh_cases.rs +++ b/crates/metal2vulkan-validation/src/mesh_cases.rs @@ -1,7 +1,6 @@ //! Object and mesh cases over the owned fixtures `engine/mesh_draws.ll` and //! `engine/mesh_barrier.ll`, each with what Metal drew for it: the words of Metal's own probe of -//! the same functions (`runtime_lane::mesh_draws`'s answers, measured on the M3 Max and an M4 -//! alike), each mesh threadgroup covering one pixel of an 8x8 pass of two `RGBA32Uint` targets +//! the same functions (measured on the M3 Max and an M4 alike), each mesh threadgroup covering one pixel of an 8x8 pass of two `RGBA32Uint` targets //! with the builtins it read, and the device write the M3 Max measured with rasterization off. A //! mesh case observed through the generated observer fragment reads what the fixture's own //! fragment function writes to its first target, so Metal's answer is the same words. An object @@ -9,8 +8,7 @@ //! ([`crate::case::MeshObservation::Launch`]), and a mesh case under a generated object function //! draws the payload that function writes ([`crate::case::ObjectLaunch`]): those words follow from //! the fixture's source, and the Metal executor's test holds them to what the M3 Max drew. -//! The Metal executor's tests (`metal::tests::mesh_draws`) hold the oracle to them, and the engine -//! candidate's (`candidate::engine::runtime_run::tests`) hold the runtime's mesh path to them. +//! The Metal executor's tests (`metal::tests::mesh_draws`) hold the oracle to them. use crate::case::{AuthoredCase, Stage}; use crate::source::SourceRow; diff --git a/crates/metal2vulkan-validation/src/observation.rs b/crates/metal2vulkan-validation/src/observation.rs index 2c1fd4ba9..cb2632f55 100644 --- a/crates/metal2vulkan-validation/src/observation.rs +++ b/crates/metal2vulkan-validation/src/observation.rs @@ -5,11 +5,10 @@ use crate::executor_contract::out_of_bounds::OutOfBoundsRun; use crate::hash::sha256_bytes; use crate::observation_contract::ComparisonClass; use base64::Engine as _; -use metal2vulkan_runtime::Degradation; use serde::{Deserialize, Serialize}; /// The product's source fingerprint (`validation/product_fingerprint.rs`: the translator's sources, -/// then the runtime crate's, and the dev-tools crate's, which assemble the public cases' bitcode). +/// then the dev-tools crate's, which assemble the public cases' bitcode). /// Every candidate row's translator fingerprint is derived from it /// (`candidate::engine::engine_fingerprint`), so a row is current only for this product. pub const TRANSLATOR_FINGERPRINT: &str = env!("METAL2VULKAN_PRODUCT_FINGERPRINT"); @@ -177,10 +176,6 @@ impl ReferenceGap { } } -/// The member of a candidate row's `environment` that holds the codes of the degrade notices its -/// runtime device delivered ([`Degradation::code`]): a run through `metal2vulkan_runtime`. -pub const RUNTIME_DEGRADES: &str = "runtime_degrades"; - #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct CandidateObservation { @@ -562,18 +557,6 @@ impl CandidateObservation { .decode(&dependencies.metal.output_b64) .is_ok_and(|golden| self.status_holds(dependencies.case, &golden)) } - - /// The degradations the row's run announced ([`RUNTIME_DEGRADES`]), read through the - /// runtime's closed vocabulary ([`Degradation::from_code`]): a code it does not know (a - /// retired kind's) is none of them. - pub fn announced_degradations(&self) -> impl Iterator + '_ { - self.environment - .get(RUNTIME_DEGRADES) - .and_then(serde_json::Value::as_array) - .into_iter() - .flatten() - .filter_map(|code| Degradation::from_code(code.as_str()?)) - } } pub(crate) fn validate_hash(field: &str, value: &str) -> Result<(), String> { diff --git a/crates/metal2vulkan-validation/src/replay/tests.rs b/crates/metal2vulkan-validation/src/replay/tests.rs index 3a0aea43c..2a7d795c1 100644 --- a/crates/metal2vulkan-validation/src/replay/tests.rs +++ b/crates/metal2vulkan-validation/src/replay/tests.rs @@ -1,5 +1,5 @@ //! The stream format, the address map and the player's order, on a backend that only keeps what it -//! is asked (no device). The runtime backends' tests are device tests (`runtime_lane`). +//! is asked (no device). The runtime backend's tests are device tests (`replay::rt_replay`). use super::addresses::AddressMap; use super::compare::{compare_plays, shown_differences}; diff --git a/crates/metal2vulkan-validation/src/requirement.rs b/crates/metal2vulkan-validation/src/requirement.rs index 0917b03f9..8e51e6c36 100644 --- a/crates/metal2vulkan-validation/src/requirement.rs +++ b/crates/metal2vulkan-validation/src/requirement.rs @@ -123,6 +123,16 @@ pub enum ToolingRequirement { /// Metal holds them and stops there; on a device with it, it runs. A case's data on the /// executing device raises it, never a source's structure, so no census row carries it. DepthOutsideUnitRange, + /// An object or mesh function's row or case (`executor_contract::mesh`), or a case that runs a + /// pipeline template of one: the engine's candidate draws no mesh render pipeline. The Metal + /// oracle draws it, so a case of it stays Metal-qualified ([`Self::qualifies_on_metal`]). + MeshRenderPipeline, + /// A replayed pipeline template the engine's candidate does not replay + /// (`candidate::engine::replay_templates`): a compute template that binds more than buffers + /// and threadgroup memory or runs a stage input, or a render template that is not a + /// rasterization-disabled vertex function binding buffers only. A case's templates raise it, + /// never a source's structure, so no census row carries it. + ReplayedTemplateResources, } /// Every executor (the requirement leaves no case to author, or none to observe). @@ -130,7 +140,7 @@ const AUTHORING: &[Executor] = &Executor::ALL; const ENGINE: &[Executor] = &[Executor::EngineCandidate]; impl ToolingRequirement { - pub const ALL: [Self; 23] = [ + pub const ALL: [Self; 25] = [ Self::FunctionConstantLiteral, Self::VertexAttributeLiteral, Self::TessellationAttributeLiteral, @@ -154,6 +164,8 @@ impl ToolingRequirement { Self::KernelMinLodClamp, Self::MeshCompanion, Self::DepthOutsideUnitRange, + Self::MeshRenderPipeline, + Self::ReplayedTemplateResources, ]; pub const fn as_str(self) -> &'static str { @@ -183,6 +195,8 @@ impl ToolingRequirement { Self::KernelMinLodClamp => "kernel_min_lod_clamp", Self::MeshCompanion => "mesh_companion", Self::DepthOutsideUnitRange => "depth_outside_unit_range", + Self::MeshRenderPipeline => "mesh_render_pipeline", + Self::ReplayedTemplateResources => "replayed_template_resources", } } @@ -201,7 +215,9 @@ impl ToolingRequirement { /// implementation's private layout where the engine's module decodes this crate's, and a /// depth outside `[0, 1]` a case gives a depth image, which its executor raises only on a /// device without `VK_EXT_depth_range_unrestricted` - /// ([`ToolingRequirement::DepthOutsideUnitRange`]). + /// ([`ToolingRequirement::DepthOutsideUnitRange`]), and a mesh render pipeline or a replayed + /// template it does not draw or replay ([`ToolingRequirement::MeshRenderPipeline`], + /// [`ToolingRequirement::ReplayedTemplateResources`]). /// /// The requirements that stopped only the old engine's candidate were retired with it. pub const fn stops(self) -> &'static [Executor] { @@ -228,10 +244,21 @@ impl ToolingRequirement { | Self::VertexDepthStencilAttachment | Self::RasterizationDisabledRenderTarget | Self::RasterizationRateMapPlacement - | Self::DepthOutsideUnitRange => ENGINE, + | Self::DepthOutsideUnitRange + | Self::MeshRenderPipeline + | Self::ReplayedTemplateResources => ENGINE, } } + /// Whether a case carrying this requirement is still a case to keep: the Metal oracle runs it + /// and its observation is evidence for a candidate that runs the family again, so the checker + /// accepts it with no candidate (`executor_contract::evidence_gap`), and the engine's candidate + /// refuses it, typed. Only [`ToolingRequirement::MeshRenderPipeline`]: its cases are qualified + /// on Metal. + pub const fn qualifies_on_metal(self) -> bool { + matches!(self, Self::MeshRenderPipeline) + } + /// Whose limit this requirement records. Every requirement is this crate's tooling's except /// [`ToolingRequirement::KernelMinLodClamp`], which Apple's compiler cannot build a pipeline /// for. @@ -363,15 +390,28 @@ mod tests { } } - /// The mesh render pipeline's requirement: both executors draw one, an object function's - /// threadgroup memory among it, so only a stage nothing generates stops them - /// (`mesh_companion`), this crate's gap, never Metal's, which keeps the census open. + /// The mesh render pipeline's requirements: a stage nothing generates stops both executors + /// (`mesh_companion`), and the engine's candidate draws none (`mesh_render_pipeline`), whose + /// cases stay Metal-qualified. Both are this crate's gaps, never Metal's, which keep the census + /// open. #[test] fn mesh_requirements_stop_the_executors_that_do_not_draw_them_yet() { let requirement = ToolingRequirement::MeshCompanion; assert_eq!(requirement.stops(), Executor::ALL); assert_eq!(requirement.limit(), Limit::Tooling, "{requirement}"); assert!(requirement.blocks_closure(), "{requirement}"); + assert!(!requirement.qualifies_on_metal(), "{requirement}"); + let requirement = ToolingRequirement::MeshRenderPipeline; + assert_eq!(requirement.stops(), [Executor::EngineCandidate]); + assert!(requirement.blocks_closure(), "{requirement}"); + assert!(requirement.qualifies_on_metal(), "{requirement}"); + assert_eq!( + ToolingRequirement::ALL + .into_iter() + .filter(|requirement| requirement.qualifies_on_metal()) + .collect::>(), + [ToolingRequirement::MeshRenderPipeline] + ); } /// Every requirement stops some executor, and an executor's name is as stable as a diff --git a/crates/metal2vulkan-validation/src/translation_audit.rs b/crates/metal2vulkan-validation/src/translation_audit.rs index 9670f5ef6..66996431e 100644 --- a/crates/metal2vulkan-validation/src/translation_audit.rs +++ b/crates/metal2vulkan-validation/src/translation_audit.rs @@ -19,8 +19,7 @@ use std::sync::OnceLock; /// The product's source fingerprint (`validation/product_fingerprint.rs`): the translator's /// manifest, build inputs, and exactly the files it can compile or read (`build_support:: -/// product_hash`; a test-only module is not one), then the runtime crate's the same way, then the -/// dev-tools crate's sources, whose `llvm-as` assembler gives a public row its bitcode. No file +/// product_hash`; a test-only module is not one), then the dev-tools crate's sources, whose `llvm-as` assembler gives a public row its bitcode. No file /// under `validation/` feeds it. const PRODUCT_FINGERPRINT: &str = env!("METAL2VULKAN_PRODUCT_FINGERPRINT"); @@ -761,11 +760,6 @@ mod tests { write("metal2vulkan/build.rs", "fn main() {}\n"); write("metal2vulkan/build_support.rs", "// fingerprint inputs\n"); write("metal2vulkan/src/lib.rs", "pub fn translate() {}\n"); - write( - "metal2vulkan-runtime/Cargo.toml", - "[package]\nname = \"runtime\"\n", - ); - write("metal2vulkan-runtime/src/lib.rs", "pub fn submit() {}\n"); write( "metal2vulkan-devtools/Cargo.toml", "[package]\nname = \"devtools\"\n", @@ -850,17 +844,6 @@ mod tests { ); write("metal2vulkan-devtools/src/lib.rs", "pub fn assemble() {}\n"); assert_eq!(key(product()).fingerprint(), before.fingerprint()); - write( - "metal2vulkan-runtime/src/lib.rs", - "pub fn submit() { /* edited */ }\n", - ); - assert_ne!( - key(product()).fingerprint(), - before.fingerprint(), - "a runtime edit is an input" - ); - write("metal2vulkan-runtime/src/lib.rs", "pub fn submit() {}\n"); - assert_eq!(key(product()).fingerprint(), before.fingerprint()); write( "metal2vulkan/src/lib.rs", "pub fn translate() { /* edited */ }\n", diff --git a/crates/metal2vulkan-validation/src/triage.rs b/crates/metal2vulkan-validation/src/triage.rs index 36cca363c..196bee1c1 100644 --- a/crates/metal2vulkan-validation/src/triage.rs +++ b/crates/metal2vulkan-validation/src/triage.rs @@ -14,7 +14,7 @@ use std::path::Path; /// bumps it says what changed; this comment keeps no history. macro_rules! analyzer_version { () => { - "structural-triage-v82" + "structural-triage-v83" }; } @@ -1947,8 +1947,6 @@ entry: write("metal2vulkan/build.rs", "fn main() {}\n"); write("metal2vulkan/build_support.rs", "\n"); write("metal2vulkan/src/lib.rs", "pub fn translate() {}\n"); - write("metal2vulkan-runtime/Cargo.toml", "[package]\n"); - write("metal2vulkan-runtime/src/lib.rs", "pub fn submit() {}\n"); write("metal2vulkan-devtools/Cargo.toml", "[package]\n"); write("metal2vulkan-devtools/src/lib.rs", "pub fn assemble() {}\n"); for input in &inputs { @@ -2004,17 +2002,6 @@ entry: ); write("metal2vulkan-devtools/src/lib.rs", "pub fn assemble() {}\n"); assert_eq!(key(analyzer_version!()), current); - write( - "metal2vulkan-runtime/src/lib.rs", - "pub fn submit() { /* edited */ }\n", - ); - assert_ne!( - key(analyzer_version!()), - current, - "a runtime edit invalidates" - ); - write("metal2vulkan-runtime/src/lib.rs", "pub fn submit() {}\n"); - assert_eq!(key(analyzer_version!()), current); write( "metal2vulkan/src/lib.rs", "pub fn translate() { /* edited */ }\n", @@ -2259,6 +2246,11 @@ define void @{name}(ptr addrspace(2) %ab, ptr addrspace(1) %out) {{ .contains(&ToolingRequirement::MeshCompanion); let draw = classified.mesh_draw.expect("a mesh draw"); assert_eq!(unresolved, !draw.missing.is_empty(), "{entry}"); + // The engine's candidate draws no mesh render pipeline. + assert!( + (classified.tooling_requirements).contains(&ToolingRequirement::MeshRenderPipeline), + "{entry}" + ); draw }; assert_eq!( @@ -2290,6 +2282,7 @@ define void @{name}(ptr addrspace(2) %ab, ptr addrspace(1) %out) {{ ); let fragment = classify(&entry_of("engine/mesh_draws.ll", "mesh_draws_fragment")).unwrap(); assert_eq!(fragment.mesh_draw, None); + assert!(!(fragment.tooling_requirements).contains(&ToolingRequirement::MeshRenderPipeline)); } /// A vertex function whose only effect is the indexed draw it encodes is observed by executing diff --git a/crates/metal2vulkan-validation/src/worker/alloc.rs b/crates/metal2vulkan-validation/src/worker/alloc.rs index 6d9c42d90..630bb94d8 100644 --- a/crates/metal2vulkan-validation/src/worker/alloc.rs +++ b/crates/metal2vulkan-validation/src/worker/alloc.rs @@ -231,12 +231,7 @@ pub fn release_free_memory() { } } -// Built with `--cfg m2v_system_alloc`, the lib test binary keeps the system allocator, as a -// consumer's process does, so the runtime lanes' cost measurements (`draw_costs`, `commit_costs`, -// `frame_costs`) pay no counting: each counted allocation takes a compare-and-swap loop and two -// shared atomic maxima, 17% of the draw path's samples. Its counting tests are -// left out there. -#[cfg(all(test, not(m2v_system_alloc)))] +#[cfg(test)] mod tests { use super::*; diff --git a/crates/metal2vulkan-validation/tests/integration/main.rs b/crates/metal2vulkan-validation/tests/integration/main.rs index a737c34f4..d657a45fd 100644 --- a/crates/metal2vulkan-validation/tests/integration/main.rs +++ b/crates/metal2vulkan-validation/tests/integration/main.rs @@ -42,5 +42,4 @@ mod public_entry_rows; mod published_crates; mod replay_completion_mark; mod replay_range; -mod swept_scratch; mod translation_l3_stage; diff --git a/crates/metal2vulkan-validation/tests/integration/swept_scratch.rs b/crates/metal2vulkan-validation/tests/integration/swept_scratch.rs deleted file mode 100644 index 87686cfa0..000000000 --- a/crates/metal2vulkan-validation/tests/integration/swept_scratch.rs +++ /dev/null @@ -1,47 +0,0 @@ -//! Where a lane's shader cache lives, and why that is the whole of the fix. -//! -//! A [`ScratchCache`] is removed when it drops, which covers a return and an unwind and covers -//! neither a kill nor an exit that runs no destructor -- and lane processes are killed: a run gets -//! cancelled, and the memory cap kills a worker and its whole process group. The caches used to be -//! `$TMPDIR/m2v-lane-shader-cache---`, named for a process and recognisable to -//! nothing, so each one a killed lane left stayed there for good: 900 to 2200 of them on a host. -//! -//! The fix is not a second removal somewhere; it is the path. A cache in the project's scratch -//! root carries a lock the kernel releases when its owner dies, so the next run of any suite -//! removes it, and removes no live run's -//! ([`metal2vulkan_devtools::scratch`], whose own tests hold the sweep itself). - -use metal2vulkan_validation::candidate::runtime_case::ScratchCache; - -/// **A lane's shader cache is a path the next run can recognise**: in the scratch root, with a -/// lock beside it. Put it back under the OS temp directory on its own and this test fails naming -/// the directory it finds there, because nothing could ever sweep it. -#[test] -fn a_lane_shader_cache_lies_in_the_swept_scratch_root() { - let root = metal2vulkan_devtools::scratch::root(); - let cache = ScratchCache::new().expect("a shader cache path"); - - assert_eq!( - cache.path().parent(), - Some(root.as_path()), - "the lane's shader cache {} is not in the scratch root {}, so no run can sweep it after \ - this one is killed", - cache.path().display(), - root.display() - ); - - let mut lock = cache.path().as_os_str().to_owned(); - lock.push(".lock"); - assert!( - std::path::Path::new(&lock).is_file(), - "{} has no lock beside it, so a sweep cannot tell its owner from a dead one", - cache.path().display() - ); - - // The device makes it, so the path is a path and nothing else until then. - assert!( - !cache.path().exists(), - "{} was created, so it is not the empty cache a lane measures against", - cache.path().display() - ); -} diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 5debd9e7b..41c90d616 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -95,7 +95,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 556; /// 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 = 2539; +pub const RUNTIME_VERSION: u32 = 2540; /// 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