diff --git a/crates/metal2vulkan-conformance/probes/dead_ordered_and_unattached_reads.m b/crates/metal2vulkan-conformance/probes/dead_ordered_and_unattached_reads.m index f7512e5f0..00762f164 100644 --- a/crates/metal2vulkan-conformance/probes/dead_ordered_and_unattached_reads.m +++ b/crates/metal2vulkan-conformance/probes/dead_ordered_and_unattached_reads.m @@ -1,9 +1,8 @@ // What plain Metal makes of a fragment function that declares an input whose read its function // constant makes dead: a `[[color(0)]]` input in a raster order group, a `const device` buffer in // one, a `[[color(0)]]` input of an output in one, and a `[[color(1)]]` input of a color the -// pipeline has no pixel format for. The reference of `metal2vulkan`'s `tests::engine_dead_reads` -// and `tests::engine_color_groups`, over the -// owned fixture `engine/dfk_dead_rog` (its source is repeated here, with `color_groups`' +// pipeline has no pixel format for. The reference of `metal2vulkan`'s `tests::engine_dead_reads`, +// over the owned fixture `engine/dfk_dead_rog` (its source is repeated here, with `color_groups`' // `cg_cover`). // // Build (no cargo target needed): diff --git a/crates/metal2vulkan-conformance/src/degradation.rs b/crates/metal2vulkan-conformance/src/degradation.rs index 435f0e3cc..7269bcdb6 100644 --- a/crates/metal2vulkan-conformance/src/degradation.rs +++ b/crates/metal2vulkan-conformance/src/degradation.rs @@ -155,8 +155,6 @@ pub enum Degradation { NativeMix, /// `metal2vulkan-degrade-device-pack-conversion`. DevicePackConversion, - /// `metal2vulkan-degrade-color-attachment-groups`. - ColorAttachmentGroups, /// `metal2vulkan-degrade-tessellation-triangle-order`. TessellationTriangleOrder, /// `metal2vulkan-degrade-unmeasured-group-speculation`. @@ -262,7 +260,6 @@ impl Degradation { Degradation::NativeDot, Degradation::NativeMix, Degradation::DevicePackConversion, - Degradation::ColorAttachmentGroups, Degradation::TessellationTriangleOrder, Degradation::UnmeasuredGroupSpeculation, Degradation::NotMipmappedAnisotropicFilter, @@ -386,7 +383,6 @@ impl Degradation { Degradation::NativeDot => "metal2vulkan-degrade-native-dot", Degradation::NativeMix => "metal2vulkan-degrade-native-mix", Degradation::DevicePackConversion => "metal2vulkan-degrade-device-pack-conversion", - Degradation::ColorAttachmentGroups => "metal2vulkan-degrade-color-attachment-groups", Degradation::TessellationTriangleOrder => { "metal2vulkan-degrade-tessellation-triangle-order" } @@ -488,7 +484,6 @@ impl Degradation { PrecisionNote::NativeDot => Degradation::NativeDot, PrecisionNote::NativeMix => Degradation::NativeMix, PrecisionNote::DevicePackConversion => Degradation::DevicePackConversion, - PrecisionNote::ColorAttachmentGroups => Degradation::ColorAttachmentGroups, PrecisionNote::TessellationTriangleOrder => Degradation::TessellationTriangleOrder, PrecisionNote::UnmeasuredGroupSpeculation => Degradation::UnmeasuredGroupSpeculation, PrecisionNote::NotMipmappedAnisotropicFilter => { diff --git a/crates/metal2vulkan-runtime/src/tests/translator_fields.rs b/crates/metal2vulkan-runtime/src/tests/translator_fields.rs index 94ae19ff4..4c61a8956 100644 --- a/crates/metal2vulkan-runtime/src/tests/translator_fields.rs +++ b/crates/metal2vulkan-runtime/src/tests/translator_fields.rs @@ -102,14 +102,6 @@ const GRAPHICS_STATE: &[(&str, Verdict)] = &[ ), ("sample_mask", Applied), ("snapshot_reads", Refused(VARIANT)), - ( - "color_group", - Fact( - "cannot be stated above the floor: a group takes a device of fewer than 8 color \ - attachments or fragment outputs, and the floor's maxColorAttachments and \ - maxFragmentOutputAttachments rows (floor::limits) require 8", - ), - ), ("logic_op", Applied), ]; diff --git a/crates/metal2vulkan-validation/src/engine.rs b/crates/metal2vulkan-validation/src/engine.rs index 75443335b..93bfe8b41 100644 --- a/crates/metal2vulkan-validation/src/engine.rs +++ b/crates/metal2vulkan-validation/src/engine.rs @@ -10,21 +10,19 @@ //! error taxonomy, never a second list of reasons. use crate::l3::L3Failure; -use metal2vulkan::device::VkLimit; use metal2vulkan::device::{DevicePolicy, DeviceProfile, Requirements}; use metal2vulkan::error::{ - CanonError, Capability, Error, ErrorClass, Feature, InputError, InputErrorKind, InternalError, - InternalKind, Limit, Location, Needs, RuntimeInput, + CanonError, Capability, Error, ErrorClass, Feature, InputError, InputErrorKind, InternalKind, + Limit, Location, Needs, RuntimeInput, }; use metal2vulkan::library::{CompiledFunction, FunctionConstantValues}; use metal2vulkan::pipeline::{ - ColorGroup, CompileReport, EntryDescriptor, EntryRef, LoweringInputs, PipelineLayout, + CompileReport, EntryDescriptor, EntryRef, LoweringInputs, PipelineLayout, }; use metal2vulkan::Budget; -use metal2vulkan_air::abi::{AbiInt, OutputRole, Stage as AbiStage}; use serde::{Deserialize, Serialize}; use std::borrow::Cow; -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::time::Instant; @@ -553,10 +551,7 @@ pub fn bounded_detail(detail: &str) -> String { /// that reads `[[stage_in]]` attributes asks for its stage-input descriptor /// (`NeedsInput(StageInputDescriptor)`): it is translated again, on a fresh meter, under the one /// its AIR implies (`executor_contract::stage_inputs::implied_descriptor`), and keeps the -/// `NeedsInput` when the tool cannot derive one. A fragment function refused for writing more -/// colors than the profile draws at once is translated as the render pipeline of its own colors -/// draws it there, in color groups (`color_groups`): one module a group, each linked and checked -/// by L3. +/// `NeedsInput` when the tool cannot derive one. /// /// `deadline` is the per-attempt wall deadline of the engine's meter. Every stage runs under /// `catch_unwind`, so a panic is an outcome, never an unwind into the caller. @@ -589,117 +584,27 @@ pub fn translate_new_unvalidated( deadline: Option, ) -> (Attempt, Option) { let descriptor = EntryDescriptor::new(bitcode, EntryRef::Name(entry)); - translate_modules_unvalidated(profile, deadline, |budget| { - let (compiled, report) = - match profile.compile_entry(&descriptor, &LoweringInputs::new(), budget) { - (Err(e @ Error::NeedsInput(RuntimeInput::StageInputDescriptor { .. })), report) => { - match crate::executor_contract::stage_inputs::implied_descriptor( - bitcode, - entry, - &FunctionConstantValues::defaults(), - ) { - Ok(Some(stage_input)) => { - let mut inputs = LoweringInputs::new(); - inputs.stage_input = Some(stage_input); - profile.compile_entry(&descriptor, &inputs, budget) - } - Ok(None) | Err(_) => (Err(e), report), + translate_unvalidated(profile, deadline, |budget| { + match profile.compile_entry(&descriptor, &LoweringInputs::new(), budget) { + (Err(e @ Error::NeedsInput(RuntimeInput::StageInputDescriptor { .. })), report) => { + match crate::executor_contract::stage_inputs::implied_descriptor( + bitcode, + entry, + &FunctionConstantValues::defaults(), + ) { + Ok(Some(stage_input)) => { + let mut inputs = LoweringInputs::new(); + inputs.stage_input = Some(stage_input); + profile.compile_entry(&descriptor, &inputs, budget) } + Ok(None) | Err(_) => (Err(e), report), } - other => other, - }; - match compiled { - Err(refusal) if color_limit(&refusal) => { - color_groups(profile, &descriptor, budget, (refusal, report)) } - compiled => (compiled.map(|function| vec![function]), report), + other => other, } }) } -/// Whether `error` is the refusal of a function's color outputs past what the profile draws at -/// once (`InterfaceComponents` at `MaxFragmentOutputAttachments` or `MaxColorAttachments`). -fn color_limit(error: &Error) -> bool { - let Error::Unsupported(u) = error else { - return false; - }; - let limit = |c: &Capability| { - matches!( - c, - Capability::Limit { - limit: VkLimit::MaxFragmentOutputAttachments | VkLimit::MaxColorAttachments, - .. - } - ) - }; - u.feature == Feature::InterfaceComponents - && matches!(&u.needs, Needs::AnyOf(sets) if sets.iter().flatten().any(limit)) -} - -/// The fragment function of `descriptor`, refused alone for writing more colors than `profile` -/// draws at once (`refusal`, after `report`), compiled as each color group of the render pipeline -/// whose attachments are the colors it writes ([`ColorGroup::of`], `LoweringInputs::color_group`), -/// as the runtime draws that pipeline on the profile (`pipeline::compile::color_group`): every -/// group's module, in group order, or the first group's refusal. A function that is not a fragment -/// function, or whose colors take no group, keeps `refusal`, and so does one of more groups that -/// writes memory, which the pipeline's link refuses so ([`CompiledFunction::writes_memory`]). -/// Each compile runs on a fresh meter of `budget`; the report is their total work and their -/// highest ledger peak. -fn color_groups( - profile: &DeviceProfile, - descriptor: &EntryDescriptor<'_>, - budget: &Budget, - (refusal, report): (Error, CompileReport), -) -> (Result, Error>, CompileReport) { - let present: BTreeSet = - match profile.specialized_entry(descriptor, &LoweringInputs::new(), budget) { - Ok(entry) if matches!(entry.ep.stage, AbiStage::Fragment { .. }) => entry - .ep - .outputs - .iter() - .filter_map(|output| match output.role { - OutputRole::RenderTarget { - attachment: AbiInt::Const(color), - .. - } => Some(color), - _ => None, - }) - .collect(), - Ok(_) | Err(_) => return (Err(refusal), report), - }; - let width = ColorGroup::width_on(profile); - let Some(grouping) = ColorGroup::of(present.into_iter().collect(), width, 0) else { - return (Err(refusal), report); - }; - let mut total = report; - let mut modules = Vec::with_capacity(grouping.groups() as usize); - for group in 0..grouping.groups() { - let Some(of_group) = ColorGroup::of(grouping.present.clone(), width, group) else { - return (Err(refusal), total); - }; - // The colors of the other groups, at their locations past the group's, have no - // attachment in the group's pipeline: stored nowhere, as `compile_render_variant` compiles - // the group's variant (`LoweringInputs::unattached_colors`). - let mut inputs = LoweringInputs::new(); - inputs.unattached_colors = (grouping.present.iter()) - .filter(|color| !of_group.colors().contains(color)) - .map(|&color| of_group.location(color)) - .collect(); - inputs.color_group = Some(of_group); - let (compiled, report) = profile.compile_entry(descriptor, &inputs, budget); - total.work_units += report.work_units; - total.ledger_peak = total.ledger_peak.max(report.ledger_peak); - match compiled { - Ok(function) => modules.push(function), - Err(error) => return (Err(error), total), - } - } - if grouping.groups() > 1 && modules.iter().any(CompiledFunction::writes_memory) { - return (Err(refusal), total); - } - (Ok(modules), total) -} - /// One engine attempt whose compile `compile` makes under the per-attempt wall deadline /// `deadline`, linked alone and checked by L3 for `profile` in this process: /// [`translate_unvalidated`], then [`PendingL3::validate`]. [`translate_new_linked`] and the @@ -740,22 +645,6 @@ pub fn translate_unvalidated( profile: &DeviceProfile, deadline: Option, compile: impl FnOnce(&Budget) -> (Result, CompileReport), -) -> (Attempt, Option) { - translate_modules_unvalidated(profile, deadline, |budget| { - let (compiled, report) = compile(budget); - (compiled.map(|function| vec![function]), report) - }) -} - -/// [`translate_unvalidated`] of a compile that may make several modules of the one function, its -/// color groups' ([`color_groups`]): each is linked alone, relocated and checked against -/// `profile` as one module is, and the first refusal is the attempt's. The attempt's words are -/// theirs together, its hash that of their bytes in order, and its strategies' words their sums; -/// L3 checks every module ([`PendingL3`]). -fn translate_modules_unvalidated( - profile: &DeviceProfile, - deadline: Option, - compile: impl FnOnce(&Budget) -> (Result, Error>, CompileReport), ) -> (Attempt, Option) { let budget = Budget::with_deadline(deadline); // The allocator window is exactly the compiles' scope: everything their ledgers are charged @@ -772,23 +661,8 @@ fn translate_modules_unvalidated( spirv_sha256: None, }) }; - let no_module = || { - Error::Internal(InternalError::new( - InternalKind::Invariant, - "a compile that made no module", - )) - }; - let (functions, report) = match compiled { - Ok((Ok(functions), report)) if !functions.is_empty() => (functions, report), - Ok((Ok(_), report)) => { - return ( - Attempt { - cost: cost(report, BTreeMap::new()), - ..error_attempt(&no_module()) - }, - None, - ) - } + let (function, report) = match compiled { + Ok((Ok(function), report)) => (function, report), Ok((Err(error), report)) => { return ( Attempt { @@ -809,42 +683,26 @@ fn translate_modules_unvalidated( } }; let mut strategy_words = BTreeMap::new(); - for function in &functions { - for (name, used) in &function.strategies().entries { - *strategy_words.entry(name.clone()).or_insert(0) += used.words; - } + for (name, used) in &function.strategies().entries { + *strategy_words.entry(name.clone()).or_insert(0) += used.words; } let cost = cost(report, strategy_words); let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - let mut modules = Vec::with_capacity(functions.len()); - for function in &functions { - let module = profile.link_standalone(function).map_err(Err)?; - crate::l3::check_requirements(function.requirements(), profile).map_err(Ok)?; - modules.push(PendingModule { - plan: L3Plan::of(profile, function.requirements()), - words: module.words, - layout: module.layout, - }); - } - let mut modules = modules.into_iter(); - let first = modules.next().ok_or_else(|| Err(no_module()))?; + let module = profile.link_standalone(&function).map_err(Err)?; + crate::l3::check_requirements(function.requirements(), profile).map_err(Ok)?; Ok::<_, Result>(PendingL3 { - plan: first.plan, - words: first.words, - layout: first.layout, - groups: modules.collect(), + plan: L3Plan::of(profile, function.requirements()), + words: module.words, + layout: module.layout, }) })); match run { Ok(Ok(pending)) => { - let bytes: Vec = pending - .modules() - .flat_map(|(words, _)| words.iter().flat_map(|w| w.to_le_bytes())) - .collect(); + let bytes: Vec = pending.words.iter().flat_map(|w| w.to_le_bytes()).collect(); let attempt = Attempt { outcome: Outcome::Translated, detail: None, - words: Some(pending.modules().map(|(words, _)| words.len() as u64).sum()), + words: Some(pending.words.len() as u64), cost: cost.map(|cost| AttemptCost { spirv_sha256: Some(crate::hash::sha256_bytes(&bytes)), ..cost @@ -919,29 +777,17 @@ impl L3Plan { } /// A module [`translate_unvalidated`] linked, relocated, and found within the profile, which -/// `spirv-val` has yet to check: its words, the pipeline layout link gave it alone, and L3's plan; -/// for a function translated in color groups (`color_groups`), the first group's, and the later -/// groups' modules, which L3 checks after it. +/// `spirv-val` has yet to check: its words, the pipeline layout link gave it alone, and L3's plan. #[derive(Debug)] pub struct PendingL3 { pub words: Vec, pub layout: PipelineLayout, pub plan: L3Plan, - pub groups: Vec, -} - -/// A later color group's module of a [`PendingL3`]: its words, its layout and L3's plan for it. -#[derive(Debug)] -pub struct PendingModule { - pub words: Vec, - pub layout: PipelineLayout, - pub plan: L3Plan, } impl PendingL3 { /// L3's `spirv-val` in this process: `attempt` (as it stands if the module is accepted) as L3 - /// leaves it ([`Attempt::settle_l3`]), with the words and layout when it accepts them (the - /// first group's, for a function translated in color groups). + /// leaves it ([`Attempt::settle_l3`]), with the words and layout when it accepts them. pub fn validate(self, mut attempt: Attempt) -> (Attempt, Option<(Vec, PipelineLayout)>) { let linked = attempt .settle_l3(self.check()) @@ -949,23 +795,12 @@ impl PendingL3 { (attempt, linked) } - /// L3's `spirv-val` on each module in this process, in order, under `catch_unwind`: the - /// first failure, else success. + /// L3's `spirv-val` on the module in this process, under `catch_unwind`. pub fn check(&self) -> std::thread::Result> { std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - self.modules() - .try_for_each(|(words, plan)| plan.check(words)) + self.plan.check(&self.words) })) } - - /// Each module's words and L3's plan for it, the first group's first. - pub fn modules(&self) -> impl Iterator { - std::iter::once((self.words.as_slice(), &self.plan)).chain( - self.groups - .iter() - .map(|module| (module.words.as_slice(), &module.plan)), - ) - } } /// Where an engine attempt on an indexed row gets its bitcode. @@ -1538,13 +1373,11 @@ mod tests { } /// A fragment function of more colors than a device draws at once (four: `runtime-floor` with - /// four color attachments, below the runtime's floor of eight), refused alone, is - /// translated as each color group of the pipeline of its colors, every module checked by L3: - /// five and seven colors in two groups, colors 0 and 5 in one renumbered. One that writes - /// memory keeps its limit refusal, which a pipeline of more groups meets at link. On lavapipe - /// (eight) each is one module, as it was. + /// four color attachments, below the runtime's floor of eight) keeps its limit refusal: + /// five and seven colors, colors 0 and 5, and one that writes memory. On lavapipe (eight) + /// each translates. #[test] - fn a_fragment_function_of_more_colors_than_the_floor_translates_in_color_groups() { + fn a_fragment_function_of_more_colors_than_the_device_draws_is_refused() { use metal2vulkan_devtools::{engine_dir, llvm_assemble, AssembleError}; let bitcode = match llvm_assemble(&engine_dir().join("color_groups.ll")) { Ok(bytes) => bytes, @@ -1567,28 +1400,18 @@ mod tests { .clone() }; let lavapipe = load_profile("lavapipe").unwrap(); - for (stem, profile, groups) in [("four colors", four, 2), ("lavapipe", lavapipe, 1)] { - for (entry, modules) in [("cg_five", groups), ("cg_seven", groups), ("cg_sparse", 1)] { - let (attempt, pending) = translate_new_unvalidated(&bitcode, entry, &profile, None); - assert_eq!(attempt.outcome, Outcome::Translated, "{entry} on {stem}"); - let pending = pending.unwrap(); - assert_eq!(pending.modules().count(), modules, "{entry} on {stem}"); - let words: usize = pending.modules().map(|(words, _)| words.len()).sum(); - assert_eq!(attempt.words, Some(words as u64), "{entry} on {stem}"); - let (attempt, linked) = pending.validate(attempt); - assert_eq!(attempt.outcome, Outcome::Translated, "{entry} on {stem}"); - assert!(linked.is_some(), "{entry} on {stem}"); + for (stem, profile, expected) in [ + ("four colors", four, "device_capability_missing"), + ("lavapipe", lavapipe, "translated"), + ] { + for entry in ["cg_five", "cg_seven", "cg_sparse", "cg_counts"] { + let attempt = translate_new(&bitcode, entry, &profile, None); + assert_eq!( + attempt.outcome.label(), + expected, + "{entry} on {stem}: {attempt:?}" + ); } - let counts = translate_new(&bitcode, "cg_counts", &profile, None); - let expected = match stem { - "lavapipe" => "translated", - _ => "device_capability_missing", - }; - assert_eq!( - counts.outcome.label(), - expected, - "cg_counts on {stem}: {counts:?}" - ); } } diff --git a/crates/metal2vulkan-validation/src/observation_contract/comparison.rs b/crates/metal2vulkan-validation/src/observation_contract/comparison.rs index a92dba363..893a849e9 100644 --- a/crates/metal2vulkan-validation/src/observation_contract/comparison.rs +++ b/crates/metal2vulkan-validation/src/observation_contract/comparison.rs @@ -246,9 +246,6 @@ impl UlpTable { /// difference is a mismatch for review, never accepted or explained by the note. /// - `LinkedSamplerNumbering`: [`Allowance::Recorded`]. Only sampler resource IDs may differ, no /// shader value; a difference is a mismatch for review. -/// - `ColorAttachmentGroups`: [`Allowance::Recorded`]. Only a group past the first may differ, at -/// a discard or depth edge where the driver compiled the groups' variants apart; a difference is -/// a mismatch for review. /// - `DeviceInterpolationOffset`: [`Allowance::Recorded`]. Recorded at every read at an offset, /// where only an offset past the device's range or off its grid reads otherwise than Metal; a /// difference is a mismatch for review, never accepted or explained by the note. @@ -270,7 +267,7 @@ pub fn allowance(note: PrecisionNote) -> Allowance { | N::FunctionStorageAssumed | N::ViewBaseTexelOffset => Allowance::Recorded, N::DeviceColorConversion => Allowance::Recorded, - N::LinkedSamplerNumbering | N::ColorAttachmentGroups => Allowance::Recorded, + N::LinkedSamplerNumbering => Allowance::Recorded, N::DeviceInterpolationOffset => Allowance::Recorded, N::GradFromBias | N::DeviceTranscendentals diff --git a/crates/metal2vulkan-validation/src/translation_audit.rs b/crates/metal2vulkan-validation/src/translation_audit.rs index d0d440202..14519d239 100644 --- a/crates/metal2vulkan-validation/src/translation_audit.rs +++ b/crates/metal2vulkan-validation/src/translation_audit.rs @@ -41,8 +41,8 @@ const PRODUCT_FINGERPRINT: &str = env!("METAL2VULKAN_PRODUCT_FINGERPRINT"); /// in its L3 stage, a fresh image of itself, so an attempt's peak is the larger of its /// translation's and its validation's, not their sum. 7: a fragment function refused for writing /// more colors than the profile draws at once is translated in color groups, one module a group, -/// each checked by L3 (`engine::color_groups`). -pub const ENGINE_CENSUS_VERSION: u32 = 7; +/// each checked by L3. 8: such a function keeps its limit refusal. +pub const ENGINE_CENSUS_VERSION: u32 = 8; /// The external tools a census row can depend on: `llvm-as` (a public row's bitcode) and /// `spirv-val` (L3). Each is keyed by its `--version` output. diff --git a/crates/metal2vulkan-validation/src/worker/l3.rs b/crates/metal2vulkan-validation/src/worker/l3.rs index b02046a4c..aad12f8de 100644 --- a/crates/metal2vulkan-validation/src/worker/l3.rs +++ b/crates/metal2vulkan-validation/src/worker/l3.rs @@ -37,9 +37,6 @@ struct Pending { plan: L3Plan, /// The module's words, little-endian. words: PathBuf, - /// The later color groups' modules of a function translated in color groups - /// ([`PendingL3::groups`]), each its words' file and its plan, checked after the first. - groups: Vec<(PathBuf, L3Plan)>, } /// Report `result` once L3 has settled its attempt, whose outcome stands if `spirv-val` accepts @@ -57,30 +54,18 @@ pub fn report_after_l3( let dir = std::env::temp_dir(); let words_path = dir.join(format!("l3-words-{}.spv", std::process::id())); let pending_path = dir.join(format!("l3-pending-{}.json", std::process::id())); - let PendingL3 { - words, - plan, - groups, - .. - } = pending; + let PendingL3 { words, plan, .. } = pending; let write = |path: &Path, words: Vec| { let bytes: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); drop(words); std::fs::write(path, bytes).map_err(|error| format!("write {}: {error}", path.display())) }; write(&words_path, words)?; - let mut group_files = Vec::with_capacity(groups.len()); - for (index, group) in groups.into_iter().enumerate() { - let path = dir.join(format!("l3-words-{}-{}.spv", std::process::id(), index + 1)); - write(&path, group.words)?; - group_files.push((path, group.plan)); - } let text = serde_json::to_vec(&Pending { peaks: super::Peaks::now(), result, plan, words: words_path, - groups: group_files, }) .map_err(|error| format!("encode the L3 stage's input: {error}"))?; std::fs::write(&pending_path, text) @@ -122,21 +107,12 @@ pub fn serve( mut result, plan, words, - groups, } = serde_json::from_slice::>(&text) .map_err(|error| format!("decode {}: {error}", pending.display()))?; drop(text); - // The tools read each module from its file; this image never holds one. The first failure is - // the attempt's. - let modules: Vec<(PathBuf, L3Plan)> = std::iter::once((words, plan)).chain(groups).collect(); - let checked = std::panic::catch_unwind(|| { - modules - .iter() - .try_for_each(|(words, plan)| plan.check_file(words)) - }); - for (words, _) in &modules { - let _ = std::fs::remove_file(words); - } + // The tools read the module from its file; this image never holds it. + let checked = std::panic::catch_unwind(|| plan.check_file(&words)); + let _ = std::fs::remove_file(&words); attempt(&mut result).settle_l3(checked); super::report_with_peaks(&result, peaks.max(super::Peaks::now())) } diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index afd6e59a2..7ff8ee0c0 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -55,8 +55,7 @@ use crate::pipeline::layout::{ BindingSource, DescriptorBinding, DescriptorSetLayout, PipelineLayout, PushConstantRange, }; use crate::pipeline::lower_inputs::{ - BlendEquation, ChannelWrite, ColorGroup, ExtendedRangeColor, FactorLane, RotatedBlendForm, - VertexFetch, + BlendEquation, ChannelWrite, ExtendedRangeColor, FactorLane, RotatedBlendForm, VertexFetch, }; use crate::pipeline::stage_io::{ CoverageLoop, CoverageLoopRefusal, DepthCompares, DepthMode, Interpolation as IoInterpolation, @@ -1161,11 +1160,10 @@ codec_struct! { rotated_colors, rotated_factors, rotated_blends, decoded_fetches, texture_write_rounding, uniform_outputs, uniform_inputs, instanced_attributes, half_blend_colors, half_fast_colors, float_blend_colors, zero_indices, - color_group, word_colors, alpha_in_red_colors, alpha_test, depth_compares, + word_colors, alpha_in_red_colors, alpha_test, depth_compares, logic_operation, } DepthCompares { samplers, clamped } - ColorGroup { present, width, group } WordField { shift, bits } ExtendedRangeColor { form, blended, nearest_even } PulledInput { index, ty, fetch } @@ -1403,7 +1401,7 @@ codec_struct! { tessellation, fragment_imageblock, vertex_writes_memory, writes_viewport_index, storage_attachments, shadow_stencil, writes_point_size, writes_depth, reads_barycentric_coord, reads_primitive_id, fragment_writes_memory, color_outputs, - sample_mask, snapshot_reads, color_group, logic_op, line_band, region_fan_out, + sample_mask, snapshot_reads, logic_op, line_band, region_fan_out, } TessellationState { patch_control_points, domain, control_points, factor_step_function, push_offset, @@ -1479,7 +1477,6 @@ codec_enum! { NativeDot, NativeMix, DevicePackConversion, - ColorAttachmentGroups, TessellationTriangleOrder, UnmeasuredGroupSpeculation, NotMipmappedAnisotropicFilter, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 299f192db..a57f867c2 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -61,7 +61,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2227; +pub const SEMANTICS_VERSION: u32 = 2228; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -71,7 +71,7 @@ pub const SEMANTICS_VERSION: u32 = 2227; /// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag /// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that /// bumps it says what changed; this comment keeps no history. -pub const ARTIFACT_FORMAT_VERSION: u32 = 572; +pub const ARTIFACT_FORMAT_VERSION: u32 = 573; /// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding /// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle @@ -459,18 +459,6 @@ pub struct VariantKey { /// as that 1D texture and reads it. The plan of a pipeline compiled under it states it. #[cfg_attr(feature = "serde", serde(default))] pub open_cl_lines: BTreeSet, - /// The group of the render pipeline's color attachments the variant draws, where the device - /// draws them in groups (`crate::pipeline::ColorGroup`, `GraphicsState::color_group`): its - /// fragment function writes that group's attachments alone, at locations `0..` - /// (`LoweringInputs::color_group`), and its graphics state holds them alone. The key's other - /// choices of colors (`zeroed_colors`, `dropped_colors`, `interlocked_colors`) then name the - /// group's locations, as a bind plan of the variant over its - /// group's part of the pass asks for them; no bind plan sets the group itself. 0, the first - /// group, by default; a group past the pipeline's last is no plan's (an invariant). Not a - /// lowering input of its own: the render pipeline's compile derives the fragment function's - /// from it, the descriptor and the profile. - #[cfg_attr(feature = "serde", serde(default))] - pub color_group: u32, /// The render pipeline draws a rasterization-rate-mapped pass's regions several at a time, /// each one draw of a multi-draw whose index selects its viewport and scissor /// (`BindShape::region_viewports`): its vertex function stores `ViewportIndex` as `DrawIndex` @@ -592,7 +580,6 @@ impl VariantKey { && self.cross_class.is_empty() && self.anisotropic_samplers.is_empty() && self.open_cl_lines.is_empty() - && self.color_group == 0 && !self.region_viewports && self.region_fan_out.is_none() } diff --git a/crates/metal2vulkan/src/library/compiled.rs b/crates/metal2vulkan/src/library/compiled.rs index 3dfa214be..ff4ce3cdf 100644 --- a/crates/metal2vulkan/src/library/compiled.rs +++ b/crates/metal2vulkan/src/library/compiled.rs @@ -276,9 +276,7 @@ impl CompiledFunction { } /// Whether the function writes memory another invocation or a later command can read: it - /// stores to a buffer or a texture, or updates one atomically. A render pipeline whose colors - /// the device draws in more than one group refuses such a function, which each group's draw - /// would run again ([`ColorGroup`](crate::pipeline::ColorGroup)). + /// stores to a buffer or a texture, or updates one atomically. pub fn writes_memory(&self) -> bool { self.0.interface.writes_memory } diff --git a/crates/metal2vulkan/src/lower/stage_io/mod.rs b/crates/metal2vulkan/src/lower/stage_io/mod.rs index 32619fbbe..c8fc897d6 100644 --- a/crates/metal2vulkan/src/lower/stage_io/mod.rs +++ b/crates/metal2vulkan/src/lower/stage_io/mod.rs @@ -424,11 +424,6 @@ pub struct StageIoPlan { pub point_size_default: Option, /// The `Position` object of a vertex function, decorated `Invariant`. pub invariant: Option, - /// A fragment function of one of its pipeline's color groups, where the pipeline takes more - /// than one (`LoweringInputs::color_group`): its `FragDepth`, `SampleMask` and - /// `FragStencilRefEXT` outputs are decorated `Invariant`, so every group's variant computes - /// them alike (the module docs of `pipeline::compile::color_group`). - pub invariant_fragment_outputs: bool, /// The entry's execution modes (fragment origin, early tests, depth and stencil modes). pub modes: Vec, /// The artifact's stage-IO interface. @@ -2805,19 +2800,6 @@ pub fn declare( } d.region_table = Some(crate::pipeline::link::fan_out::declare_table(mb)?); } - if sp.invariant_fragment_outputs { - use crate::spv::BuiltIn as B; - for (o, g) in sp.objects.iter().zip(&d.globals) { - if let IoObject::Builtin { - builtin: B::FragDepth | B::SampleMask | B::FragStencilRefEXT, - dir: IoDir::Output, - .. - } = o - { - mb.invariant(*g)?; - } - } - } modes.extend(sp.modes.iter().copied()); Ok(d) } diff --git a/crates/metal2vulkan/src/lower/stage_io/plan.rs b/crates/metal2vulkan/src/lower/stage_io/plan.rs index fd5fccc47..6e2744e86 100644 --- a/crates/metal2vulkan/src/lower/stage_io/plan.rs +++ b/crates/metal2vulkan/src/lower/stage_io/plan.rs @@ -2201,19 +2201,6 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { } let (returned, tys) = output_types(cx)?; cx.families.stage_io.returned = returned; - // A fragment function of one of its pipeline's color groups (`LoweringInputs::color_group`), - // its colors renumbered before planning (`pipeline::compile::color_group::entry`): stated for - // link, and, where the pipeline takes more than one group, its per-fragment outputs invariant - // across the groups' variants, and the note of what is not. - if cx.stage == Stage::Fragment { - if let Some(group) = cx.inputs.color_group.clone() { - if group.groups() > 1 { - cx.families.stage_io.invariant_fragment_outputs = true; - cx.precision.insert(PrecisionNote::ColorAttachmentGroups); - } - cx.families.stage_io.interface.color_group = Some(group); - } - } // A fragment function compiled for a multisampled pipeline reads `[[position]]` at the pixel // center. cx.families.stage_io.interface.multisampled = diff --git a/crates/metal2vulkan/src/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index 72f5728a9..0174f27aa 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -271,7 +271,6 @@ mod serde_round_trips { )]), anisotropic_samplers: BTreeSet::from([slot(Stage::Fragment, SlotClass::Sampler, 1)]), open_cl_lines: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 1)]), - color_group: 1, region_viewports: true, region_fan_out: Some(crate::pipeline::RegionFanOut::Probe), }); @@ -479,11 +478,6 @@ mod serde_round_trips { open_cl_lines: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 2)]), uniform_varyings: BTreeSet::from([VaryingKey::user(b"user(tint)")]), instanced_attributes: BTreeSet::from([1]), - color_group: Some(crate::pipeline::ColorGroup { - present: vec![0, 1, 2, 3, 5, 7], - width: 4, - group: 1, - }), object_payload: Some(64), region_viewports: true, region_copies: true, @@ -634,11 +628,6 @@ mod serde_round_trips { color_outputs: 0b101, sample_mask: Some(0b1001), snapshot_reads: true, - color_group: Some(crate::pipeline::ColorGroup { - present: vec![0, 5], - width: 4, - group: 0, - }), logic_op: Some(vk::LogicOp::EQUIVALENT), line_band: Some(crate::pipeline::LineBandState { push_offset: 112, diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 6eb9dcc07..c5ea82649 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -1942,20 +1942,6 @@ pub enum PrecisionNote { /// unless the stage records it outright for another conversion. Validation derives no /// tolerance from it. DevicePackConversion, - /// A render pipeline whose color attachments the device draws in more than one group - /// (`GraphicsState::color_group`, the module docs of `pipeline::compile::color_group`): a - /// device without Metal's eight color attachments draws each of its draws once per group, - /// each group's variant writing that group's attachments over its own copy of the depth and - /// stencil the pass loads. Every variant's vertex stage is the same module, its `Position` - /// decorated `Invariant`, and every fragment variant computes `FragDepth`, `SampleMask` and - /// `FragStencilRefEXT` by the same expressions, decorated `Invariant` (SPIR-V: "computed - /// invariantly with respect to other shaders computing the same expressions"). Vulkan's - /// invariance appendix promises no more across pipelines of other fragment modules and - /// attachments (its Rule 4 holds for "identical pipelines", its Corollary 1 across the state - /// of its Rule 2). **Residual:** groups past the first may differ at discard or depth edges if - /// the driver compiles the variants differently. Nothing broader. Recorded only by a fragment - /// stage of such a pipeline. Validation derives no tolerance from it. - ColorAttachmentGroups, /// A tessellation pipeline drawn through the device's tessellation stages (a device with /// `tessellationShader`), on every device (no Vulkan query tells Apple's tessellator apart): /// the device's tessellator orders each patch's triangles and picks each one's first corner, diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 07ec410ba..9b78c90f6 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -14,7 +14,6 @@ //! key derivation is [`key`]. pub mod api; -pub(crate) mod color_group; mod entry; mod images; pub mod key; @@ -153,10 +152,6 @@ pub struct FragmentPass<'a> { /// The pipeline's private `fragmentDepthCompareClampMask` /// (`LoweringInputs::depth_compare_clamp_mask`). pub(crate) depth_compare_clamp_mask: u32, - /// The group of the pipeline's color attachments the function writes - /// (`LoweringInputs::color_group`), whose variant's descriptor `color_attachments` is - /// (`color_group::descriptor`); `None` from a descriptor, set by the compile layer. - pub(crate) color_group: Option<&'a crate::pipeline::lower_inputs::ColorGroup>, /// Where the function's push fields start on the floor (`LoweringInputs::push_base`): 0 from /// a render descriptor, set by the compile layer from the vertex function it compiled; past /// the object and mesh functions' windows for a mesh pipeline's. @@ -181,7 +176,6 @@ impl<'a> From<&'a RenderPipelineDescriptor> for FragmentPass<'a> { .flatten(), logic_operation: None, depth_compare_clamp_mask: d.private.fragment_depth_compare_clamp_mask, - color_group: None, push_base: 0, } } @@ -202,7 +196,6 @@ impl<'a> From<&'a MeshPipelineDescriptor> for FragmentPass<'a> { alpha_test: None, logic_operation: None, depth_compare_clamp_mask: 0, - color_group: None, push_base: crate::lower::push::window(crate::pipeline::sym::Stage::Mesh, 0).1, } } @@ -264,41 +257,17 @@ impl<'a> InputsFrom<'a> { InputsFrom::Vertex(..) | InputsFrom::Fragment(..) => &NONE, } } - - /// The group of its pipeline's color attachments a fragment stage compiles for - /// (`LoweringInputs::color_group`): the given inputs', or the render pipeline variant's. - fn color_group(&self) -> Option<&'a crate::pipeline::lower_inputs::ColorGroup> { - match self { - InputsFrom::Given(i) => i.color_group.as_ref(), - InputsFrom::Vertex(..) => None, - InputsFrom::Fragment(pass, ..) => pass.color_group, - } - } -} - -/// The specialized entry `spec` as a compile under `inputs` lowers it on `p`: renumbered for its -/// color group (`color_group::entry`) where it compiles for one. -fn grouped_entry( - spec: air::Entry, - inputs: InputsFrom<'_>, - p: &DeviceProfile, -) -> Result { - match inputs.color_group() { - Some(g) => color_group::entry(spec, g, p), - None => Ok(spec), - } } /// Where `inputs` are a render pipeline's fragment stage's, each `[[color(n)]]` input the /// specialized fragment entry `spec` declares has an attachment with a pixel format in the -/// pipeline (the pass's attachments, or its color group's `ColorGroup::present`, the pipeline's -/// own), whether or not the body reads it: plain Metal refuses the pipeline otherwise, with the +/// pipeline, whether or not the body reads it: plain Metal refuses the pipeline otherwise, with the /// read dead after specialization as with it live ("Shaders reads from a color attachment whose /// pixel format is MTLPixelFormatInvalid", /// `metal2vulkan-conformance/probes/dead_ordered_and_unattached_reads.m`, an M3 Max under macOS /// 27.0.1). `InvalidDescriptor(ColorAttachment)` at the first index without one. An input its -/// constants gate is no parameter of the specialized entry. Checked on the entry before its -/// group renumbers it, by both a stage's keys ([`stage_inputs`]) and its compile. +/// constants gate is no parameter of the specialized entry. Checked by both a stage's keys +/// ([`stage_inputs`]) and its compile. fn color_inputs_attached(spec: &air::Entry, inputs: InputsFrom<'_>) -> Result<(), Error> { let InputsFrom::Fragment(pass, ..) = inputs else { return Ok(()); @@ -311,13 +280,10 @@ fn color_inputs_attached(spec: &air::Entry, inputs: InputsFrom<'_>) -> Result<() else { continue; }; - let attached = match pass.color_group { - Some(g) => g.present.contains(&color), - None => pass - .color_attachments - .get(color as usize) - .is_some_and(Option::is_some), - }; + let attached = pass + .color_attachments + .get(color as usize) + .is_some_and(Option::is_some); if !attached { return Err(Error::InvalidDescriptor(DescriptorError::ColorAttachment { index: color, @@ -641,12 +607,7 @@ pub fn stage_inputs( let open_cl = (inputs.open_cl_mode(), inputs.open_cl_lines()); let specialized = entries.specialized(fd, inputs.call_stack_depth(), open_cl, m)?; color_inputs_attached(&specialized.spec, inputs)?; - // A color group's variant reads its own renumbering of the entry the creation shares. - let grouped = match inputs.color_group() { - Some(_) => Some(grouped_entry(specialized.spec.clone(), inputs, p)?), - None => None, - }; - let spec = grouped.as_ref().unwrap_or(&specialized.spec); + let spec = &specialized.spec; let inputs = lower_inputs(spec, inputs, p, m)?; let uniform = crate::lower::stage_io::uniform_varyings(spec, &inputs, m)?; let writes = raw_indices_written(spec, &inputs); @@ -2846,7 +2807,6 @@ fn lower_inputs( } InputsFrom::Fragment(d, variant, written, primitive, varyings, uniform) => { let mut out = fragment_inputs(d, variant, p); - out.color_group = d.color_group.cloned(); out.signed_color_attachments = signed_colors_written(spec, d.color_attachments); out.signed_color_attachments.extend(signed_colors_fetched( spec, @@ -3133,7 +3093,6 @@ fn analyze_one(r: &Request<'_>, p: &DeviceProfile, m: &mut Meter) -> Result = d.into(); - pass.color_group = group.as_ref(); pass.logic_operation = logic; pass.push_base = push_end; if crate::pipeline::private_state::applied_masks(d).is_some() { @@ -828,9 +822,7 @@ impl Device { }) } - /// [`Device::compile_render_variant`] with the caller's meter. A variant of one of - /// the pipeline's color groups (`VariantKey::color_group`) compiles and links as the pipeline - /// of its group's attachments (`color_group`), its key's choices of colors naming the group's. + /// [`Device::compile_render_variant`] with the caller's meter. pub(crate) fn render_pipeline( &self, d: &RenderPipelineDescriptor, @@ -844,13 +836,10 @@ impl Device { // function's, where one is needed. let (operated, logic) = crate::pipeline::private_state::logic_operation(d, p)?; let d = operated.as_ref(); - let group = color_group::group(d, v, p)?; - let grouped = group.as_ref().map(|g| color_group::descriptor(d, g)); - let zeroed = with_zeroed_colors(grouped.as_ref().unwrap_or(d), v)?; + let zeroed = with_zeroed_colors(d, v)?; let d = zeroed.as_ref(); let pass = || { let mut pass = FragmentPass::from(d); - pass.color_group = group.as_ref(); pass.logic_operation = crate::pipeline::private_state::LogicDraw::shader(logic); pass }; @@ -935,11 +924,7 @@ impl Device { } let compiled: Vec<&CompiledFunction> = std::iter::once(&vertex).chain(&fragment).collect(); let artifacts: Vec<&FunctionArtifact> = compiled.iter().map(|c| c.artifact()).collect(); - let linked = link( - &artifacts, - &LinkInputs::render_variant(d, v, group.clone()), - p, - )?; + let linked = link(&artifacts, &LinkInputs::render_variant(d, v), p)?; let mut stages = Vec::with_capacity(compiled.len()); for (i, c) in compiled.iter().enumerate() { stages.push(stage_module(c, &linked, i)?); @@ -1652,15 +1637,10 @@ fn compute_fields(d: &ComputePipelineDescriptor) -> String { } } -/// The pipeline key's fields of variant `v` past its stages' keys: its color group past the first -/// (`VariantKey::color_group`), whose variant of a pipeline without a fragment function has no -/// stage of its own, and a band variant's synthesized tessellation stages. Empty for every other variant, so a pipeline keeps its key. +/// The pipeline key's fields of variant `v` past its stages' keys: a band variant's synthesized +/// tessellation stages. Empty for every other variant, so a pipeline keeps its key. fn variant_fields(v: &VariantKey) -> String { let mut fields = String::new(); - // The group a pipeline without a fragment function keeps in no stage's key. - if v.color_group != 0 { - fields.push_str(&format!(" color_group {}", v.color_group)); - } // The band's synthesized stages, in no stage's key. match v.line_band { None => {} diff --git a/crates/metal2vulkan/src/pipeline/compile/color_group.rs b/crates/metal2vulkan/src/pipeline/compile/color_group.rs deleted file mode 100644 index c3fc14247..000000000 --- a/crates/metal2vulkan/src/pipeline/compile/color_group.rs +++ /dev/null @@ -1,227 +0,0 @@ -//! Render pipelines whose color attachments a device draws in groups ([`ColorGroup`]). -//! -//! A subpass, or a dynamic rendering, holds at most `maxColorAttachments` color attachments -//! (`VUID-VkSubpassDescription-colorAttachmentCount-00845`, -//! `VUID-VkRenderingInfo-colorAttachmentCount-06106`), and a fragment shader's outputs lie below -//! `maxFragmentOutputAttachments` locations (`VUID-RuntimeSpirv-Location-06272`). Metal's -//! pipelines take eight color attachments; a device at Vulkan's floor holds four. The lesser of -//! the two limits is a group's width `w`. -//! -//! **Grouping**. A pipeline's attachments with a pixel format, in the order of their indices, -//! fall into groups of `w`: group `g` holds the `g`-th `w` of them. Metal requires the pass's -//! attachments to match the pipeline's, so the pass's attachments group alike. A pipeline whose -//! attachments are all below `w` keeps every attachment at its own index and takes no group (the -//! common path, unchanged); one with at most `w` attachments, one of them at an index at or past -//! `w` (`color(0)` and `color(5)` on a device of four), takes one group, its attachments -//! renumbered below `w`; one with more takes more groups. A variant of the pipeline draws one -//! group (`VariantKey::color_group`). -//! -//! **Projection**. Group `g`'s variant compiles as the pipeline whose descriptor holds the group's -//! attachments alone, at locations `0..` ([`descriptor`]), and whose fragment function's color -//! indices, the `[[color(n)]]` outputs' and inputs', are renumbered by [`ColorGroup::location`] -//! ([`entry`]): a color of another group, or one without an attachment, lands past the group's, -//! where the projected descriptor has no attachment, so the function stores it nowhere, as plain -//! Metal stores a color without an attachment. Every attachment-indexed input, table and check of -//! the compile and link then speaks the variant's locations, and the variant is an ordinary -//! pipeline of its group's attachments: its variant key's choices of colors (the zeroed, dropped, -//! interlocked and shadowed ones) name the group's locations, as a bind plan of the variant over -//! its group's part of the pass asks for them. The grouping is the pipeline's own, whatever the -//! pass holds. -//! -//! **Invariance**. A draw of a pipeline of several groups is a draw of each group's variant, each -//! in a pass of its group's attachments over its own copy of the depth and stencil the pass -//! loads. Each group's colors are Metal's where every variant generates the same fragments, with -//! the same depth, stencil reference, coverage and discard. Vulkan's invariance appendix gives -//! that for "identical pipelines" alone ("`VkPipeline` objects that have been created with -//! identical SPIR-V binaries and identical state", Rule 4), and its Rule 2 lists the state whose -//! change has no side effects ("Color and depth/stencil attachment contents", "Write masks", -//! "Blend parameters", among others), whence "Fragment generation is invariant with respect to the -//! state values listed in Rule 2" (Corollary 1). The variants differ beyond those: in their color -//! attachments' formats and count, and in their fragment modules, which write other colors. What -//! can be made invariant is: -//! -//! - The vertex stage: every variant's is the same module (its inputs do not name the group), and -//! its `Position` is decorated `Invariant`, as in every pipeline. -//! - The fragment stage's per-fragment outputs, `FragDepth`, `SampleMask` and -//! `FragStencilRefEXT`: each variant keeps them, computed by the same expressions, and decorates -//! them `Invariant`, SPIR-V's "expressions computing its value be computed invariantly with -//! respect to other shaders computing the same expressions". `NoContraction` adds nothing for -//! them: an `Invariant` output's expressions are computed alike in every variant, contraction -//! included, and decorating the arithmetic would round it apart where Metal fuses it. -//! -//! What cannot: a discard has no output to decorate, and the device's rasterization of the -//! fixed-function depth is not covered across pipelines of other fragment modules and attachments. -//! So the variants record `PrecisionNote::ColorAttachmentGroups`, whose residual is that groups -//! past the first may differ at discard or depth edges if the driver compiles the variants -//! differently, and nothing broader. -//! -//! **Refusals**. What runs once per covered sample in Metal and would run once per group here is -//! refused where the pipeline takes more than one group, with the pipeline's own limit refusal -//! (`Unsupported{InterfaceComponents}` at `MaxColorAttachments`, or `MaxFragmentOutputAttachments` -//! where that is the lesser): a vertex or fragment stage that writes memory, stores or atomics -//! (`StageInterface::writes_memory`, link); a tessellation pipeline (link); alpha to coverage, -//! which reads color 0's alpha in every group ([`group`]); a `[[color(n)]]` input of another -//! group that the function reads, imageblock data and raster order groups ([`entry`]). A color -//! input of another group that the specialized body never uses (its read folded away by the -//! function's constants) reads nothing there, and is not refused; nor is a raster order group on a -//! parameter the body never uses, which orders nothing (plain Metal makes and draws such a -//! function, `metal2vulkan-conformance/probes/dead_ordered_and_unattached_reads.m`). Imageblocks are refused under any -//! renumbering: an implicit imageblock's members name the attachments they alias by index. A mesh -//! render pipeline and a tile pipeline take no groups and keep the limit refusals. - -use crate::air; -use crate::air::abi::{AbiInt, OutputRole, ParamRole, Stage as AbiStage}; -use crate::cache::VariantKey; -use crate::device::requirements::VkLimit; -use crate::device::DeviceProfile; -use crate::error::{Capability, Error, Feature, InternalError, InternalKind, Unsupported}; -use crate::pipeline::descriptor::RenderPipelineDescriptor; -use crate::pipeline::lower_inputs::ColorGroup; - -/// The color group variant `v` of render pipeline `d` draws on `p` (the module docs): `None` -/// where each of `d`'s attachments is below the group width. A pipeline of more than one group -/// under alpha to coverage, or one renumbering color 0, is the limit refusal; a variant of a -/// group the pipeline does not have is no plan's (an invariant). -pub(crate) fn group( - d: &RenderPipelineDescriptor, - v: &VariantKey, - p: &DeviceProfile, -) -> Result, Error> { - let present: Vec = (0u32..) - .zip(&d.color_attachments) - .filter_map(|(i, a)| a.map(|_| i)) - .collect(); - let Some(g) = ColorGroup::of(present, width(p), v.color_group) else { - return match v.color_group { - 0 => Ok(None), - _ => Err(invariant("a color group of a pipeline that takes none")), - }; - }; - if v.color_group >= g.groups() { - return Err(invariant("a color group past the pipeline's last")); - } - // Metal's coverage reads color 0's alpha, attached or not, which another group's variant - // does not write, and a renumbering moves. - if d.alpha_to_coverage && (g.groups() > 1 || g.location(0) != 0) { - return Err(refusal(&g, p)); - } - Ok(Some(g)) -} - -/// `d` as group `g`'s variant compiles it: the group's attachments alone, attachment -/// `g.colors()[l]` at index `l`. -pub(crate) fn descriptor(d: &RenderPipelineDescriptor, g: &ColorGroup) -> RenderPipelineDescriptor { - let mut out = d.clone(); - out.color_attachments = Default::default(); - for &color in g.colors() { - let at = g.location(color) as usize; - if let (Some(slot), Some(a)) = ( - out.color_attachments.get_mut(at), - d.color_attachments.get(color as usize), - ) { - *slot = *a; - } - } - out -} - -/// The specialized fragment entry `spec` as group `g`'s variant compiles it: each color index its -/// outputs and `[[color(n)]]` inputs name renumbered by [`ColorGroup::location`]. Imageblock data -/// is the limit refusal on `p`, and so, where the pipeline takes more than one group, is a color -/// input of another group that the body uses and a raster order group on a color output or on a -/// parameter the body uses. Any other entry as it is. -pub(crate) fn entry( - mut spec: air::Entry, - g: &ColorGroup, - p: &DeviceProfile, -) -> Result { - if !matches!(spec.ep.stage, AbiStage::Fragment { .. }) { - return Ok(spec); - } - let split = g.groups() > 1; - let refused = || refusal(g, p); - // A parameter the specialized body never uses reads nothing: a color input of whichever group - // reads no attachment, and a raster order group on it orders no access. - let used = super::params_used(&spec); - for b in &mut spec.ep.params { - let read = used.contains(&b.param); - match &mut b.role { - ParamRole::Imageblock(_) => return Err(refused()), - ParamRole::ColorInput { - index, - raster_order_group, - } => { - if split && read && raster_order_group.is_some() { - return Err(refused()); - } - if let AbiInt::Const(color) = *index { - if split && read && !g.colors().contains(&color) { - return Err(refused()); - } - *index = AbiInt::Const(g.location(color)); - } - } - ParamRole::Buffer(a) | ParamRole::ArgumentBuffer(a) | ParamRole::Threadgroup(a) - if split && read && a.raster_order_group.is_some() => - { - return Err(refused()); - } - ParamRole::Texture(t) if split && read && t.raster_order_group.is_some() => { - return Err(refused()); - } - _ => {} - } - } - for o in &mut spec.ep.outputs { - match &mut o.role { - OutputRole::ImageblockData(_) => return Err(refused()), - OutputRole::RenderTarget { - attachment, - raster_order_group, - .. - } => { - if split && raster_order_group.is_some() { - return Err(refused()); - } - if let AbiInt::Const(color) = *attachment { - *attachment = AbiInt::Const(g.location(color)); - } - } - _ => {} - } - } - Ok(spec) -} - -/// The attachments a group holds on `p` ([`ColorGroup::width_on`]). -fn width(p: &DeviceProfile) -> u32 { - ColorGroup::width_on(p) -} - -/// The refusal of a pipeline of color group `g` on `p` whose groups cannot keep Metal's answer: -/// the limit the pipeline's attachments pass, as a pipeline the device cannot draw in groups is -/// refused. -pub(crate) fn refusal(g: &ColorGroup, p: &DeviceProfile) -> Error { - let l = &p.fields().limits; - let limit = match l.max_fragment_output_attachments < l.max_color_attachments { - true => VkLimit::MaxFragmentOutputAttachments, - false => VkLimit::MaxColorAttachments, - }; - let required = g.present.last().map_or(0, |&last| u64::from(last) + 1); - Unsupported::needs( - Feature::InterfaceComponents, - Capability::Limit { - limit, - required, - available: u64::from(width(p)), - }, - ) - .into() -} - -fn invariant(detail: &str) -> Error { - Error::Internal(InternalError::new( - InternalKind::Invariant, - detail.to_owned(), - )) -} diff --git a/crates/metal2vulkan/src/pipeline/compile/key.rs b/crates/metal2vulkan/src/pipeline/compile/key.rs index f01efe2b8..4de6be1ab 100644 --- a/crates/metal2vulkan/src/pipeline/compile/key.rs +++ b/crates/metal2vulkan/src/pipeline/compile/key.rs @@ -491,11 +491,6 @@ pub fn function_key( h.bytes(b"instanced-attributes") .bytes(format!("{:?}", inputs.instanced_attributes).as_bytes()); } - // Appended only when set, in its derived `Debug` form (integers), as `dropped_colors` is. - if let Some(group) = &inputs.color_group { - h.bytes(b"color-group") - .bytes(format!("{group:?}").as_bytes()); - } // Appended only when set: a mesh function whose own payload arena holds its object // function's keeps its key. if let Some(bytes) = inputs.object_payload { diff --git a/crates/metal2vulkan/src/pipeline/compile/tests.rs b/crates/metal2vulkan/src/pipeline/compile/tests.rs index 98e7060f1..b82c1329b 100644 --- a/crates/metal2vulkan/src/pipeline/compile/tests.rs +++ b/crates/metal2vulkan/src/pipeline/compile/tests.rs @@ -730,7 +730,6 @@ fn the_inputs_encoding_is_the_earlier_derived_debug() { .replace(", open_cl_lines: {}", "") .replace(", uniform_varyings: {}", "") .replace(", instanced_attributes: {}", "") - .replace(", color_group: None", "") .replace(", object_payload: None", "") .replace(", tessellation: None", "") .replace(", region_viewports: false", "") diff --git a/crates/metal2vulkan/src/pipeline/graphics.rs b/crates/metal2vulkan/src/pipeline/graphics.rs index f9c3b1ed0..effa90995 100644 --- a/crates/metal2vulkan/src/pipeline/graphics.rs +++ b/crates/metal2vulkan/src/pipeline/graphics.rs @@ -229,17 +229,6 @@ pub struct GraphicsState { /// requirements name `attachmentFeedbackLoopLayout` and `extendedDynamicState3ColorWriteMask`. #[cfg_attr(feature = "serde", serde(default))] pub snapshot_reads: bool, - /// The group of the pipeline's color attachments this variant draws - /// (`VariantKey::color_group`), where the device draws them in groups - /// ([`ColorGroup`](crate::pipeline::ColorGroup)): every color-indexed part of the state - /// (`color_attachments`, `input_attachments`, `storage_attachments` among them) indexes the group's attachments by location, Metal's attachment - /// `colors()[l]` at location `l`, and the fragment stage writes those alone. Each draw of the - /// pipeline is a draw of every group's variant, in a pass of that group's attachments; the - /// vertex stage is the same module in every variant, and the fragment stage's `FragDepth`, - /// `SampleMask` and `FragStencilRefEXT` outputs are decorated `Invariant` where there is more - /// than one group. `None` where each attachment is at its own index. - #[cfg_attr(feature = "serde", serde(default))] - pub color_group: Option, /// `VkPipelineColorBlendStateCreateInfo::logicOp` with `logicOpEnable`: the descriptor's /// private `logicOperation` /// ([`PrivateRenderState::logic_operation`](crate::pipeline::PrivateRenderState::logic_operation)), @@ -472,7 +461,6 @@ impl GraphicsState { color_outputs: 0, sample_mask: None, snapshot_reads: false, - color_group: None, logic_op: None, } } diff --git a/crates/metal2vulkan/src/pipeline/link.rs b/crates/metal2vulkan/src/pipeline/link.rs index 0a2b13427..6e6a1242f 100644 --- a/crates/metal2vulkan/src/pipeline/link.rs +++ b/crates/metal2vulkan/src/pipeline/link.rs @@ -87,7 +87,6 @@ use crate::pipeline::interface::{PipelineInterface, StageDescriptor, StageInterf use crate::pipeline::layout::{ BindingSource, DescriptorBinding, DescriptorSetLayout, PipelineLayout, PushConstantRange, }; -use crate::pipeline::lower_inputs::ColorGroup; use crate::pipeline::stage_io::StageBuiltin; use crate::pipeline::sym::{ CombinedSampler, HandleClass, ResourceKind, ResourceSlot, SlotClass, SlotRef, SpecKey, Stage, @@ -150,17 +149,11 @@ impl LinkInputs { } /// A render pipeline of `desc`'s fixed-function state under `variant`'s pulled vertex - /// buffers, the variant of color group `group` where it draws one, whose descriptor `desc` - /// holds the group's attachments alone (`pipeline::compile::color_group::descriptor`). - pub fn render_variant( - desc: &RenderPipelineDescriptor, - variant: &VariantKey, - group: Option, - ) -> LinkInputs { + /// buffers. + pub fn render_variant(desc: &RenderPipelineDescriptor, variant: &VariantKey) -> LinkInputs { let mut r = RenderLinkInputs::from(desc); r.pulled_vertex_buffers = variant.pulled_vertex_buffers.clone(); r.pull_every = variant.primitive_id_indices.is_some() || variant.private_list; - r.color_group = group; r.line_band = variant.line_band; r.region_fan_out = variant.region_fan_out; LinkInputs::Render(Box::new(r)) @@ -200,10 +193,6 @@ pub struct RenderLinkInputs { pub tessellation: Option, /// `textureWriteRoundingMode`: the color writes the fragment stage rounds by. pub texture_write_rounding_mode: metal::TextureWriteRoundingMode, - /// The group of the pipeline's color attachments the variant draws, whose attachments - /// alone [`color_attachments`](Self::color_attachments) holds, at their locations - /// (`GraphicsState::color_group`); `None` where each attachment is at its own index. - pub color_group: Option, /// The variant draws its lines, or its triangles' edges, as bands through synthesized /// tessellation stages (`VariantKey::line_band`, [`band`]), each patch one primitive of this /// kind; `None` for every other variant. @@ -232,7 +221,6 @@ impl RenderLinkInputs { max_vertex_amplification_count: 1, tessellation: None, texture_write_rounding_mode: metal::TextureWriteRoundingMode::TowardZero, - color_group: None, line_band: None, region_fan_out: None, } @@ -262,7 +250,6 @@ impl From<&RenderPipelineDescriptor> for RenderLinkInputs { max_vertex_amplification_count: d.max_vertex_amplification_count, tessellation: d.tessellation, texture_write_rounding_mode: d.texture_write_rounding_mode, - color_group: None, line_band: None, region_fan_out: None, } diff --git a/crates/metal2vulkan/src/pipeline/link/graphics.rs b/crates/metal2vulkan/src/pipeline/link/graphics.rs index 2a5d42a60..e99b3656f 100644 --- a/crates/metal2vulkan/src/pipeline/link/graphics.rs +++ b/crates/metal2vulkan/src/pipeline/link/graphics.rs @@ -279,30 +279,6 @@ fn topology(class: PrimitiveTopologyClass) -> vk::PrimitiveTopology { } } -/// Check the color group of render inputs `r` (`RenderLinkInputs::color_group`) with vertex stage -/// `vs`, fragment stage `fs`, a tessellation pipeline where `tessellated`, on `p`: the fragment -/// stage compiled for the variant's own group (`NeedsInput(ColorWrites)` for one compiled for -/// another, or for none), and, where the pipeline takes more than one group, neither stage writes -/// memory and the pipeline is no tessellation pipeline, which each group's draw would run again -/// (the limit refusal, `compile::color_group`). -fn color_group( - r: &RenderLinkInputs, - (vs, fs): (&StageInterface, Option<&StageInterface>), - tessellated: bool, - p: &DeviceProfile, -) -> Result<(), Error> { - if fs.is_some_and(|fs| fs.io.color_group != r.color_group) { - return Err(Error::NeedsInput(RuntimeInput::ColorWrites)); - } - let Some(g) = r.color_group.as_ref().filter(|g| g.groups() > 1) else { - return Ok(()); - }; - if tessellated || vs.writes_memory || fs.is_some_and(|fs| fs.writes_memory) { - return Err(crate::pipeline::compile::color_group::refusal(g, p)); - } - Ok(()) -} - /// The vertex amplification count of render inputs `r` (see the module docs), of a mesh pipeline /// where `mesh`: it draws no amplification as a view, so it needs no multiview (its draws of more /// than one amplification are refused at the draw, `bind::graphics`). @@ -350,7 +326,6 @@ pub fn graphics_state( ) .into()); } - color_group(r, (vs, fs), tessellation.is_some(), p)?; let max_vertex_amplification_count = vertex_amplification(r, vs.stage == Stage::Mesh, p)?; // A vertex function that selects its slice through the synthesized geometry stage // (`IoRole::SelectedLayer`) declares `Layer` there, and a fragment function that reads it as 0 @@ -814,7 +789,6 @@ pub fn graphics_state( color_outputs: 0, sample_mask: None, snapshot_reads, - color_group: r.color_group.clone(), // The pipeline's private logic operation, once compile decided it // (`private_state::logic_operation`). logic_op: None, diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index d74c8da8f..091414d70 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -792,20 +792,6 @@ pub struct LoweringInputs { /// projection). Empty for any other function. #[cfg_attr(feature = "serde", serde(default))] pub instanced_attributes: BTreeSet, - /// The group of its render pipeline's color attachments a fragment function writes - /// ([`ColorGroup`]), where the pipeline has more color attachments than the device draws to at - /// once, or one at an index at or past that count: the function writes the group's colors at - /// locations `0..` in the order of their indices, and every other color index it names, its - /// `[[color(n)]]` inputs' included, is renumbered past them ([`ColorGroup::location`]), so a - /// color of another group or without an attachment is stored nowhere - /// (`unattached_colors`). Where the pipeline takes more than one group, the function reads no - /// color outside its group, and its `FragDepth`, `SampleMask` and `FragStencilRefEXT` outputs - /// are decorated `Invariant` (`PrecisionNote::ColorAttachmentGroups`). - /// `Device::compile_render_variant` sets it for a `Function` fragment stage from the - /// descriptor, `VariantKey::color_group` and the profile; `None`, each color at its own index, - /// for a pipeline the device draws in one pass as it is, and for any other function. - #[cfg_attr(feature = "serde", serde(default))] - pub color_group: Option, /// The payload bytes of the object or mesh function's mesh render pipeline: for a mesh /// function, its object function's payload arena (`StageInterface::payload`), where it is /// larger than the mesh function's own; for an object function, and a mesh function without @@ -898,86 +884,6 @@ pub struct LoweringInputs { pub push_base: u32, } -/// One group of a render pipeline's color attachments (`LoweringInputs::color_group`, -/// `GraphicsState::color_group`). A device draws to at most [`width`](Self::width) color -/// attachments at once, the lesser of its `maxColorAttachments` and -/// `maxFragmentOutputAttachments`, at locations below it. A render pipeline whose attachments with -/// a pixel format ([`present`](Self::present)) number more draws them in groups of `width`, in the -/// order of their indices, each group a variant of the pipeline (`VariantKey::color_group`) that -/// writes its attachments at locations `0..`; one whose attachments number no more but reach an -/// index at or past `width` takes one group, renumbered below `width`. -#[non_exhaustive] -#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct ColorGroup { - /// The pipeline's color attachments with a pixel format, by index, ascending. - pub present: Vec, - /// The attachments a group holds: the lesser of the device's `maxColorAttachments` and - /// `maxFragmentOutputAttachments`. - pub width: u32, - /// The group: the attachments of [`present`](Self::present) from `group ยท width` on, `width` - /// of them or the rest. - pub group: u32, -} - -impl ColorGroup { - /// Group `group` of a pipeline whose attachments with a pixel format are `present` - /// (ascending) on a device that draws to `width` at once; `None` where every one of them is - /// below `width`, which the device draws in one pass at their own indices. - pub fn of(present: Vec, width: u32, group: u32) -> Option { - let beyond = present.last().is_some_and(|&last| last >= width); - beyond.then_some(ColorGroup { - present, - width, - group, - }) - } - - /// The attachments a group holds on `profile`: the lesser of its `maxColorAttachments` and - /// `maxFragmentOutputAttachments` (a subpass, or a dynamic rendering, holds at most the - /// first, `VUID-VkSubpassDescription-colorAttachmentCount-00845`, and a fragment shader's - /// outputs lie below the second, `VUID-RuntimeSpirv-Location-06272`). - pub fn width_on(profile: &crate::device::DeviceProfile) -> u32 { - let l = profile.limits(); - l.max_color_attachments - .min(l.max_fragment_output_attachments) - } - - /// The group's attachments, by location: attachment `colors()[l]` at location `l`. - pub fn colors(&self) -> &[u32] { - let width = self.width as usize; - let start = (self.group as usize).saturating_mul(width); - let end = start.saturating_add(width).min(self.present.len()); - self.present.get(start..end).unwrap_or(&[]) - } - - /// How many groups the pipeline's attachments take: one draw of the pipeline is one draw of - /// each group's variant. - pub fn groups(&self) -> u32 { - match self.width { - 0 => 0, - width => u32::try_from(self.present.len()) - .unwrap_or(u32::MAX) - .div_ceil(width), - } - } - - /// The location of Metal's color index `color` in the group's variant: an attachment of the - /// group at its place among [`colors`](Self::colors); every other index past them, in the order - /// of the indices, so no two indices share a location and none outside the group reaches one - /// below `colors().len()`. - pub fn location(&self, color: u32) -> u32 { - let colors = self.colors(); - match colors.iter().position(|&c| c == color) { - Some(at) => at as u32, - None => { - let below = colors.iter().filter(|&&c| c < color).count() as u32; - colors.len() as u32 + color - below - } - } - } -} - /// How the blend of an attachment held with its channels rotated reads the fragment function's /// first output there (`LoweringInputs::rotated_blends`). Apple's blend does not compute each /// factor pair alike in its color and alpha arithmetic, and the rotation moves Metal's blue into diff --git a/crates/metal2vulkan/src/pipeline/mod.rs b/crates/metal2vulkan/src/pipeline/mod.rs index f3f9666f3..c44858c84 100644 --- a/crates/metal2vulkan/src/pipeline/mod.rs +++ b/crates/metal2vulkan/src/pipeline/mod.rs @@ -131,8 +131,8 @@ pub use layout::{ }; pub use link::{heap_sampler_capacity, heap_unused_while_pending}; pub use lower_inputs::{ - AliasView, AmplificationDraws, BlendEquation, ChannelWrite, ColorGroup, ExtendedRangeColor, - FactorLane, FetchedAttachment, FramebufferFetchInputs, LoweringInputs, RotatedBlendForm, + AliasView, AmplificationDraws, BlendEquation, ChannelWrite, ExtendedRangeColor, FactorLane, + FetchedAttachment, FramebufferFetchInputs, LoweringInputs, RotatedBlendForm, StorageImageChoice, StorageImageClass, VertexFetch, VertexFetchProjection, }; pub use table::FunctionHandle; diff --git a/crates/metal2vulkan/src/pipeline/stage_io.rs b/crates/metal2vulkan/src/pipeline/stage_io.rs index 45c4d3b19..f98dc9b82 100644 --- a/crates/metal2vulkan/src/pipeline/stage_io.rs +++ b/crates/metal2vulkan/src/pipeline/stage_io.rs @@ -381,12 +381,6 @@ pub struct StageIo { /// Empty for every other function. #[cfg_attr(feature = "serde", serde(default))] pub zero_indices: Vec, - /// The group of its render pipeline's color attachments the fragment function writes - /// (`LoweringInputs::color_group`): its colors at locations `0..`. Link refuses the function - /// in a pipeline variant of another group (`NeedsInput(ColorWrites)`). `None` for a function - /// compiled with each color at its own index, and for every other function. - #[cfg_attr(feature = "serde", serde(default))] - pub color_group: Option, } /// The samplers a fragment function makes depth comparisons through ([`StageIo::depth_compares`]), diff --git a/crates/metal2vulkan/src/spirv/builder/module.rs b/crates/metal2vulkan/src/spirv/builder/module.rs index 5036dbc7c..7278d6328 100644 --- a/crates/metal2vulkan/src/spirv/builder/module.rs +++ b/crates/metal2vulkan/src/spirv/builder/module.rs @@ -852,16 +852,13 @@ impl ModuleBuilder { /// Decorate builtin output `g` `Invariant`: SPIR-V's "expressions computing its value be /// computed invariantly with respect to other shaders computing the same expressions". Only - /// the `Position` output (Metal's `[[invariant]]` position), the `ClipDistance` output (a - /// rate-mapped pass's copies of its triangles, `pipeline::link::fan_out`) and a fragment's - /// per-fragment outputs, `FragDepth`, `SampleMask` and `FragStencilRefEXT` (the variants of - /// one render pipeline's color groups, `LoweringInputs::color_group`), can be invariant. + /// the `Position` output (Metal's `[[invariant]]` position) and the `ClipDistance` output (a + /// rate-mapped pass's copies of its triangles, `pipeline::link::fan_out`) can be invariant. pub fn invariant(&mut self, g: GlobalId) -> BResult<()> { use crate::spv::BuiltIn as B; match self.global(g)?.kind { GlobalKind::BuiltIn { - builtin: - B::Position | B::ClipDistance | B::FragDepth | B::SampleMask | B::FragStencilRefEXT, + builtin: B::Position | B::ClipDistance, dir: IoDir::Output, } => { self.invariant.insert(g); diff --git a/crates/metal2vulkan/src/spirv/builder/tests.rs b/crates/metal2vulkan/src/spirv/builder/tests.rs index 3577d50d3..b2152b1a4 100644 --- a/crates/metal2vulkan/src/spirv/builder/tests.rs +++ b/crates/metal2vulkan/src/spirv/builder/tests.rs @@ -1065,11 +1065,10 @@ fn a_push_block_that_is_not_std430_uses_scalar_layout() { assert_eq!(m.push_members().len(), 2); } -/// Only the `Position` output (Metal `[[invariant]]`), the `ClipDistance` output (a rate-mapped -/// pass's copies) and a fragment's per-fragment outputs (the variants of a render pipeline's -/// color groups) can be decorated `Invariant`. +/// Only the `Position` output (Metal `[[invariant]]`) and the `ClipDistance` output (a +/// rate-mapped pass's copies) can be decorated `Invariant`. #[test] -fn only_the_position_clip_distances_and_per_fragment_outputs_are_invariant() { +fn only_the_position_and_clip_distances_are_invariant() { let mut t = T::new(); let f = t.f32(); let v4 = t.vec(f, 4); @@ -1091,8 +1090,7 @@ fn only_the_position_clip_distances_and_per_fragment_outputs_are_invariant() { .expect("varying"); assert_eq!(t.b.invariant(pos), Ok(())); assert_eq!(t.b.invariant(clips), Ok(())); - assert_eq!(t.b.invariant(depth), Ok(())); - for g in [size, color] { + for g in [depth, size, color] { assert_eq!( t.b.invariant(g), Err(BuildError::Global(GlobalRule::InvariantTarget)) diff --git a/crates/metal2vulkan/src/tests/engine_color_groups.rs b/crates/metal2vulkan/src/tests/engine_color_groups.rs deleted file mode 100644 index 8b047d3ee..000000000 --- a/crates/metal2vulkan/src/tests/engine_color_groups.rs +++ /dev/null @@ -1,531 +0,0 @@ -//! Render pipelines whose color attachments a device draws in groups -//! (`pipeline::compile::color_group`): the owned fixtures `engine/color_groups`, -//! `engine/color_groups_fetch`, `engine/dfk_dead_group` and `engine/dfk_dead_rog` on `lavapipe` -//! with four color attachments and four fragment output locations (Vulkan's floor, the device of -//! the groups' lane), on `moltenvk-m3` likewise, on `runtime-floor` likewise (below the runtime's -//! floor, which requires eight color attachments), and on `lavapipe` as it is (eight), where -//! nothing groups. `llvm-as` assembles the fixtures; a missing tool skips visibly. - -use std::collections::BTreeSet; - -use crate::budget::Budget; -use crate::cache::VariantKey; -use crate::device::requirements::VkLimit; -use crate::device::{Device, DevicePolicy}; -use crate::error::{Capability, Error, Feature, InternalKind, Needs, RuntimeInput}; -use crate::library::{FunctionConstantValue, FunctionConstantValues, Library}; -use crate::metal::{DataType, PixelFormat}; -use crate::pipeline::descriptor::{ - ColorAttachmentDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageSource, -}; -use crate::pipeline::testing::{description, engine_dir, llvm_assemble, AssembleError}; -use crate::pipeline::{ColorGroup, PrecisionNote, RenderPipeline, StageModule}; -use crate::spirv::testing::check_words_valid; -use crate::spv::BuiltIn; -use crate::vk; - -fn fixture(name: &str) -> Option> { - match llvm_assemble(&engine_dir().join(format!("{name}.ll"))) { - Ok(b) => Some(b), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {name}.ll: {why}"), - } -} - -/// `lavapipe` drawing to four color attachments at once. -fn four() -> Device { - narrowed("lavapipe") -} - -/// The committed profile `stem` drawing to four color attachments at once. -fn narrowed(stem: &str) -> Device { - let mut desc = description(stem).expect("profile"); - desc.limits.max_color_attachments = 4; - desc.limits.max_fragment_output_attachments = 4; - Device::from_queries(desc, DevicePolicy::default()).expect("device") -} - -fn device(stem: &str) -> Device { - Device::from_queries(description(stem).expect("profile"), DevicePolicy::default()) - .expect("device") -} - -/// A different format at each color index, so an attachment's place in a group shows. -const FORMATS: [PixelFormat; 8] = [ - PixelFormat::RGBA8Unorm, - PixelFormat::RGBA16Float, - PixelFormat::RGBA32Float, - PixelFormat::BGRA8Unorm, - PixelFormat::RG16Float, - PixelFormat::RGBA8UnormSRGB, - PixelFormat::R32Float, - PixelFormat::RG32Float, -]; - -/// The pipeline of `cg_cover` and fragment function `fragment` of module `fs`, with attachments -/// at `colors`. -fn pipeline(vs: &[u8], fs: &[u8], fragment: &str, colors: &[u32]) -> RenderPipelineDescriptor { - let function = |bc: &[u8], name: &str| { - FunctionDescriptor::new( - Library::from_air(bc) - .expect("library") - .function(name) - .expect("function"), - ) - }; - let mut d = RenderPipelineDescriptor::new(StageSource::Function(function(vs, "cg_cover"))); - d.fragment = Some(StageSource::Function(function(fs, fragment))); - for &c in colors { - d.color_attachments[c as usize] = Some(ColorAttachmentDescriptor::new(FORMATS[c as usize])); - } - d -} - -fn compile( - dev: &Device, - d: &RenderPipelineDescriptor, - group: u32, -) -> Result { - let mut v = VariantKey::new(); - v.color_group = group; - dev.compile_render_variant(d, &v, &Budget::standard()) -} - -fn stage(p: &RenderPipeline, s: vk::ShaderStage) -> &StageModule { - p.stages.iter().find(|m| m.stage == s).expect("stage") -} - -/// Each instruction of `words` past the header: its opcode and operands. -fn instructions(words: &[u32]) -> Vec<(u32, &[u32])> { - let mut out = Vec::new(); - let mut at = 5; - while at < words.len() { - let len = (words[at] >> 16) as usize; - out.push((words[at] & 0xffff, &words[at + 1..at + len])); - at += len.max(1); - } - out -} - -const OP_VARIABLE: u32 = 59; -const OP_DECORATE: u32 = 71; -const STORAGE_OUTPUT: u32 = 3; -const DECORATION_BUILTIN: u32 = 11; -const DECORATION_INVARIANT: u32 = 18; -const DECORATION_LOCATION: u32 = 30; - -/// The locations of `words`' output variables. -fn output_locations(words: &[u32]) -> BTreeSet { - let insts = instructions(words); - let outputs: BTreeSet = insts - .iter() - .filter(|(op, o)| *op == OP_VARIABLE && o.get(2) == Some(&STORAGE_OUTPUT)) - .map(|(_, o)| o[1]) - .collect(); - insts - .iter() - .filter(|(op, o)| *op == OP_DECORATE && o.get(1) == Some(&DECORATION_LOCATION)) - .filter(|(_, o)| outputs.contains(&o[0])) - .map(|(_, o)| o[2]) - .collect() -} - -/// The builtins `words` decorates `Invariant`. -fn invariant_builtins(words: &[u32]) -> BTreeSet { - let insts = instructions(words); - let invariant: BTreeSet = insts - .iter() - .filter(|(op, o)| *op == OP_DECORATE && o.get(1) == Some(&DECORATION_INVARIANT)) - .map(|(_, o)| o[0]) - .collect(); - insts - .iter() - .filter(|(op, o)| *op == OP_DECORATE && o.get(1) == Some(&DECORATION_BUILTIN)) - .filter(|(_, o)| invariant.contains(&o[0])) - .map(|(_, o)| o[2]) - .collect() -} - -/// Every stage of `p` passes L3 on `dev`. -fn validate(p: &RenderPipeline, dev: &Device) { - for m in &p.stages { - check_words_valid(&m.spirv, &p.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{:?}: L3: {e}", m.stage)); - } -} - -/// The formats of `p`'s color attachments, in order. -fn formats(p: &RenderPipeline) -> Vec> { - p.graphics - .color_attachments - .iter() - .map(|a| a.as_ref().map(|a| a.format)) - .collect() -} - -/// The formats `p`'s attachments at Metal's indices `colors` take on `lavapipe`, which draws -/// every one at its own index: what a group of them holds, in order. -fn reference(d: &RenderPipelineDescriptor, colors: &[u32]) -> Vec> { - let whole = formats(&compile(&device("lavapipe"), d, 0).expect("lavapipe")); - colors.iter().map(|&c| whole[c as usize]).collect() -} - -/// The limit refusal of a pipeline whose attachments reach index `required - 1` on a device of four. -fn is_limit(e: &Error, required: u64) -> bool { - matches!(e, Error::Unsupported(u) if u.feature == Feature::InterfaceComponents - && u.needs == Needs::AnyOf(vec![vec![Capability::Limit { - limit: VkLimit::MaxColorAttachments, - required, - available: 4, - }]])) -} - -/// Five colors on a device of four draw in two groups: the first four attachments, then the -/// fifth, each variant's fragment stage writing its group's alone at locations `0..` in a state of -/// its group's attachments alone, every variant's vertex stage the same module, and each variant -/// noting the groups. A variant past the last group is no plan's. On `runtime-floor` of four too; on -/// `lavapipe` as it is, one pipeline of five, no note. -#[test] -fn five_colors_on_a_device_of_four_draw_in_two_groups() { - let Some(bc) = fixture("color_groups") else { - return; - }; - let d = pipeline(&bc, &bc, "cg_five", &[0, 1, 2, 3, 4]); - for (stem, dev) in [ - ("four", four()), - ("runtime-floor of four", narrowed("runtime-floor")), - ] { - let groups: Vec = (0..2) - .map(|g| compile(&dev, &d, g).unwrap_or_else(|e| panic!("{stem} group {g}: {e}"))) - .collect(); - for (g, (p, colors)) in groups.iter().zip([vec![0, 1, 2, 3], vec![4]]).enumerate() { - let group = p.graphics.color_group.as_ref().expect("a group"); - assert_eq!(group.colors(), colors, "{stem} group {g}"); - assert_eq!(group.groups(), 2, "{stem} group {g}"); - if stem == "four" { - assert_eq!(formats(p), reference(&d, &colors), "{stem} group {g}"); - } - assert_eq!(formats(p).len(), colors.len(), "{stem} group {g}"); - let fragment = stage(p, vk::ShaderStage::FRAGMENT); - assert_eq!( - output_locations(&fragment.spirv), - (0..colors.len() as u32).collect(), - "{stem} group {g}" - ); - assert!( - fragment - .precision_notes - .contains(&PrecisionNote::ColorAttachmentGroups), - "{stem} group {g}: {:?}", - fragment.precision_notes - ); - validate(p, &dev); - } - assert_eq!( - stage(&groups[0], vk::ShaderStage::VERTEX).spirv, - stage(&groups[1], vk::ShaderStage::VERTEX).spirv, - "{stem}: the vertex stage differs between groups" - ); - assert_ne!(groups[0].key, groups[1].key, "{stem}"); - match compile(&dev, &d, 2) { - Err(Error::Internal(e)) => assert_eq!(e.kind, InternalKind::Invariant, "{stem}"), - other => panic!("{stem}: {other:?}"), - } - } - let dev = device("lavapipe"); - let p = compile(&dev, &d, 0).expect("lavapipe"); - assert_eq!(p.graphics.color_group, None); - assert_eq!(formats(&p).len(), 5); - let fragment = stage(&p, vk::ShaderStage::FRAGMENT); - assert_eq!(output_locations(&fragment.spirv), (0..5).collect()); - assert!(!fragment - .precision_notes - .contains(&PrecisionNote::ColorAttachmentGroups)); - assert!( - compile(&dev, &d, 1).is_err(), - "lavapipe draws no second group" - ); -} - -/// Seven colors take two groups, the second of three; colors 0 and 5 take one group, renumbered -/// below four with no note, as the colors present are numbered whatever their indices; a pipeline -/// whose colors are all below four takes none. -#[test] -fn groups_number_the_attachments_present_densely() { - let Some(bc) = fixture("color_groups") else { - return; - }; - let dev = four(); - let seven = pipeline(&bc, &bc, "cg_seven", &[0, 1, 2, 3, 4, 5, 6]); - let p = compile(&dev, &seven, 1).expect("seven, group 1"); - let group = p.graphics.color_group.as_ref().expect("a group"); - assert_eq!((group.colors(), group.groups()), (&[4, 5, 6][..], 2)); - assert_eq!(formats(&p), reference(&seven, &[4, 5, 6])); - assert_eq!( - output_locations(&stage(&p, vk::ShaderStage::FRAGMENT).spirv), - BTreeSet::from([0, 1, 2]) - ); - validate(&p, &dev); - - let sparse = pipeline(&bc, &bc, "cg_sparse", &[0, 5]); - let p = compile(&dev, &sparse, 0).expect("sparse"); - assert_eq!( - p.graphics.color_group, - Some(ColorGroup { - present: vec![0, 5], - width: 4, - group: 0, - }) - ); - assert_eq!(formats(&p), reference(&sparse, &[0, 5])); - let fragment = stage(&p, vk::ShaderStage::FRAGMENT); - assert_eq!(output_locations(&fragment.spirv), BTreeSet::from([0, 1])); - assert!(!fragment - .precision_notes - .contains(&PrecisionNote::ColorAttachmentGroups)); - assert!(invariant_builtins(&fragment.spirv).is_empty()); - validate(&p, &dev); - assert!(matches!( - compile(&dev, &sparse, 1), - Err(Error::Internal(e)) if e.kind == InternalKind::Invariant - )); - - let low = pipeline(&bc, &bc, "cg_sparse", &[0, 3]); - let p = compile(&dev, &low, 0).expect("colors 0 and 3"); - assert_eq!(p.graphics.color_group, None); -} - -/// A variant of a pipeline of more than one group decorates its fragment's `FragDepth` and -/// `SampleMask` `Invariant`, beside the vertex stage's `Position`; a pipeline of one group, or -/// none, decorates the position alone. -#[test] -fn a_grouped_fragment_s_per_fragment_outputs_are_invariant() { - let Some(bc) = fixture("color_groups") else { - return; - }; - let d = pipeline(&bc, &bc, "cg_depth", &[0, 1, 2, 3, 4]); - let per_fragment = BTreeSet::from([BuiltIn::FragDepth as u32, BuiltIn::SampleMask as u32]); - let dev = four(); - for g in 0..2 { - let p = compile(&dev, &d, g).unwrap_or_else(|e| panic!("group {g}: {e}")); - let fragment = stage(&p, vk::ShaderStage::FRAGMENT); - assert_eq!( - invariant_builtins(&fragment.spirv), - per_fragment, - "group {g}" - ); - assert_eq!( - invariant_builtins(&stage(&p, vk::ShaderStage::VERTEX).spirv), - BTreeSet::from([BuiltIn::Position as u32]), - "group {g}" - ); - validate(&p, &dev); - } - let p = compile(&device("lavapipe"), &d, 0).expect("lavapipe"); - assert!(invariant_builtins(&stage(&p, vk::ShaderStage::FRAGMENT).spirv).is_empty()); -} - -/// What each group's draw would run again, or read from another group, is the pipeline's limit -/// refusal: a fragment function that writes memory, alpha to coverage, and a read of a color of -/// another group. A read of a color in a pipeline of one group is that group's own, renumbered with -/// it. A fragment compiled for another group than the variant's is `NeedsInput(ColorWrites)`. -#[test] -fn what_each_group_would_run_again_is_the_limit_refusal() { - let (Some(bc), Some(fetch)) = (fixture("color_groups"), fixture("color_groups_fetch")) else { - return; - }; - let dev = four(); - let counts = pipeline(&bc, &bc, "cg_counts", &[0, 1, 2, 3, 4]); - let e = compile(&dev, &counts, 0).expect_err("a fragment that writes memory"); - assert!(is_limit(&e, 5), "{e:?}"); - - let mut covered = pipeline(&bc, &bc, "cg_five", &[0, 1, 2, 3, 4]); - covered.alpha_to_coverage = true; - let e = compile(&dev, &covered, 1).expect_err("alpha to coverage"); - assert!(is_limit(&e, 5), "{e:?}"); - - let fetched = pipeline(&bc, &fetch, "cg_fetch", &[0, 1, 2, 3, 4]); - let e = compile(&dev, &fetched, 0).expect_err("a read of color 4 in group 0"); - assert!(is_limit(&e, 5), "{e:?}"); - - let sparse = pipeline(&bc, &fetch, "cg_fetch_sparse", &[0, 5]); - let p = compile(&dev, &sparse, 0).expect("a read of color 5 in its own group"); - assert_eq!(formats(&p), reference(&sparse, &[0, 5])); - validate(&p, &dev); - - // Group 0's fragment, compiled alone, in group 1's variant. - let d = pipeline(&bc, &bc, "cg_five", &[0, 1, 2, 3, 4]); - let keys = dev - .render_variant_key( - &d, - &VariantKey::new(), - &Budget::standard(), - &crate::pipeline::compile::StageEntries::new(), - ) - .expect("keys"); - let Some(StageSource::Function(f)) = &d.fragment else { - unreachable!() - }; - let inputs = keys.fragment_inputs.expect("the fragment's inputs"); - assert!(inputs.color_group.is_some()); - let first = dev - .compile_function(f, &inputs, &Budget::standard()) - .expect("group 0's fragment"); - let mut mixed = d.clone(); - mixed.fragment = Some(StageSource::Compiled(first)); - compile(&dev, &mixed, 0).expect("group 0's fragment in group 0"); - assert!(matches!( - compile(&dev, &mixed, 1), - Err(Error::NeedsInput(RuntimeInput::ColorWrites)) - )); -} - -/// [`pipeline`] of `cg_cover` and `fragment` of `fs` at `colors`, the fragment function -/// specialized with its `bool` function constant 0 `on`. -fn specialized( - vs: &[u8], - fs: &[u8], - fragment: &str, - colors: &[u32], - on: bool, -) -> RenderPipelineDescriptor { - let mut d = pipeline(vs, fs, fragment, colors); - if let Some(StageSource::Function(f)) = d.fragment.as_mut() { - f.constants = FunctionConstantValues::defaults().with_index( - 0, - FunctionConstantValue::new(DataType::Bool, [u8::from(on)]), - ); - f.specialized = true; - } - d -} - -/// A read of a color of another group that the function's constants make dead reads nothing -/// (`dfk_dead_group`: `dfg_branch`, the read of color 4 in the arm of a branch on constant 0, and -/// `dfg_gated`, whose color 4 input the constant gates). Five colors on a device of four draw in -/// two groups, color 4 in the second; on `lavapipe` of four (input attachments), `moltenvk-m3` of -/// four (the pixel interlock) and `runtime-floor` of four (no ordered fetch form), specialized with -/// the read dead, each group's variant compiles as a pipeline of its group's attachments that reads -/// none (no input or storage attachment, every color a color attachment), passing L3. Specialized -/// live, group 0's variant, which would read color 4 of group 1, is the pipeline's limit refusal. -/// The misses are counted by kind before the test fails. -#[test] -fn a_read_of_another_group_dead_after_specialization_is_no_refusal() { - let (Some(bc), Some(fs)) = (fixture("color_groups"), fixture("dfk_dead_group")) else { - return; - }; - let colors = [0, 1, 2, 3, 4]; - let devices = [ - ("lavapipe of four", four()), - ("moltenvk-m3 of four", narrowed("moltenvk-m3")), - ("runtime-floor of four", narrowed("runtime-floor")), - ]; - let mut misses = std::collections::BTreeMap::>::new(); - let mut checked = 0; - for (name, dev) in &devices { - for entry in ["dfg_branch", "dfg_gated"] { - let dead = specialized(&bc, &fs, entry, &colors, false); - for (group, held) in [(0u32, &colors[..4]), (1, &colors[4..])] { - let what = format!("{name} {entry} dead, group {group}"); - let p = match compile(dev, &dead, group) { - Ok(p) => p, - Err(e) => { - let kind = match is_limit(&e, 5) { - true => "refused at the limit".to_owned(), - false => format!("refused otherwise: {e}"), - }; - misses.entry(kind).or_default().push(what); - continue; - } - }; - assert_eq!(formats(&p), reference(&dead, held), "{what}"); - assert!(p.graphics.input_attachments.is_empty(), "{what}"); - assert!(p.graphics.storage_attachments.is_empty(), "{what}"); - validate(&p, dev); - checked += 1; - } - let live = specialized(&bc, &fs, entry, &colors, true); - let e = compile(dev, &live, 0).expect_err("a read of color 4 in group 0"); - assert!(is_limit(&e, 5), "{name} {entry} live, group 0: {e:?}"); - } - } - for (kind, whats) in &misses { - eprintln!("{}: {kind} (first: {})", whats.len(), whats[0]); - } - assert!(misses.is_empty(), "{misses:#?}"); - assert_eq!(checked, devices.len() * 2 * 2); -} - -/// Whether `words` interlocks: an interlock execution mode (`PixelInterlockOrderedEXT` 5366 to -/// `ShadingRateInterlockUnorderedEXT` 5371) or an `OpBeginInvocationInterlockEXT` (5364). -fn interlocks(words: &[u32]) -> bool { - const OP_EXECUTION_MODE: u32 = 16; - const OP_BEGIN_INTERLOCK: u32 = 5364; - instructions(words).iter().any(|(op, o)| { - *op == OP_BEGIN_INTERLOCK - || (*op == OP_EXECUTION_MODE && o.get(1).is_some_and(|m| (5366..=5371).contains(m))) - }) -} - -/// A raster order group on an input the function's constants make dead orders nothing, in a -/// pipeline of groups as in any (`dfk_dead_rog`: `dfr_color`, a color 0 input in group 0, and -/// `dfr_buffer`, a buffer in group 0, each read in the arm of a branch on constant 0; plain Metal -/// makes and draws both, dead and live). Five colors on a device of four draw in two groups; on -/// `lavapipe` and `moltenvk-m3` of four (each with the pixel interlock) and `runtime-floor` of four -/// (without), specialized with the read dead, each group's variant compiles as a pipeline of its -/// group's attachments without an interlock, an input or a storage attachment, passing L3. -/// Specialized live, group 0's variant, which would order its read in each group's draw, is the -/// pipeline's limit refusal. The misses are counted by kind before the test fails. -#[test] -fn a_raster_order_group_dead_after_specialization_is_no_refusal_in_groups() { - let (Some(bc), Some(fs)) = (fixture("color_groups"), fixture("dfk_dead_rog")) else { - return; - }; - let colors = [0, 1, 2, 3, 4]; - let devices = [ - ("lavapipe of four", four()), - ("moltenvk-m3 of four", narrowed("moltenvk-m3")), - ("runtime-floor of four", narrowed("runtime-floor")), - ]; - let mut misses = std::collections::BTreeMap::>::new(); - let mut checked = 0; - for (name, dev) in &devices { - for entry in ["dfr_color", "dfr_buffer"] { - let dead = specialized(&bc, &fs, entry, &colors, false); - for (group, held) in [(0u32, &colors[..4]), (1, &colors[4..])] { - let what = format!("{name} {entry} dead, group {group}"); - let p = match compile(dev, &dead, group) { - Ok(p) => p, - Err(e) => { - let kind = match is_limit(&e, 5) { - true => "refused at the limit".to_owned(), - false => format!("refused otherwise: {e}"), - }; - misses.entry(kind).or_default().push(what); - continue; - } - }; - if interlocks(&stage(&p, vk::ShaderStage::FRAGMENT).spirv) { - misses.entry("interlocked".into()).or_default().push(what); - continue; - } - assert_eq!(formats(&p), reference(&dead, held), "{what}"); - assert!(p.graphics.input_attachments.is_empty(), "{what}"); - assert!(p.graphics.storage_attachments.is_empty(), "{what}"); - validate(&p, dev); - checked += 1; - } - let live = specialized(&bc, &fs, entry, &colors, true); - let e = compile(dev, &live, 0).expect_err("a raster order group in group 0"); - assert!(is_limit(&e, 5), "{name} {entry} live, group 0: {e:?}"); - } - } - for (kind, whats) in &misses { - eprintln!("{}: {kind} (first: {})", whats.len(), whats[0]); - } - assert!(misses.is_empty(), "{misses:#?}"); - assert_eq!(checked, devices.len() * 2 * 2); -} diff --git a/crates/metal2vulkan/src/tests/engine_primitive_ids.rs b/crates/metal2vulkan/src/tests/engine_primitive_ids.rs index d8369789f..97cf0a2e1 100644 --- a/crates/metal2vulkan/src/tests/engine_primitive_ids.rs +++ b/crates/metal2vulkan/src/tests/engine_primitive_ids.rs @@ -333,32 +333,6 @@ fn the_fragment_reads_the_id_flat() { assert_eq!(flat, 3); } -/// With five colors on a device of four, each color group's variant reads the ID from the same -/// varying of the same vertex module: the groups' vertex words are identical, and the varying -/// takes one location beside the vertex function's own. -#[test] -fn color_groups_share_the_vertex_function_s_id() { - let Some(bc) = fixture() else { return }; - let dev = withheld(4); - let d = pipeline(&bc, "pi_place", Some("pi_five"), 5); - let groups: Vec = (0..2) - .map(|g| { - let mut v = VariantKey::new(); - v.color_group = g; - dev.compile_render_variant(&d, &v, &Budget::standard()) - .unwrap_or_else(|e| panic!("group {g}: {e}")) - }) - .collect(); - for p in &groups { - assert!(reads_layout(p)); - validate(p, &dev); - } - assert_eq!( - stage(&groups[0], vk::ShaderStage::VERTEX).spirv, - stage(&groups[1], vk::ShaderStage::VERTEX).spirv - ); -} - // ---- Indexed draws: the de-indexed form (VariantKey::primitive_id_indices) ------------------- /// A state binding `pi_place`'s and `pi_counts`' buffers, at device addresses. diff --git a/crates/metal2vulkan/src/tests/mod.rs b/crates/metal2vulkan/src/tests/mod.rs index 7a86d77d6..4949227e4 100644 --- a/crates/metal2vulkan/src/tests/mod.rs +++ b/crates/metal2vulkan/src/tests/mod.rs @@ -34,7 +34,6 @@ mod engine_binder; mod engine_bit_manipulation; mod engine_buffer_table; mod engine_chosen_pointers; -mod engine_color_groups; mod engine_compute_limits; mod engine_convert_rounding; mod engine_copy; diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index e4a01b543..8f4c15343 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2403,7 +2403,6 @@ field metal2vulkan::cache::VariantKey.addressed_function_tables pub addressed_fu field metal2vulkan::cache::VariantKey.amplification_draws pub amplification_draws: Option field metal2vulkan::cache::VariantKey.anisotropic_samplers pub anisotropic_samplers: BTreeSet field metal2vulkan::cache::VariantKey.call_threadgroups pub call_threadgroups: bool -field metal2vulkan::cache::VariantKey.color_group pub color_group: u32 field metal2vulkan::cache::VariantKey.cross_class pub cross_class: BTreeMap field metal2vulkan::cache::VariantKey.cubic_samplers pub cubic_samplers: BTreeMap field metal2vulkan::cache::VariantKey.depth_clamp_range pub depth_clamp_range: bool @@ -2818,9 +2817,6 @@ field metal2vulkan::pipeline::ColorAttachmentDescriptor.write_mask pub write_mas field metal2vulkan::pipeline::ColorAttachmentState.blend pub blend: Option field metal2vulkan::pipeline::ColorAttachmentState.format pub format: vk::Format field metal2vulkan::pipeline::ColorAttachmentState.write_mask pub write_mask: vk::ColorComponentFlags -field metal2vulkan::pipeline::ColorGroup.group pub group: u32 -field metal2vulkan::pipeline::ColorGroup.present pub present: Vec -field metal2vulkan::pipeline::ColorGroup.width pub width: u32 field metal2vulkan::pipeline::CombinedSampler.compare pub compare: bool field metal2vulkan::pipeline::CombinedSampler.integer pub integer: bool field metal2vulkan::pipeline::CombinedSampler.sampler pub sampler: SamplerRef @@ -2904,7 +2900,6 @@ field metal2vulkan::pipeline::FunctionDescriptor.specialized pub specialized: bo field metal2vulkan::pipeline::GraphicsState.alpha_to_coverage pub alpha_to_coverage: bool field metal2vulkan::pipeline::GraphicsState.alpha_to_one pub alpha_to_one: bool field metal2vulkan::pipeline::GraphicsState.color_attachments pub color_attachments: Vec> -field metal2vulkan::pipeline::GraphicsState.color_group pub color_group: Option field metal2vulkan::pipeline::GraphicsState.color_outputs pub color_outputs: u32 field metal2vulkan::pipeline::GraphicsState.declares_layer pub declares_layer: bool field metal2vulkan::pipeline::GraphicsState.depth_format pub depth_format: Option @@ -2966,7 +2961,6 @@ field metal2vulkan::pipeline::LoweringInputs.alpha_test pub alpha_test: Option field metal2vulkan::pipeline::LoweringInputs.anisotropic_samplers pub anisotropic_samplers: BTreeSet field metal2vulkan::pipeline::LoweringInputs.call_threadgroups pub call_threadgroups: bool -field metal2vulkan::pipeline::LoweringInputs.color_group pub color_group: Option field metal2vulkan::pipeline::LoweringInputs.color_writes pub color_writes: BTreeMap; 4]> field metal2vulkan::pipeline::LoweringInputs.cross_class pub cross_class: BTreeMap field metal2vulkan::pipeline::LoweringInputs.cubic_samplers pub cubic_samplers: BTreeMap @@ -7213,11 +7207,6 @@ method metal2vulkan::pipeline::BufferForm::uniform_view pub fn uniform_view(self method metal2vulkan::pipeline::ColorAttachmentDescriptor::new pub fn new(pixel_format: metal::PixelFormat) -> ColorAttachmentDescriptor method metal2vulkan::pipeline::ColorAttachmentDescriptor::specialized #[must_use] pub fn specialized(&self) -> ColorAttachmentDescriptor method metal2vulkan::pipeline::ColorAttachmentState::new pub fn new(format: vk::Format, write_mask: vk::ColorComponentFlags, blend: Option) -> ColorAttachmentState -method metal2vulkan::pipeline::ColorGroup::colors pub fn colors(&self) -> &[u32] -method metal2vulkan::pipeline::ColorGroup::groups pub fn groups(&self) -> u32 -method metal2vulkan::pipeline::ColorGroup::location pub fn location(&self, color: u32) -> u32 -method metal2vulkan::pipeline::ColorGroup::of pub fn of(present: Vec, width: u32, group: u32) -> Option -method metal2vulkan::pipeline::ColorGroup::width_on pub fn width_on(profile: &crate::device::DeviceProfile) -> u32 method metal2vulkan::pipeline::CombinedSampler::constexpr_sampler pub fn constexpr_sampler(&self, profile: &crate::device::DeviceProfile) -> Result, crate::error::Error> method metal2vulkan::pipeline::CombinedSampler::from_heap_index pub fn from_heap_index(sampler: SamplerRef, index: u32) -> CombinedSampler method metal2vulkan::pipeline::CombinedSampler::heap_index pub fn heap_index(&self) -> u32 @@ -7827,7 +7816,6 @@ struct metal2vulkan::pipeline::BlendState #[cfg_attr(feature = "serde", derive(s struct metal2vulkan::pipeline::BufferSlot #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct BufferSlot struct metal2vulkan::pipeline::ColorAttachmentDescriptor #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ColorAttachmentDescriptor struct metal2vulkan::pipeline::ColorAttachmentState #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ColorAttachmentState -struct metal2vulkan::pipeline::ColorGroup #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct ColorGroup struct metal2vulkan::pipeline::CombinedSampler #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct CombinedSampler struct metal2vulkan::pipeline::CommandWrites #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct CommandWrites struct metal2vulkan::pipeline::CompileReport #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct CompileReport @@ -9294,7 +9282,6 @@ variant metal2vulkan-runtime::PrecisionNote::BicubicFilterArithmetic BicubicFilt variant metal2vulkan-runtime::PrecisionNote::BlendedWriteRounding BlendedWriteRounding variant metal2vulkan-runtime::PrecisionNote::CappedLodBias CappedLodBias variant metal2vulkan-runtime::PrecisionNote::ClippedCoverageSplit ClippedCoverageSplit -variant metal2vulkan-runtime::PrecisionNote::ColorAttachmentGroups ColorAttachmentGroups variant metal2vulkan-runtime::PrecisionNote::CompressedTexelDecode CompressedTexelDecode variant metal2vulkan-runtime::PrecisionNote::CoverageReadsRoundedAlpha CoverageReadsRoundedAlpha variant metal2vulkan-runtime::PrecisionNote::CubeGradientFootprint CubeGradientFootprint @@ -10904,7 +10891,6 @@ variant metal2vulkan::pipeline::PrecisionNote::BicubicFilterArithmetic BicubicFi variant metal2vulkan::pipeline::PrecisionNote::BlendedWriteRounding BlendedWriteRounding variant metal2vulkan::pipeline::PrecisionNote::CappedLodBias CappedLodBias variant metal2vulkan::pipeline::PrecisionNote::ClippedCoverageSplit ClippedCoverageSplit -variant metal2vulkan::pipeline::PrecisionNote::ColorAttachmentGroups ColorAttachmentGroups variant metal2vulkan::pipeline::PrecisionNote::CompressedTexelDecode CompressedTexelDecode variant metal2vulkan::pipeline::PrecisionNote::CoverageReadsRoundedAlpha CoverageReadsRoundedAlpha variant metal2vulkan::pipeline::PrecisionNote::CubeGradientFootprint CubeGradientFootprint diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index 8969c6aca..d57922360 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -401,7 +401,6 @@ surface! { struct AmplificationDraws N; struct BlendEquation N; enum ChannelWrite N; - struct ColorGroup N; struct ExtendedRangeColor N; enum FactorLane N; struct FetchedAttachment N; diff --git a/docs/API.md b/docs/API.md index bc240bbde..06c10bcff 100644 --- a/docs/API.md +++ b/docs/API.md @@ -906,27 +906,10 @@ Where Metal's rules differ from Vulkan's, the pipeline gives Metal's answer: the list, at the list's address (`PushHole::CaptureIndexAddress`), adding them as Metal's vertex ID wraps, so each position runs once and the positions count Metal's primitives. - A device draws to at most the lesser of its `maxColorAttachments` and - `maxFragmentOutputAttachments` color attachments at once (four at Vulkan's floor), where Metal - takes eight. A pipeline whose attachments with a pixel format number more draws them in groups - of that many, in the order of their indices: variant `VariantKey::color_group` of the pipeline - draws one group, its fragment function writing that group's attachments alone at locations `0..` - and its `graphics` holding them alone (`graphics.color_group`, a `ColorGroup`; - `ColorGroup::of(present, width, group)` names a group, and `ColorGroup::width_on(profile)` is a - device's group width). A pipeline whose - attachments number no more but reach an index at or past the count (`color(0)` and `color(5)` on - a device of four) takes one group, renumbered. Every group's variant has the same vertex module; - where there is more than one group, their fragment stages' `FragDepth`, `SampleMask` and - `FragStencilRefEXT` are decorated `Invariant` and record - `PrecisionNote::ColorAttachmentGroups`. What each group's draw would run again or read from - another group is the pipeline's limit refusal (`InterfaceComponents` at `MaxColorAttachments`): - a vertex or fragment function that writes memory, alpha to coverage, a tessellation pipeline, a - `[[color(n)]]` input of another group that the specialized function reads (one whose read its - function constants fold away reads nothing and is not refused), imageblocks, and a raster order - group on a color output or on a parameter the specialized function uses (one on a parameter it - never uses orders nothing and is not refused). Mesh and tile pipelines take no groups. The - runtime draws such a pass group by group, each group's colors in a pass of its own over a twin - of the depth and stencil (the runtime's `render/color_groups.rs`; what it refuses there is - `RuntimeGap::ColorAttachmentGroups`). + `maxFragmentOutputAttachments` color attachments at once (eight at the runtime's floor), where + Metal takes eight. A pipeline with an attachment at an index at or past the first is refused + `InterfaceComponents` at `MaxColorAttachments`, and a fragment function with a color output at + a location at or past the second at `MaxFragmentOutputAttachments`. - A pipeline's band variant (`VariantKey::line_band`, of a `BandPrimitive`) draws each line, or each edge of a triangle in fill mode `Lines`, as the parallelogram Metal draws for a line under Apple's `setLineWidth:` at a width the device's own lines do not draw (the runtime chooses @@ -2662,16 +2645,6 @@ bound. where a texture its handles can name is one (`SpecKey::HeapRawTextures`, which the binding plan gives from the textures the command makes resident or binds), so a reading of the module alone holds it, and so does a command that can name one. -- `metal2vulkan-degrade-color-attachment-groups` (precision). - `PrecisionNote::ColorAttachmentGroups`: A render pipeline whose color attachments the device - draws in more than one group (more than the lesser of its `maxColorAttachments` and - `maxFragmentOutputAttachments`, four on a device at Vulkan's floor): each draw runs once per - group, each group's variant writing its own attachments over its own copy of the depth and - stencil the pass loads. Every variant's vertex stage is the same module, `Position` invariant, - and every fragment variant's `FragDepth`, `SampleMask` and `FragStencilRefEXT` are decorated - `Invariant`; Vulkan promises no more across pipelines of other fragment modules and attachments. - Groups past the first may differ at discard or depth edges if the driver compiles the variants - differently. - `metal2vulkan-degrade-device-fragment-runs` (precision). `PrecisionNote::DeviceFragmentRuns`: A fragment function that writes memory (`StageInterface::writes_memory`) in a render pipeline of more than one sample, which the pipeline's compile records on its fragment stage, decided by the diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 3b1aee219..2c0b9de97 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -124,7 +124,7 @@ Columns: | `DivergentInterpolation` | Metal's pull-model interpolation at a sample or an offset (`interpolate_at_sample`, `interpolate_at_offset`) outside the fragment function's first... | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/lower/stage_io/plan.rs (interpolant_reads)` | `rare`: an interpolant read at a sample or an offset in a branch, a loop or after a discard | | `SamplePositions` | A render pass's custom sample positions (`setSamplePositions:count:`) on a device that takes no custom sample locations at the pass's sample... | - | `-` | 0 | `rare`: custom sample positions on a device that takes none at the pass's sample count | | `PixelCoverageAtSampleRate` | The pixel's coverage (`[[sample_mask]]` read) in a fragment function that runs once per sample | every device (no Vulkan mechanism); every device (not implemented) | `ours` | 2: `crates/metal2vulkan/src/lower/simd/mod.rs (select_param)`, `crates/metal2vulkan/src/pipeline/link/graphics.rs (sample_invocations)` | `rare`: coverage read at sample rate | -| `InterfaceComponents` | Too many interface components or locations | devices short of a device limit the site names; devices without VkLimit::MaxColorAttachments; devices without VkLimit::MaxVertexInputAttributes | `device` | 4: `crates/metal2vulkan/src/pipeline/compile/color_group.rs (refusal)`, `crates/metal2vulkan/src/pipeline/link/graphics.rs (graphics_state)` (+2) | `rare`: too many varyings or attachments for a device | +| `InterfaceComponents` | Too many interface components or locations | devices short of a device limit the site names; devices without VkLimit::MaxColorAttachments; devices without VkLimit::MaxVertexInputAttributes | `device` | 3: `crates/metal2vulkan/src/pipeline/link/graphics.rs (graphics_state)`, `crates/metal2vulkan/src/pipeline/link/varyings.rs (assign)` (+1) | `rare`: too many varyings or attachments for a device | | `UnmatchedVarying` | A fragment input without a vertex producer (a Metal link error) | every device (no Vulkan mechanism) | `device` | 3: `crates/metal2vulkan/src/pipeline/link/varyings.rs (mesh_fragment)`, `crates/metal2vulkan/src/pipeline/link/varyings.rs (varyings, 2 sites)` | `none`: a Metal link error | | `KernelStageIn` | Kernel `[[stage_in]]` | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/lower/stage_io/stage_in.rs (select)` | `rare`: kernel stage-in combinations Metal leaves unestablished | | `VertexStepRate` | A vertex buffer layout stepped per instance at a rate above 1, on a profile that fetches every attribute in fixed function (the identity domains,... | devices without a capability the site computes (`needs`) | `device` | 1: `crates/metal2vulkan/src/metal/vertex.rs (divided)` | `app`: instanced vertex layouts stepped at a rate above 1 | @@ -463,7 +463,7 @@ Each refusal's sites, with the function that builds it. - `feature::PullModelInterpolation`: `crates/metal2vulkan/src/lower/fragment/interpolate.rs (select, 2 sites)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (interpolant, 2 sites)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (interpolant_reads)` - `feature::DivergentInterpolation`: `crates/metal2vulkan/src/lower/stage_io/plan.rs (interpolant_reads)` - `feature::PixelCoverageAtSampleRate`: `crates/metal2vulkan/src/lower/simd/mod.rs (select_param)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (sample_invocations)` -- `feature::InterfaceComponents`: `crates/metal2vulkan/src/pipeline/compile/color_group.rs (refusal)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (graphics_state)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs (assign)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs (limit_error)` +- `feature::InterfaceComponents`: `crates/metal2vulkan/src/pipeline/link/graphics.rs (graphics_state)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs (assign)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs (limit_error)` - `feature::UnmatchedVarying`: `crates/metal2vulkan/src/pipeline/link/varyings.rs (mesh_fragment)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs (varyings, 2 sites)` - `feature::KernelStageIn`: `crates/metal2vulkan/src/lower/stage_io/stage_in.rs (select)` - `feature::VertexStepRate`: `crates/metal2vulkan/src/metal/vertex.rs (divided)` diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index ce5f53d5b..9444807c7 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -374,7 +374,7 @@ worker under the 20-second and 500-MiB ceilings, resumable in bounded batches (` | Audit | What it answers | |---|---| | `authoring-capabilities [--reclassify-all]` | For every indexed AIR identity, whether a case can express and both executors can run its structure (`ToolingRequirement`s). Closed only when `classified == total`, `remaining == 0` and `unresolved == 0`; a warm rerun reads no source shard. A row Metal cannot build (`metal_refused`) or the runtime refuses, typed (`runtime_refused`: a requirement whose limit is `Limit::Runtime`, each held both ways by a lavapipe device test where the runtime has a call for it, mesh pipelines by the runtime README's known gap) is closed without that executor's run and counted apart; a tooling gap of its own still keeps it open | -| `translation --profile P...` | Each row translated for each committed profile, recorded as a typed outcome class under the current product fingerprint (`--current-fingerprint`, `--retry-failures`, `--hash-file PATH` select rows). A fragment function of more colors than the profile draws at once is translated as its render pipeline's color groups, one module a group, each checked by L3. It fails when a row breaks a ceiling | +| `translation --profile P...` | Each row translated for each committed profile, recorded as a typed outcome class under the current product fingerprint (`--current-fingerprint`, `--retry-failures`, `--hash-file PATH` select rows). It fails when a row breaks a ceiling | | `budgets --profile P...` | The budget gates from recorded rows: no row above 20 s or 500 MiB, no stopped worker, and each row's ledger peak at least 0.7 of its allocator peak | | `specialization --profile P...` | Rows translated under planned function-constant value sets and the pipeline inputs their AIR states, not only with none | | `authored-compile [--bless \| --bless-additions \| --case ID]` | Every committed authored case compiled, with the requests its executor builds, on each profile and leg of `corpus/authored-compile.tsv`; it fails on any changed cell. The table is re-blessed on `development` |