From 6746e8a1ff2cb1bbb38aa2c45e9a72945785ca62 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 19 Oct 2026 00:16:00 +0300 Subject: [PATCH] Hold A8Unorm in R8_UNORM with alpha in red where the device has no A8_UNORM Where the device has no A8_UNORM, an A8Unorm texture is held in R8_UNORM with Metal's alpha in red: as a render target, through fetch and coverage by alpha, as a texture buffer, as an argument buffer's storage texture, and multisampled, where fetch reads sample planes held in A8_UNORM and a resolve follows Metal's unorm rule. The A8 lanes hold the device's resolve rounding and the sample planes' typed refusal; the fixtures are listed with their printouts. Folds in: - Hold an A8Unorm texture in R8_UNORM with Metal's alpha in red where the device has no A8_UNORM - Bless the golden tables and the A8-in-red fixture's printout - List the A8-in-red fixture's rows in the engine expectations - Fetch and cover by alpha through an A8Unorm attachment held in red, as Metal does - Hold the A8 lanes to the device's resolve rounding and its sample planes' typed refusal - Read and write an A8Unorm texture buffer through an R8_UNORM view where the device has no A8_UNORM, as Metal does - Name texel_buffer_alpha_in_red in plain text in FormatEmulation::AlphaInRed's doc - List the a8r_buffers fixture in the engine expectations and give it its golden printout - Read and write an argument buffer's A8Unorm storage texture held in red, as Metal does - Fetch a multisampled A8Unorm attachment through sample planes held in A8_UNORM, and resolve A8Unorm by Metal's unorm rule Verified by each folded change's own checks; the tree this series ends on is the one verified at the tip on six GPUs, the CPU suites and lint (see the tables commit). --- .../metal2vulkan-runtime/src/clear_value.rs | 46 +- .../src/framebuffer_fetch.rs | 23 +- crates/metal2vulkan-runtime/src/image_plan.rs | 12 +- .../metal2vulkan-runtime/src/render_pass.rs | 6 + .../metal2vulkan-runtime/src/sample_planes.rs | 57 +- .../src/tests/framebuffer_fetch.rs | 30 +- .../src/tests/image_plan.rs | 72 + crates/metal2vulkan-runtime/src/texture.rs | 4 +- .../fixtures/public/engine/TOOLCHAIN | 2 + .../fixtures/public/engine/a8r_buffers.air.ll | 204 +++ .../fixtures/public/engine/a8r_buffers.ll | 201 +++ .../fixtures/public/engine/a8r_buffers.metal | 43 + .../fixtures/public/engine/a8r_targets.air.ll | 292 ++++ .../fixtures/public/engine/a8r_targets.ll | 289 ++++ .../fixtures/public/engine/a8r_targets.metal | 76 + .../src/runtime_lane.rs | 2 + .../src/runtime_lane/alpha_in_red.rs | 1372 +++++++++++++++++ crates/metal2vulkan/src/bind/color_resolve.rs | 35 +- .../src/bind/color_resolve/tests.rs | 48 +- crates/metal2vulkan/src/bind/graphics.rs | 1 + crates/metal2vulkan/src/bind/heap.rs | 42 +- crates/metal2vulkan/src/bind/heap/tests.rs | 45 +- crates/metal2vulkan/src/bind/plan/compute.rs | 1 + .../metal2vulkan/src/bind/plan/resources.rs | 60 +- .../src/bind/plan/resources/tests.rs | 141 ++ .../src/bind/sample_interleave.rs | 8 +- .../src/bind/sample_interleave/tests.rs | 12 +- crates/metal2vulkan/src/bind/sample_planes.rs | 110 +- .../src/bind/sample_planes/tests.rs | 54 +- crates/metal2vulkan/src/cache/codec.rs | 2 +- .../metal2vulkan/src/lower/fragment/color.rs | 47 + .../metal2vulkan/src/lower/fragment/fetch.rs | 67 +- crates/metal2vulkan/src/lower/stage_io/mod.rs | 15 +- .../metal2vulkan/src/lower/stage_io/plan.rs | 13 +- crates/metal2vulkan/src/lower/texture/emit.rs | 52 + crates/metal2vulkan/src/lower/texture/mod.rs | 53 +- crates/metal2vulkan/src/metal/format/mod.rs | 130 +- crates/metal2vulkan/src/metal/format/tests.rs | 162 +- crates/metal2vulkan/src/metal/mod.rs | 20 + crates/metal2vulkan/src/metal/sampler.rs | 2 +- crates/metal2vulkan/src/metal/state.rs | 19 +- crates/metal2vulkan/src/metal/texel_format.rs | 37 + crates/metal2vulkan/src/pipeline/api_tests.rs | 1 + .../metal2vulkan/src/pipeline/color_writes.rs | 80 +- crates/metal2vulkan/src/pipeline/compile.rs | 3 + .../metal2vulkan/src/pipeline/compile/key.rs | 5 + .../src/pipeline/compile/tests.rs | 1 + .../src/pipeline/link/graphics.rs | 48 +- .../metal2vulkan/src/pipeline/lower_inputs.rs | 22 +- .../src/pipeline/rotated_blend.rs | 54 + .../src/pipeline/rotated_blend/tests.rs | 44 + crates/metal2vulkan/src/pipeline/stage_io.rs | 9 + crates/metal2vulkan/src/pipeline/testing.rs | 3 + .../tests/air_input/a8r_buffers.txt | 220 +++ .../tests/air_input/a8r_targets.txt | 323 ++++ crates/metal2vulkan/tests/api_surface.rs | 2 + 56 files changed, 4453 insertions(+), 269 deletions(-) create mode 100644 crates/metal2vulkan-validation/fixtures/public/engine/a8r_buffers.air.ll create mode 100644 crates/metal2vulkan-validation/fixtures/public/engine/a8r_buffers.ll create mode 100644 crates/metal2vulkan-validation/fixtures/public/engine/a8r_buffers.metal create mode 100644 crates/metal2vulkan-validation/fixtures/public/engine/a8r_targets.air.ll create mode 100644 crates/metal2vulkan-validation/fixtures/public/engine/a8r_targets.ll create mode 100644 crates/metal2vulkan-validation/fixtures/public/engine/a8r_targets.metal create mode 100644 crates/metal2vulkan-validation/src/runtime_lane/alpha_in_red.rs create mode 100644 crates/metal2vulkan/tests/air_input/a8r_buffers.txt create mode 100644 crates/metal2vulkan/tests/air_input/a8r_targets.txt diff --git a/crates/metal2vulkan-runtime/src/clear_value.rs b/crates/metal2vulkan-runtime/src/clear_value.rs index 1678ccce1..0c9d4d9ac 100644 --- a/crates/metal2vulkan-runtime/src/clear_value.rs +++ b/crates/metal2vulkan-runtime/src/clear_value.rs @@ -61,7 +61,8 @@ use ash::vk; use metal2vulkan::metal::format::{ - rotated_channels, to_rotated_image, ycbcr_renders, ClearRoute, ExtendedRange, + alpha_in_red_format, rotated_channels, to_rotated_image, ycbcr_renders, ClearRoute, + ExtendedRange, WordAttachment, }; use metal2vulkan::metal::PixelFormat; use metal2vulkan::vk::Format; @@ -254,6 +255,27 @@ pub(super) fn color( }) } +/// [`color`] for an attachment of `pf` whose image is of Vulkan format `format`: an `A8Unorm` +/// image held in `R8_UNORM` (`metal::format::FormatEmulation::AlphaInRed`) takes the clear's alpha +/// in red, as it holds Metal's alpha (Metal's clear stores the color's alpha, probe `a8`, an M3 +/// Max under macOS 27.0.1). +pub(super) fn held_color( + pf: PixelFormat, + format: Format, + color: [f64; 4], + route: ClearRoute, +) -> Option { + let value = self::color(pf, color, route)?; + if alpha_in_red_format(pf) != Some(format) { + return Some(value); + } + // SAFETY: `color` gives a normalized format's clear as `float32`. + let float32 = unsafe { value.float32 }; + Some(vk::ClearColorValue { + float32: to_rotated_image(float32), + }) +} + /// The Vulkan clear value of Metal's clear `color` for an attachment of `pf` that renders through /// the view of its word `word` (`metal::format::WordAttachment`): the word of the codes Metal's /// clear stores ([`color`]'s conversion of each channel; `RGB9E5Float`'s word of the color @@ -977,6 +999,28 @@ pub(crate) mod tests { } } + /// An `A8Unorm` attachment's clear writes the color's alpha (probe `a8`, an M3 Max under + /// macOS 27.0.1: a clear of (0.2, 0.4, 0.6, 0.8) stores 204): in `A8_UNORM`'s alpha, and in an + /// `R8_UNORM` image's red where the image holds Metal's alpha there; another format's image + /// takes [`color`]'s value as it is. + #[test] + fn an_alpha_in_red_clear_takes_the_alpha_in_red() { + let color = [0.2, 0.4, 0.6, 0.8]; + let route = ClearRoute::ThroughHalf; + let code = 204.0 / 255.0; + let held = |pf, format| { + let value = held_color(pf, format, color, route).expect("a clear rule"); + // SAFETY: a normalized format's clear is `float32`. + unsafe { value.float32 } + }; + assert_eq!(held(P::A8Unorm, Format::A8_UNORM), [0.0, 0.0, 0.0, code]); + assert_eq!(held(P::A8Unorm, Format::R8_UNORM), [code, 0.0, 0.0, 0.0]); + assert_eq!( + held(P::R8Unorm, Format::R8_UNORM), + [51.0 / 255.0, 0.0, 0.0, 0.0] + ); + } + /// A texel's unsigned-integer clear writes its bytes: its little-endian words in the format /// of its size (`RGBA16Float`'s fresh pattern, half NaNs around a zero, as two 32-bit words). #[test] diff --git a/crates/metal2vulkan-runtime/src/framebuffer_fetch.rs b/crates/metal2vulkan-runtime/src/framebuffer_fetch.rs index ea25ff439..3367e3998 100644 --- a/crates/metal2vulkan-runtime/src/framebuffer_fetch.rs +++ b/crates/metal2vulkan-runtime/src/framebuffer_fetch.rs @@ -275,14 +275,16 @@ pub(crate) fn storage_candidate(plan: &ImagePlan, profile: &DeviceProfile) -> Op /// Whether the sample planes' copies (`sample_planes.rs`) read and write `plan`'s image directly: /// it is sampled and may be viewed in the [`PlanesCopy`] format of its texel size (mutable, with -/// no format list or one that lists it). +/// no format list or one that lists it); an `A8_UNORM` image, whose copy is in its own format +/// ([`PlanesCopy::Alpha8`]), needs no other view. pub(crate) fn planes_copies(plan: &ImagePlan) -> bool { - let Some(copy) = PlanesCopy::for_format(plan.format) else { + let Some(copy) = PlanesCopy::for_planes(plan.format) else { return false; }; plan.usage.contains(ImageUsageFlags::SAMPLED) - && plan.flags.contains(ImageCreateFlags::MUTABLE_FORMAT) - && (plan.view_formats.is_empty() || plan.view_formats.contains(©.format())) + && (!copy.moves_bits() + || (plan.flags.contains(ImageCreateFlags::MUTABLE_FORMAT) + && (plan.view_formats.is_empty() || plan.view_formats.contains(©.format())))) } /// What a multisampled color image of `format` lacks on `profile` for the sample planes' copies @@ -290,7 +292,7 @@ pub(crate) fn planes_copies(plan: &ImagePlan) -> bool { /// usage is asked), and the [`PlanesCopy`] format of its texel size sampled and a color /// attachment. `None` where it lacks nothing, and where `format` has no copy format. pub(crate) fn planes_copies_gap(format: Format, profile: &DeviceProfile) -> Option { - let copy = PlanesCopy::for_format(format)?; + let copy = PlanesCopy::for_planes(format)?; [ (format, FormatUsage::SampledImage), (copy.format(), FormatUsage::SampledImage), @@ -303,15 +305,20 @@ pub(crate) fn planes_copies_gap(format: Format, profile: &DeviceProfile) -> Opti /// The usage and format list a multisampled color image takes for the sample planes' copies /// (`sample_planes.rs`): `plan` sampled and mutable with the [`PlanesCopy`] format of its texel -/// size among its view formats. `None` where the device cannot run the copies on it: no copy -/// format, or a format usage it lacks ([`planes_copies_gap`]). +/// size among its view formats, or sampled alone where the copy is in its own format +/// (`A8_UNORM`'s). `None` where the device cannot run the copies on it: no copy format, or a +/// format usage it lacks ([`planes_copies_gap`]). pub(crate) fn with_planes_copies(plan: &ImagePlan, profile: &DeviceProfile) -> Option { - let copy = PlanesCopy::for_format(plan.format)?; + let copy = PlanesCopy::for_planes(plan.format)?; if planes_copies_gap(plan.format, profile).is_some() { return None; } let mut candidate = plan.clone(); candidate.usage |= ImageUsageFlags::SAMPLED; + // `A8_UNORM`'s copy is in its own format, which views it as it is. + if !copy.moves_bits() { + return Some(candidate); + } let any_format = plan.flags.contains(ImageCreateFlags::MUTABLE_FORMAT) && plan.view_formats.is_empty(); candidate.flags |= ImageCreateFlags::MUTABLE_FORMAT; diff --git a/crates/metal2vulkan-runtime/src/image_plan.rs b/crates/metal2vulkan-runtime/src/image_plan.rs index 28c1efeb0..ce4c031b6 100644 --- a/crates/metal2vulkan-runtime/src/image_plan.rs +++ b/crates/metal2vulkan-runtime/src/image_plan.rs @@ -77,8 +77,9 @@ use metal2vulkan::error::{ Capability, Error as CompileError, Feature, Needs, RuntimeDriverDefect, Unsupported, }; use metal2vulkan::metal::format::{ - direct_format, image_type, is_depth_stencil, srgb_raw_twin, storage_image_choice, - storage_view_formats, vk_format, FormatEmulation, FormatMapping, + alpha_in_red, alpha_in_red_format, direct_format, image_type, is_depth_stencil, srgb_raw_twin, + storage_image_choice, storage_view_formats, vk_format, FormatEmulation, FormatMapping, + WordAttachment, }; use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage}; use metal2vulkan::vk::{ @@ -627,7 +628,12 @@ fn plan_held( // `vk_format` with no usage names the refusal of a format without a representation (not // representable, not implemented, or no format at all). let any = vk_format(pf, &BTreeSet::new(), profile).map_err(ImageRefusal::of)?; - let direct = direct_format(pf).unwrap_or(any.format); + // An `A8Unorm` texture on a device that holds no `A8_UNORM` image is held in `R8_UNORM`, its + // alpha in red, for every use (`metal::format::alpha_in_red`): that is its direct format here. + let direct = match alpha_in_red_format(pf).filter(|_| alpha_in_red(pf, profile)) { + Some(red) => red, + None => direct_format(pf).unwrap_or(any.format), + }; let depth_stencil = is_depth_stencil(pf); let attachment_usage = if depth_stencil { FormatUsage::DepthStencilAttachment diff --git a/crates/metal2vulkan-runtime/src/render_pass.rs b/crates/metal2vulkan-runtime/src/render_pass.rs index 18c2604c2..7e2cd0b6a 100644 --- a/crates/metal2vulkan-runtime/src/render_pass.rs +++ b/crates/metal2vulkan-runtime/src/render_pass.rs @@ -1335,6 +1335,12 @@ pub(super) fn layout( .filter(|w| w.word_format() == target.format); let clear = match word { Some(word) => clear_value::word(texture.pixel_format(), channels, word), + None => clear_value::held_color( + texture.pixel_format(), + target.format, + channels, + ClearRoute::ThroughHalf, + ), } .ok_or_else(not_yet)?; let straight_clear = ExtendedRange::of(texture.pixel_format()).and_then(|_| { diff --git a/crates/metal2vulkan-runtime/src/sample_planes.rs b/crates/metal2vulkan-runtime/src/sample_planes.rs index 81338920a..de879f250 100644 --- a/crates/metal2vulkan-runtime/src/sample_planes.rs +++ b/crates/metal2vulkan-runtime/src/sample_planes.rs @@ -30,7 +30,9 @@ //! its samples are the planes' there. //! //! Both copies read and write the bits of each texel through a view in the unsigned-integer -//! format of its size (`bind::PlanesCopy`), so every format crosses unchanged. The image the +//! format of its size (`bind::PlanesCopy`), so every format crosses unchanged; `A8_UNORM`, whose +//! class no unsigned format shares, crosses as the `float`s of its own views +//! (`bind::PlanesCopy::Alpha8`), which keep each code. The image the //! copies run on is the attachment's own where it is sampled and may be viewed so //! (`framebuffer_fetch::planes_copies`, which a multisampled color render target the runtime //! makes takes where it costs the image nothing), else a stand-in that is @@ -43,7 +45,9 @@ //! `Unsupported` (feature `FramebufferFetch`) naming what it lacks: a storage view of an extended //! copy format (`shaderStorageImageExtendedFormats`), `sampleRateShading` for the merge, the //! pass's sample count among `framebufferIntegerColorSampleCounts` (the merge renders the copy -//! format, an integer one), or a format usage of the attachment's or the copy format's. A device +//! format, an integer one; `framebufferColorSampleCounts` for `A8_UNORM`'s), or a format usage of +//! the attachment's or the copy format's (`A8_UNORM`'s storage write without a format among them, +//! which its split's declaration needs). A device //! whose portability subset withholds `imageViewFormatReinterpretation` refuses it too, typed //! `Unsupported` (feature `ViewFormatReinterpretation`, `view_plan.rs`), where the copy format's //! components differ from the attachment's in count or width: every format but those of one 8-, 16- @@ -133,9 +137,9 @@ impl Planes { ) -> Result { let device = maker.device(); let format = target.format; - // A format of a compatibility class of its own (`A8_UNORM`) has no view whose texels the - // copies move as bits. - let copy = PlanesCopy::for_format(format).ok_or_else(|| { + // A format of a compatibility class of its own has no view whose texels the copies move + // as bits; `A8_UNORM`'s move as its own views' floats (`PlanesCopy::for_planes`). + let copy = PlanesCopy::for_planes(format).ok_or_else(|| { Error::Unsupported(Unsupported::not_implemented(Feature::FramebufferFetch)) })?; // The copies view the planes and the attachment's image in the copy format, whose @@ -165,11 +169,18 @@ impl Planes { // unsigned-integer view, or a BGRA-order one's RGBA-order twin), the split's storage view // and the merge's sampled view in the copy format. let view = framebuffer_fetch::storage_view_format(profile, format); + // The split writes `A8_UNORM` planes through a declaration without a format + // (`PlanesSplitModule::requirements`), which the format's own bit must allow. + let formatless = (!copy.moves_bits()) + .then_some((copy.format(), FormatUsage::StorageImageWriteWithoutFormat)); for (format, usage) in [ (view, FormatUsage::StorageImage), (copy.format(), FormatUsage::StorageImage), (copy.format(), FormatUsage::SampledImage), - ] { + ] + .into_iter() + .chain(formatless) + { if !profile.supports_format(format, usage) { return Err(lacks_format(format, usage)); } @@ -329,11 +340,12 @@ struct MergePipeline { pipeline: vk::Pipeline, } -/// The planes' objects one device has made (the module docs). +/// The planes' objects one device has made (the module docs). The merge's shaders are one pair +/// for every bits copy and one for the copy of floats (`PlanesCopy::moves_bits`). #[derive(Default)] pub(super) struct PlanesObjects { split: Vec<(PlanesCopy, SplitKernel)>, - merge: Option, + merge: Vec<(bool, MergeShaders)>, merge_pipelines: Vec<((PlanesCopy, u32), MergePipeline)>, } @@ -347,7 +359,7 @@ impl PlanesObjects { release::object(raw, merge.pipeline); release::object(raw, merge.render_pass); } - if let Some(shaders) = self.merge { + for (_, shaders) in &self.merge { release::object(raw, shaders.layout); release::object(raw, shaders.set_layout); release::object(raw, shaders.fragment); @@ -485,12 +497,16 @@ impl Device { copy: PlanesCopy, samples: u32, ) -> Result<(MergeShaders, MergePipeline), Error> { - // The merge renders the attachment's view in the copy format, an integer one, at the - // pass's samples: a count every integer color attachment takes, or the copy format's - // own, the alternatives link asks of a pipeline's integer color attachment - // (`pipeline::graphics`, which the runtime does not import), in its order. + // The merge renders the attachment's view in the copy format, an integer one (or + // `A8_UNORM` itself), at the pass's samples: a count every integer (or every) color + // attachment takes, or the copy format's own, the alternatives link asks of a pipeline's + // color attachment (`pipeline::graphics`, which the runtime does not import), in its order. + let every = match copy.moves_bits() { + true => VkProperty::FramebufferIntegerColorSampleCount(samples), + false => VkProperty::FramebufferColorSampleCount(samples), + }; let alternatives = [ - VkProperty::FramebufferIntegerColorSampleCount(samples), + every, VkProperty::ColorAttachmentSampleCount(copy.format(), samples), ]; let enabled = &self.compile_device().profile().enabled().properties; @@ -513,10 +529,17 @@ impl Device { let mut objects = lock(&self.shared().planes); let shared = self.shared(); let raw = shared.vk(); - let shaders = match objects.merge { + let bits = copy.moves_bits(); + let made = objects + .merge + .iter() + .find(|(b, _)| *b == bits) + .map(|(_, s)| *s); + let shaders = match made { Some(shaders) => shaders, None => { - let modules = planes_merge_modules(self.compile_device()).map_err(device_error)?; + let modules = + planes_merge_modules(self.compile_device(), copy).map_err(device_error)?; let mut shaders = MergeShaders { vertex: vk::ShaderModule::null(), fragment: vk::ShaderModule::null(), @@ -545,7 +568,7 @@ impl Device { } return Err(error); } - objects.merge = Some(shaders); + objects.merge.push((bits, shaders)); shaders } }; diff --git a/crates/metal2vulkan-runtime/src/tests/framebuffer_fetch.rs b/crates/metal2vulkan-runtime/src/tests/framebuffer_fetch.rs index b9b4327df..0aeab7fc4 100644 --- a/crates/metal2vulkan-runtime/src/tests/framebuffer_fetch.rs +++ b/crates/metal2vulkan-runtime/src/tests/framebuffer_fetch.rs @@ -207,10 +207,11 @@ fn storage_is_offered_to_the_interlock_forms_color_targets() { } /// A multisampled `A8Unorm` render target held as `A8_UNORM`, whose class ("8-bit alpha") no -/// copy format shares, is offered no planes copies' usage, on a device whose fetch reads planes -/// too: no view in `R8_UINT` is listed for it. +/// unsigned copy format shares, takes the planes copies in its own format +/// (`PlanesCopy::Alpha8`), on a device whose fetch reads planes: its candidate is the plan sampled, +/// neither mutable nor listing another format, which the copies then read and write directly. #[test] -fn an_a8_target_is_offered_no_planes_copies() { +fn an_a8_target_takes_the_planes_copies_in_its_own_format() { let mut planes = 0; for (name, desc, device) in committed() { let facts = facts(&desc, &device); @@ -222,10 +223,27 @@ fn an_a8_target_is_offered_no_planes_copies() { if target.format != Format::A8_UNORM { continue; } - planes += usize::from(through_planes(profile, 4)); assert_eq!(PlanesCopy::for_format(target.format), None, "{name}"); - assert_eq!(planes_candidate(&target, profile), None, "{name}"); - assert!(!planes_copies(&target), "{name}"); + assert_eq!( + PlanesCopy::for_planes(target.format), + Some(PlanesCopy::Alpha8), + "{name}" + ); + if !through_planes(profile, 4) || planes_copies_gap(target.format, profile).is_some() { + continue; + } + planes += 1; + let candidate = planes_candidate(&target, profile).expect("the planes' usage"); + assert_eq!( + candidate, + ImagePlan { + usage: target.usage | ImageUsageFlags::SAMPLED, + ..target.clone() + }, + "{name}" + ); + assert!(planes_copies(&candidate), "{name}"); + assert_eq!(planes_candidate(&candidate, profile), None, "{name}"); } assert!(planes > 0, "a planes profile holds A8Unorm as A8_UNORM"); } diff --git a/crates/metal2vulkan-runtime/src/tests/image_plan.rs b/crates/metal2vulkan-runtime/src/tests/image_plan.rs index 061c3f0e6..ae6bac1c0 100644 --- a/crates/metal2vulkan-runtime/src/tests/image_plan.rs +++ b/crates/metal2vulkan-runtime/src/tests/image_plan.rs @@ -189,8 +189,14 @@ fn check_plan( } assert!(supports(FormatUsage::StorageImage) || extended, "{what}"); // The format's own, or the UNORM twin of an 8-bit sRGB format the device holds no image + // of, which serves its storage alias, or the red image of an `A8Unorm` texture the + // device holds no `A8_UNORM` image of. let own = direct_format(pf); + let unheld = own.filter(|&f| facts.optimal(f).is_empty()); + let twin = unheld.and(srgb_raw_twin(pf).and_then(direct_format)); + let red = unheld.and(alpha_in_red_format(pf)); assert!( + Some(plan.format) == own || Some(plan.format) == twin || Some(plan.format) == red, "{what}" ); } @@ -513,6 +519,72 @@ fn an_srgb_format_the_device_cannot_sample_is_held_as_its_unorm_twin() { } } +/// An `A8Unorm` texture on a device that holds no `A8_UNORM` image is an `R8_UNORM` image holding +/// Metal's alpha in red (`FormatEmulation::AlphaInRed`), sampled through `(Zero, Zero, Zero, R)`, +/// stored and rendered where the device does those with `R8_UNORM`; where the device holds +/// `A8_UNORM`, that format. A pipeline's attachment agrees (`alpha_in_red`). +#[test] +fn an_a8_texture_without_a8_unorm_holds_its_alpha_in_red() { + let usage = + TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE | TextureUsage::RENDER_TARGET; + let mut held = Vec::new(); + for (name, desc, device) in committed() { + let facts = facts(&desc, &device); + let profile = facts.profile; + let what = name.clone(); + let l = layout(TextureType::Type2D, PixelFormat::A8Unorm, 1, 1); + let plan = plan_image(&l, usage, false, &facts).expect(&what); + check_plan(&name, PixelFormat::A8Unorm, usage, &plan, &facts); + if !facts.optimal(Format::A8_UNORM).is_empty() { + assert_eq!(plan.format, Format::A8_UNORM, "{what}: {plan:?}"); + assert!(!alpha_in_red(PixelFormat::A8Unorm, profile), "{what}"); + continue; + } + held.push(name.clone()); + assert_eq!(plan.format, Format::R8_UNORM, "{what}: {plan:?}"); + assert_eq!( + plan.mapping.emulation, + FormatEmulation::AlphaInRed, + "{what}" + ); + assert_eq!( + plan.mapping.components.a, + metal2vulkan::vk::ComponentSwizzle::R, + "{what}" + ); + assert!(alpha_in_red(PixelFormat::A8Unorm, profile), "{what}"); + for (bit, flags, need) in [ + ( + TextureUsage::SHADER_READ, + ImageUsageFlags::SAMPLED, + FormatUsage::SampledImage, + ), + ( + TextureUsage::SHADER_WRITE, + ImageUsageFlags::STORAGE, + FormatUsage::StorageImage, + ), + ( + TextureUsage::RENDER_TARGET, + ImageUsageFlags::COLOR_ATTACHMENT, + FormatUsage::ColorAttachment, + ), + ] { + let has = profile.supports_format(Format::R8_UNORM, need); + assert_eq!(plan.usage.contains(flags), has, "{what}: {bit:?} {plan:?}"); + assert_eq!(plan.unavailable.contains(bit), !has, "{what}: {bit:?}"); + } + } + for stem in [ + "vk12-floor", + "lavapipe", + "amd-rdna3-radv", + "nvidia-pascal-linux", + ] { + assert!(held.contains(&stem.to_owned()), "{stem}: {held:?}"); + } +} + #[test] fn srgb_twins_share_one_mutable_image() { for (name, desc, device) in committed() { diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 9c2dff92a..bce89d84b 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -3891,7 +3891,9 @@ impl Device { }; let written = match pattern { FreshPattern::Color { color, .. } if clear && color.is_some() => color - .and_then(|color| clear_value::color(pf, color, ClearRoute::ThroughHalf)) + .and_then(|color| { + clear_value::held_color(pf, plan.format, color, ClearRoute::ThroughHalf) + }) .map(Pattern::Color), FreshPattern::Color { texel, .. } if single && heap_tiled::holds_metal_texels(pf, plan.format, texel.len()) => diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN b/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN index c9f3979a9..432782048 100644 --- a/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN +++ b/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN @@ -16,6 +16,8 @@ fixture a27_ob1_buffer_atomic: metal: Apple metal version 32023.921 (metalfe-320 fixture a27_ob1_threadgroup: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture a27_spse_write_barrier: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture a27_thread_atomics: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) +fixture a8r_buffers: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) +fixture a8r_targets: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture ani_cube_grad: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture bary_weights: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture bcx_half_read: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/a8r_buffers.air.ll b/crates/metal2vulkan-validation/fixtures/public/engine/a8r_buffers.air.ll new file mode 100644 index 000000000..c7e465c39 --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/engine/a8r_buffers.air.ll @@ -0,0 +1,204 @@ +; Generated by scripts/regen-air-fixtures from a8r_buffers.metal (typed pointers; xcrun metal-as reassembles it). Do not edit. +; ModuleID = '-' +source_filename = "-" +target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" +target triple = "air64_v28-apple-macosx26.0.0" + +%struct._texture_buffer_1d_t = type opaque +%struct._sampler_t = type opaque +%struct.A8rHeld = type { %"struct.metal::texture2d", %"struct.metal::texture2d.45" } +%"struct.metal::texture2d" = type { %struct._texture_2d_t addrspace(1)* } +%struct._texture_2d_t = type opaque +%"struct.metal::texture2d.45" = type { %struct._texture_2d_t addrspace(1)* } + +; Function Attrs: mustprogress nofree nounwind willreturn +define void @a8r_buffer_read(%struct._texture_buffer_1d_t addrspace(1)* nocapture readonly %0, <4 x float> addrspace(1)* nocapture noundef writeonly "air-buffer-no-alias" %1, i32 noundef %2) local_unnamed_addr #0 { + %4 = tail call %struct._sampler_t addrspace(2)* @air.get_read_sampler() #8 + %5 = tail call { <4 x float>, i8 } @air.read_texture_buffer_1d.v4f32(%struct._texture_buffer_1d_t addrspace(1)* nocapture readonly %0, %struct._sampler_t addrspace(2)* %4, i32 %2, i32 1) #9 + %6 = extractvalue { <4 x float>, i8 } %5, 0 + %7 = zext i32 %2 to i64 + %8 = getelementptr inbounds <4 x float>, <4 x float> addrspace(1)* %1, i64 %7 + store <4 x float> %6, <4 x float> addrspace(1)* %8, align 16, !tbaa !40, !alias.scope !43, !noalias !46 + ret void +} + +; Function Attrs: mustprogress nofree nounwind willreturn +define void @a8r_buffer_read_half(%struct._texture_buffer_1d_t addrspace(1)* nocapture readonly %0, <4 x float> addrspace(1)* nocapture noundef writeonly "air-buffer-no-alias" %1, i32 noundef %2) local_unnamed_addr #1 { + %4 = tail call %struct._sampler_t addrspace(2)* @air.get_read_sampler() #8 + %5 = tail call { <4 x half>, i8 } @air.read_texture_buffer_1d.v4f16(%struct._texture_buffer_1d_t addrspace(1)* nocapture readonly %0, %struct._sampler_t addrspace(2)* %4, i32 %2, i32 1) #9 + %6 = extractvalue { <4 x half>, i8 } %5, 0 + %7 = tail call fast <4 x float> @air.convert.f.v4f32.f.v4f16(<4 x half> %6) #10 + %8 = zext i32 %2 to i64 + %9 = getelementptr inbounds <4 x float>, <4 x float> addrspace(1)* %1, i64 %8 + store <4 x float> %7, <4 x float> addrspace(1)* %9, align 16, !tbaa !40, !alias.scope !48, !noalias !51 + ret void +} + +; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn +declare <4 x float> @air.convert.f.v4f32.f.v4f16(<4 x half>) local_unnamed_addr #2 + +; Function Attrs: argmemonly mustprogress nounwind willreturn +define void @a8r_buffer_write(%struct._texture_buffer_1d_t addrspace(1)* nocapture %0, <4 x float> addrspace(2)* nocapture noundef readonly "air-buffer-no-alias" %1, i32 noundef %2) local_unnamed_addr #3 { + %4 = load <4 x float>, <4 x float> addrspace(2)* %1, align 16, !tbaa !40, !alias.scope !53, !noalias !56 + tail call void @air.write_texture_buffer_1d.v4f32(%struct._texture_buffer_1d_t addrspace(1)* nocapture %0, i32 %2, <4 x float> %4, i32 2) #11, !alias.scope !56, !noalias !53 + ret void +} + +; Function Attrs: mustprogress nounwind willreturn +define void @a8r_buffer_read_write(%struct._texture_buffer_1d_t addrspace(1)* %0, <4 x float> addrspace(2)* nocapture noundef readonly "air-buffer-no-alias" %1, <4 x float> addrspace(1)* nocapture noundef writeonly "air-buffer-no-alias" %2, i32 noundef %3) local_unnamed_addr #4 { + %5 = tail call %struct._sampler_t addrspace(2)* @air.get_read_sampler() #8 + %6 = tail call { <4 x float>, i8 } @air.read_texture_buffer_1d.v4f32(%struct._texture_buffer_1d_t addrspace(1)* nocapture readonly %0, %struct._sampler_t addrspace(2)* %5, i32 %3, i32 3) #9 + %7 = extractvalue { <4 x float>, i8 } %6, 0 + %8 = zext i32 %3 to i64 + %9 = getelementptr inbounds <4 x float>, <4 x float> addrspace(1)* %2, i64 %8 + store <4 x float> %7, <4 x float> addrspace(1)* %9, align 16, !tbaa !40, !alias.scope !58, !noalias !61 + %10 = load <4 x float>, <4 x float> addrspace(2)* %1, align 16, !tbaa !40, !alias.scope !64, !noalias !65 + tail call void @air.write_texture_buffer_1d.v4f32(%struct._texture_buffer_1d_t addrspace(1)* nocapture %0, i32 %3, <4 x float> %10, i32 3) #11, !alias.scope !66, !noalias !67 + ret void +} + +; Function Attrs: mustprogress nounwind willreturn +define void @a8r_held(%struct.A8rHeld addrspace(2)* nocapture noundef readonly align 8 dereferenceable(16) "air-buffer-no-alias" %0, <4 x float> addrspace(2)* nocapture noundef readonly "air-buffer-no-alias" %1, <4 x float> addrspace(1)* nocapture noundef writeonly "air-buffer-no-alias" %2, <2 x i32> noundef %3) local_unnamed_addr #4 { + %5 = getelementptr inbounds %struct.A8rHeld, %struct.A8rHeld addrspace(2)* %0, i64 0, i32 0, i32 0 + %6 = load %struct._texture_2d_t addrspace(1)*, %struct._texture_2d_t addrspace(1)* addrspace(2)* %5, align 8, !tbaa !68, !alias.scope !71, !noalias !74 + %7 = tail call %struct._sampler_t addrspace(2)* @air.get_read_sampler() #8 + %8 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly %6, %struct._sampler_t addrspace(2)* %7, <2 x i32> %3, <2 x i32> zeroinitializer, i32 0, i32 3) #9 + %9 = extractvalue { <4 x float>, i8 } %8, 0 + %10 = extractelement <2 x i32> %3, i64 1 + %11 = shl i32 %10, 3 + %12 = extractelement <2 x i32> %3, i64 0 + %13 = add i32 %11, %12 + %14 = zext i32 %13 to i64 + %15 = getelementptr inbounds <4 x float>, <4 x float> addrspace(1)* %2, i64 %14 + store <4 x float> %9, <4 x float> addrspace(1)* %15, align 16, !tbaa !40, !alias.scope !77, !noalias !78 + %16 = load <4 x float>, <4 x float> addrspace(2)* %1, align 16, !tbaa !40, !alias.scope !79, !noalias !80 + tail call void @air.write_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture %6, <2 x i32> %3, <4 x float> %16, i32 0, i32 3) #11 + %17 = getelementptr inbounds <4 x float>, <4 x float> addrspace(2)* %1, i64 1 + %18 = load <4 x float>, <4 x float> addrspace(2)* %17, align 16, !tbaa !40, !alias.scope !79, !noalias !80 + %19 = getelementptr inbounds %struct.A8rHeld, %struct.A8rHeld addrspace(2)* %0, i64 0, i32 1, i32 0 + %20 = load %struct._texture_2d_t addrspace(1)*, %struct._texture_2d_t addrspace(1)* addrspace(2)* %19, align 8, !tbaa !81, !alias.scope !71, !noalias !74 + tail call void @air.write_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture %20, <2 x i32> %3, <4 x float> %18, i32 0, i32 2) #11 + ret void +} + +; Function Attrs: inaccessiblememonly mustprogress nofree nounwind readonly willreturn +declare %struct._sampler_t addrspace(2)* @air.get_read_sampler() local_unnamed_addr #5 + +; Function Attrs: argmemonly mustprogress nofree nounwind readonly willreturn +declare { <4 x float>, i8 } @air.read_texture_buffer_1d.v4f32(%struct._texture_buffer_1d_t addrspace(1)* nocapture readonly, %struct._sampler_t addrspace(2)*, i32, i32) local_unnamed_addr #6 + +; Function Attrs: argmemonly mustprogress nofree nounwind readonly willreturn +declare { <4 x half>, i8 } @air.read_texture_buffer_1d.v4f16(%struct._texture_buffer_1d_t addrspace(1)* nocapture readonly, %struct._sampler_t addrspace(2)*, i32, i32) local_unnamed_addr #6 + +; Function Attrs: argmemonly mustprogress nounwind willreturn +declare void @air.write_texture_buffer_1d.v4f32(%struct._texture_buffer_1d_t addrspace(1)* nocapture, i32, <4 x float>, i32) local_unnamed_addr #7 + +; Function Attrs: argmemonly mustprogress nofree nounwind readonly willreturn +declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly, %struct._sampler_t addrspace(2)*, <2 x i32>, <2 x i32>, i32, i32) local_unnamed_addr #6 + +; Function Attrs: argmemonly mustprogress nounwind willreturn +declare void @air.write_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture, <2 x i32>, <4 x float>, i32, i32) local_unnamed_addr #7 + +attributes #0 = { mustprogress nofree nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #1 = { mustprogress nofree nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="64" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #2 = { mustprogress nofree nosync nounwind readnone willreturn } +attributes #3 = { argmemonly mustprogress nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #4 = { mustprogress nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #5 = { inaccessiblememonly mustprogress nofree nounwind readonly willreturn } +attributes #6 = { argmemonly mustprogress nofree nounwind readonly willreturn } +attributes #7 = { argmemonly mustprogress nounwind willreturn } +attributes #8 = { inaccessiblememonly nounwind readonly willreturn } +attributes #9 = { argmemonly nounwind readonly willreturn } +attributes #10 = { nounwind readnone willreturn } +attributes #11 = { argmemonly nounwind willreturn } + +!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} +!air.kernel = !{!9, !15, !18, !22, !27} +!air.compile_options = !{!34, !35, !36} +!llvm.ident = !{!37} +!air.version = !{!38} +!air.language_version = !{!39} + +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 27, i32 0]} +!1 = !{i32 1, !"wchar_size", i32 4} +!2 = !{i32 7, !"frame-pointer", i32 2} +!3 = !{i32 7, !"air.max_device_buffers", i32 31} +!4 = !{i32 7, !"air.max_constant_buffers", i32 31} +!5 = !{i32 7, !"air.max_threadgroup_buffers", i32 31} +!6 = !{i32 7, !"air.max_textures", i32 128} +!7 = !{i32 7, !"air.max_read_write_textures", i32 8} +!8 = !{i32 7, !"air.max_samplers", i32 16} +!9 = !{void (%struct._texture_buffer_1d_t addrspace(1)*, <4 x float> addrspace(1)*, i32)* @a8r_buffer_read, !10, !11} +!10 = !{} +!11 = !{!12, !13, !14} +!12 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture_buffer", !"air.arg_name", !"t"} +!13 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"} +!14 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"g"} +!15 = !{void (%struct._texture_buffer_1d_t addrspace(1)*, <4 x float> addrspace(1)*, i32)* @a8r_buffer_read_half, !10, !16} +!16 = !{!17, !13, !14} +!17 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture_buffer", !"air.arg_name", !"t"} +!18 = !{void (%struct._texture_buffer_1d_t addrspace(1)*, <4 x float> addrspace(2)*, i32)* @a8r_buffer_write, !10, !19} +!19 = !{!20, !21, !14} +!20 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.write", !"air.arg_type_name", !"texture_buffer", !"air.arg_name", !"t"} +!21 = !{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"color"} +!22 = !{void (%struct._texture_buffer_1d_t addrspace(1)*, <4 x float> addrspace(2)*, <4 x float> addrspace(1)*, i32)* @a8r_buffer_read_write, !10, !23} +!23 = !{!24, !21, !25, !26} +!24 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.arg_type_name", !"texture_buffer", !"air.arg_name", !"t"} +!25 = !{i32 2, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"} +!26 = !{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"g"} +!27 = !{void (%struct.A8rHeld addrspace(2)*, <4 x float> addrspace(2)*, <4 x float> addrspace(1)*, <2 x i32>)* @a8r_held, !10, !28} +!28 = !{!29, !21, !25, !33} +!29 = !{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 16, !"air.location_index", i32 2, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !30, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"A8rHeld", !"air.arg_name", !"held"} +!30 = !{i32 0, i32 8, i32 0, !"texture2d", !"rw", !"air.indirect_argument", !31, i32 8, i32 8, i32 0, !"texture2d", !"w", !"air.indirect_argument", !32} +!31 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"rw"} +!32 = !{i32 1, !"air.texture", !"air.location_index", i32 1, i32 1, !"air.write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"w"} +!33 = !{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"g"} +!34 = !{!"air.compile.denorms_disable"} +!35 = !{!"air.compile.fast_math_enable"} +!36 = !{!"air.compile.framebuffer_fetch_enable"} +!37 = !{!"Apple metal version 32023.921 (metalfe-32023.921.6)"} +!38 = !{i32 2, i32 8, i32 0} +!39 = !{!"Metal", i32 4, i32 0, i32 0} +!40 = !{!41, !41, i64 0} +!41 = !{!"omnipotent char", !42, i64 0} +!42 = !{!"Simple C++ TBAA"} +!43 = !{!44} +!44 = distinct !{!44, !45, !"air-alias-scope-arg(1)"} +!45 = distinct !{!45, !"air-alias-scopes(a8r_buffer_read)"} +!46 = !{!47} +!47 = distinct !{!47, !45, !"air-alias-scope-textures"} +!48 = !{!49} +!49 = distinct !{!49, !50, !"air-alias-scope-arg(1)"} +!50 = distinct !{!50, !"air-alias-scopes(a8r_buffer_read_half)"} +!51 = !{!52} +!52 = distinct !{!52, !50, !"air-alias-scope-textures"} +!53 = !{!54} +!54 = distinct !{!54, !55, !"air-alias-scope-arg(1)"} +!55 = distinct !{!55, !"air-alias-scopes(a8r_buffer_write)"} +!56 = !{!57} +!57 = distinct !{!57, !55, !"air-alias-scope-textures"} +!58 = !{!59} +!59 = distinct !{!59, !60, !"air-alias-scope-arg(2)"} +!60 = distinct !{!60, !"air-alias-scopes(a8r_buffer_read_write)"} +!61 = !{!62, !63} +!62 = distinct !{!62, !60, !"air-alias-scope-textures"} +!63 = distinct !{!63, !60, !"air-alias-scope-arg(1)"} +!64 = !{!63} +!65 = !{!62, !59} +!66 = !{!62} +!67 = !{!63, !59} +!68 = !{!69, !70, i64 0} +!69 = !{!"_ZTSN5metal9texture2dIfLNS_6accessE3ELNS_16memory_coherenceE0EvEE", !70, i64 0} +!70 = !{!"__metal_texture_2d_t", !41, i64 0} +!71 = !{!72} +!72 = distinct !{!72, !73, !"air-alias-scope-arg(0)"} +!73 = distinct !{!73, !"air-alias-scopes(a8r_held)"} +!74 = !{!75, !76} +!75 = distinct !{!75, !73, !"air-alias-scope-arg(1)"} +!76 = distinct !{!76, !73, !"air-alias-scope-arg(2)"} +!77 = !{!76} +!78 = !{!72, !75} +!79 = !{!75} +!80 = !{!72, !76} +!81 = !{!82, !70, i64 0} +!82 = !{!"_ZTSN5metal9texture2dIfLNS_6accessE2ELNS_16memory_coherenceE0EvEE", !70, i64 0} diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/a8r_buffers.ll b/crates/metal2vulkan-validation/fixtures/public/engine/a8r_buffers.ll new file mode 100644 index 000000000..40ef12a03 --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/engine/a8r_buffers.ll @@ -0,0 +1,201 @@ +; Generated by scripts/regen-air-fixtures from a8r_buffers.metal (llvm-dis of a8r_buffers.air). Do not edit. +; ModuleID = '' +source_filename = "-" +target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" +target triple = "air64_v28-apple-macosx26.0.0" + +%struct.A8rHeld = type { %"struct.metal::texture2d", %"struct.metal::texture2d.45" } +%"struct.metal::texture2d" = type { ptr addrspace(1) } +%"struct.metal::texture2d.45" = type { ptr addrspace(1) } + +; Function Attrs: mustprogress nofree nounwind willreturn +define void @a8r_buffer_read(ptr addrspace(1) readonly captures(none) %0, ptr addrspace(1) noundef writeonly captures(none) "air-buffer-no-alias" %1, i32 noundef %2) local_unnamed_addr #0 { + %4 = tail call ptr addrspace(2) @air.get_read_sampler() #8 + %5 = tail call { <4 x float>, i8 } @air.read_texture_buffer_1d.v4f32(ptr addrspace(1) readonly captures(none) %0, ptr addrspace(2) %4, i32 %2, i32 1) #9 + %6 = extractvalue { <4 x float>, i8 } %5, 0 + %7 = zext i32 %2 to i64 + %8 = getelementptr inbounds <4 x float>, ptr addrspace(1) %1, i64 %7 + store <4 x float> %6, ptr addrspace(1) %8, align 16, !tbaa !40, !alias.scope !43, !noalias !46 + ret void +} + +; Function Attrs: mustprogress nofree nounwind willreturn +define void @a8r_buffer_read_half(ptr addrspace(1) readonly captures(none) %0, ptr addrspace(1) noundef writeonly captures(none) "air-buffer-no-alias" %1, i32 noundef %2) local_unnamed_addr #1 { + %4 = tail call ptr addrspace(2) @air.get_read_sampler() #8 + %5 = tail call { <4 x half>, i8 } @air.read_texture_buffer_1d.v4f16(ptr addrspace(1) readonly captures(none) %0, ptr addrspace(2) %4, i32 %2, i32 1) #9 + %6 = extractvalue { <4 x half>, i8 } %5, 0 + %7 = tail call fast <4 x float> @air.convert.f.v4f32.f.v4f16(<4 x half> %6) #10 + %8 = zext i32 %2 to i64 + %9 = getelementptr inbounds <4 x float>, ptr addrspace(1) %1, i64 %8 + store <4 x float> %7, ptr addrspace(1) %9, align 16, !tbaa !40, !alias.scope !48, !noalias !51 + ret void +} + +; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none) +declare <4 x float> @air.convert.f.v4f32.f.v4f16(<4 x half>) local_unnamed_addr #2 + +; Function Attrs: mustprogress nounwind willreturn memory(argmem: readwrite) +define void @a8r_buffer_write(ptr addrspace(1) captures(none) %0, ptr addrspace(2) noundef readonly captures(none) "air-buffer-no-alias" %1, i32 noundef %2) local_unnamed_addr #3 { + %4 = load <4 x float>, ptr addrspace(2) %1, align 16, !tbaa !40, !alias.scope !53, !noalias !56 + tail call void @air.write_texture_buffer_1d.v4f32(ptr addrspace(1) captures(none) %0, i32 %2, <4 x float> %4, i32 2) #11, !alias.scope !56, !noalias !53 + ret void +} + +; Function Attrs: mustprogress nounwind willreturn +define void @a8r_buffer_read_write(ptr addrspace(1) %0, ptr addrspace(2) noundef readonly captures(none) "air-buffer-no-alias" %1, ptr addrspace(1) noundef writeonly captures(none) "air-buffer-no-alias" %2, i32 noundef %3) local_unnamed_addr #4 { + %5 = tail call ptr addrspace(2) @air.get_read_sampler() #8 + %6 = tail call { <4 x float>, i8 } @air.read_texture_buffer_1d.v4f32(ptr addrspace(1) readonly captures(none) %0, ptr addrspace(2) %5, i32 %3, i32 3) #9 + %7 = extractvalue { <4 x float>, i8 } %6, 0 + %8 = zext i32 %3 to i64 + %9 = getelementptr inbounds <4 x float>, ptr addrspace(1) %2, i64 %8 + store <4 x float> %7, ptr addrspace(1) %9, align 16, !tbaa !40, !alias.scope !58, !noalias !61 + %10 = load <4 x float>, ptr addrspace(2) %1, align 16, !tbaa !40, !alias.scope !64, !noalias !65 + tail call void @air.write_texture_buffer_1d.v4f32(ptr addrspace(1) captures(none) %0, i32 %3, <4 x float> %10, i32 3) #11, !alias.scope !66, !noalias !67 + ret void +} + +; Function Attrs: mustprogress nounwind willreturn +define void @a8r_held(ptr addrspace(2) noundef readonly align 8 captures(none) dereferenceable(16) "air-buffer-no-alias" %0, ptr addrspace(2) noundef readonly captures(none) "air-buffer-no-alias" %1, ptr addrspace(1) noundef writeonly captures(none) "air-buffer-no-alias" %2, <2 x i32> noundef %3) local_unnamed_addr #4 { + %5 = getelementptr inbounds %struct.A8rHeld, ptr addrspace(2) %0, i64 0, i32 0, i32 0 + %6 = load ptr addrspace(1), ptr addrspace(2) %5, align 8, !tbaa !68, !alias.scope !71, !noalias !74 + %7 = tail call ptr addrspace(2) @air.get_read_sampler() #8 + %8 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) readonly captures(none) %6, ptr addrspace(2) %7, <2 x i32> %3, <2 x i32> zeroinitializer, i32 0, i32 3) #9 + %9 = extractvalue { <4 x float>, i8 } %8, 0 + %10 = extractelement <2 x i32> %3, i64 1 + %11 = shl i32 %10, 3 + %12 = extractelement <2 x i32> %3, i64 0 + %13 = add i32 %11, %12 + %14 = zext i32 %13 to i64 + %15 = getelementptr inbounds <4 x float>, ptr addrspace(1) %2, i64 %14 + store <4 x float> %9, ptr addrspace(1) %15, align 16, !tbaa !40, !alias.scope !77, !noalias !78 + %16 = load <4 x float>, ptr addrspace(2) %1, align 16, !tbaa !40, !alias.scope !79, !noalias !80 + tail call void @air.write_texture_2d.v4f32(ptr addrspace(1) captures(none) %6, <2 x i32> %3, <4 x float> %16, i32 0, i32 3) #11 + %17 = getelementptr inbounds <4 x float>, ptr addrspace(2) %1, i64 1 + %18 = load <4 x float>, ptr addrspace(2) %17, align 16, !tbaa !40, !alias.scope !79, !noalias !80 + %19 = getelementptr inbounds %struct.A8rHeld, ptr addrspace(2) %0, i64 0, i32 1, i32 0 + %20 = load ptr addrspace(1), ptr addrspace(2) %19, align 8, !tbaa !81, !alias.scope !71, !noalias !74 + tail call void @air.write_texture_2d.v4f32(ptr addrspace(1) captures(none) %20, <2 x i32> %3, <4 x float> %18, i32 0, i32 2) #11 + ret void +} + +; Function Attrs: mustprogress nofree nounwind willreturn memory(inaccessiblemem: read) +declare ptr addrspace(2) @air.get_read_sampler() local_unnamed_addr #5 + +; Function Attrs: mustprogress nofree nounwind willreturn memory(argmem: read) +declare { <4 x float>, i8 } @air.read_texture_buffer_1d.v4f32(ptr addrspace(1) readonly captures(none), ptr addrspace(2), i32, i32) local_unnamed_addr #6 + +; Function Attrs: mustprogress nofree nounwind willreturn memory(argmem: read) +declare { <4 x half>, i8 } @air.read_texture_buffer_1d.v4f16(ptr addrspace(1) readonly captures(none), ptr addrspace(2), i32, i32) local_unnamed_addr #6 + +; Function Attrs: mustprogress nounwind willreturn memory(argmem: readwrite) +declare void @air.write_texture_buffer_1d.v4f32(ptr addrspace(1) captures(none), i32, <4 x float>, i32) local_unnamed_addr #7 + +; Function Attrs: mustprogress nofree nounwind willreturn memory(argmem: read) +declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) readonly captures(none), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) local_unnamed_addr #6 + +; Function Attrs: mustprogress nounwind willreturn memory(argmem: readwrite) +declare void @air.write_texture_2d.v4f32(ptr addrspace(1) captures(none), <2 x i32>, <4 x float>, i32, i32) local_unnamed_addr #7 + +attributes #0 = { mustprogress nofree nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #1 = { mustprogress nofree nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="64" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #2 = { mustprogress nofree nosync nounwind willreturn memory(none) } +attributes #3 = { mustprogress nounwind willreturn memory(argmem: readwrite) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #4 = { mustprogress nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #5 = { mustprogress nofree nounwind willreturn memory(inaccessiblemem: read) } +attributes #6 = { mustprogress nofree nounwind willreturn memory(argmem: read) } +attributes #7 = { mustprogress nounwind willreturn memory(argmem: readwrite) } +attributes #8 = { nounwind willreturn memory(inaccessiblemem: read) } +attributes #9 = { nounwind willreturn memory(argmem: read) } +attributes #10 = { nounwind willreturn memory(none) } +attributes #11 = { nounwind willreturn memory(argmem: readwrite) } + +!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} +!air.kernel = !{!9, !15, !18, !22, !27} +!air.compile_options = !{!34, !35, !36} +!llvm.ident = !{!37} +!air.version = !{!38} +!air.language_version = !{!39} + +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 27, i32 0]} +!1 = !{i32 1, !"wchar_size", i32 4} +!2 = !{i32 7, !"frame-pointer", i32 2} +!3 = !{i32 7, !"air.max_device_buffers", i32 31} +!4 = !{i32 7, !"air.max_constant_buffers", i32 31} +!5 = !{i32 7, !"air.max_threadgroup_buffers", i32 31} +!6 = !{i32 7, !"air.max_textures", i32 128} +!7 = !{i32 7, !"air.max_read_write_textures", i32 8} +!8 = !{i32 7, !"air.max_samplers", i32 16} +!9 = !{ptr @a8r_buffer_read, !10, !11} +!10 = !{} +!11 = !{!12, !13, !14} +!12 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture_buffer", !"air.arg_name", !"t"} +!13 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"} +!14 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"g"} +!15 = !{ptr @a8r_buffer_read_half, !10, !16} +!16 = !{!17, !13, !14} +!17 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture_buffer", !"air.arg_name", !"t"} +!18 = !{ptr @a8r_buffer_write, !10, !19} +!19 = !{!20, !21, !14} +!20 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.write", !"air.arg_type_name", !"texture_buffer", !"air.arg_name", !"t"} +!21 = !{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"color"} +!22 = !{ptr @a8r_buffer_read_write, !10, !23} +!23 = !{!24, !21, !25, !26} +!24 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.arg_type_name", !"texture_buffer", !"air.arg_name", !"t"} +!25 = !{i32 2, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"} +!26 = !{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"g"} +!27 = !{ptr @a8r_held, !10, !28} +!28 = !{!29, !21, !25, !33} +!29 = !{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 16, !"air.location_index", i32 2, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !30, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"A8rHeld", !"air.arg_name", !"held"} +!30 = !{i32 0, i32 8, i32 0, !"texture2d", !"rw", !"air.indirect_argument", !31, i32 8, i32 8, i32 0, !"texture2d", !"w", !"air.indirect_argument", !32} +!31 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"rw"} +!32 = !{i32 1, !"air.texture", !"air.location_index", i32 1, i32 1, !"air.write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"w"} +!33 = !{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"g"} +!34 = !{!"air.compile.denorms_disable"} +!35 = !{!"air.compile.fast_math_enable"} +!36 = !{!"air.compile.framebuffer_fetch_enable"} +!37 = !{!"Apple metal version 32023.921 (metalfe-32023.921.6)"} +!38 = !{i32 2, i32 8, i32 0} +!39 = !{!"Metal", i32 4, i32 0, i32 0} +!40 = !{!41, !41, i64 0} +!41 = !{!"omnipotent char", !42, i64 0} +!42 = !{!"Simple C++ TBAA"} +!43 = !{!44} +!44 = distinct !{!44, !45, !"air-alias-scope-arg(1)"} +!45 = distinct !{!45, !"air-alias-scopes(a8r_buffer_read)"} +!46 = !{!47} +!47 = distinct !{!47, !45, !"air-alias-scope-textures"} +!48 = !{!49} +!49 = distinct !{!49, !50, !"air-alias-scope-arg(1)"} +!50 = distinct !{!50, !"air-alias-scopes(a8r_buffer_read_half)"} +!51 = !{!52} +!52 = distinct !{!52, !50, !"air-alias-scope-textures"} +!53 = !{!54} +!54 = distinct !{!54, !55, !"air-alias-scope-arg(1)"} +!55 = distinct !{!55, !"air-alias-scopes(a8r_buffer_write)"} +!56 = !{!57} +!57 = distinct !{!57, !55, !"air-alias-scope-textures"} +!58 = !{!59} +!59 = distinct !{!59, !60, !"air-alias-scope-arg(2)"} +!60 = distinct !{!60, !"air-alias-scopes(a8r_buffer_read_write)"} +!61 = !{!62, !63} +!62 = distinct !{!62, !60, !"air-alias-scope-textures"} +!63 = distinct !{!63, !60, !"air-alias-scope-arg(1)"} +!64 = !{!63} +!65 = !{!62, !59} +!66 = !{!62} +!67 = !{!63, !59} +!68 = !{!69, !70, i64 0} +!69 = !{!"_ZTSN5metal9texture2dIfLNS_6accessE3ELNS_16memory_coherenceE0EvEE", !70, i64 0} +!70 = !{!"__metal_texture_2d_t", !41, i64 0} +!71 = !{!72} +!72 = distinct !{!72, !73, !"air-alias-scope-arg(0)"} +!73 = distinct !{!73, !"air-alias-scopes(a8r_held)"} +!74 = !{!75, !76} +!75 = distinct !{!75, !73, !"air-alias-scope-arg(1)"} +!76 = distinct !{!76, !73, !"air-alias-scope-arg(2)"} +!77 = !{!76} +!78 = !{!72, !75} +!79 = !{!75} +!80 = !{!72, !76} +!81 = !{!82, !70, i64 0} +!82 = !{!"_ZTSN5metal9texture2dIfLNS_6accessE2ELNS_16memory_coherenceE0EvEE", !70, i64 0} diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/a8r_buffers.metal b/crates/metal2vulkan-validation/fixtures/public/engine/a8r_buffers.metal new file mode 100644 index 000000000..581a421ad --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/engine/a8r_buffers.metal @@ -0,0 +1,43 @@ +// The texture-buffer and argument-buffer functions of the `A8Unorm` lane +// (validation/src/runtime_lane/alpha_in_red.rs), our own MSL: kernels that read (as `float` and as +// `half`), write, and read and write a texture buffer at every texel, and one that reads and writes +// the 8 x 8 storage textures an argument buffer (buffer 2) holds. +#include +using namespace metal; + +kernel void a8r_buffer_read(texture_buffer t [[texture(0)]], + device float4 *out [[buffer(1)]], uint g [[thread_position_in_grid]]) { + out[g] = t.read(g); +} + +kernel void a8r_buffer_read_half(texture_buffer t [[texture(0)]], + device float4 *out [[buffer(1)]], + uint g [[thread_position_in_grid]]) { + out[g] = float4(t.read(g)); +} + +kernel void a8r_buffer_write(texture_buffer t [[texture(0)]], + constant float4 *color [[buffer(0)]], + uint g [[thread_position_in_grid]]) { + t.write(color[0], g); +} + +kernel void a8r_buffer_read_write(texture_buffer t [[texture(0)]], + constant float4 *color [[buffer(0)]], + device float4 *out [[buffer(1)]], + uint g [[thread_position_in_grid]]) { + out[g] = t.read(g); + t.write(color[0], g); +} + +struct A8rHeld { + texture2d rw; + texture2d w; +}; + +kernel void a8r_held(constant A8rHeld &held [[buffer(2)]], constant float4 *color [[buffer(0)]], + device float4 *out [[buffer(1)]], uint2 g [[thread_position_in_grid]]) { + out[g.y * 8 + g.x] = held.rw.read(g); + held.rw.write(color[0], g); + held.w.write(color[1], g); +} diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/a8r_targets.air.ll b/crates/metal2vulkan-validation/fixtures/public/engine/a8r_targets.air.ll new file mode 100644 index 000000000..e66477553 --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/engine/a8r_targets.air.ll @@ -0,0 +1,292 @@ +; Generated by scripts/regen-air-fixtures from a8r_targets.metal (typed pointers; xcrun metal-as reassembles it). Do not edit. +; ModuleID = '-' +source_filename = "-" +target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" +target triple = "air64_v28-apple-macosx26.0.0" + +%struct._texture_2d_t = type opaque +%struct._sampler_t = type opaque + +; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn +define <{ <4 x float> }> @a8r_vertex(i32 noundef %0) local_unnamed_addr #0 { + %2 = shl i32 %0, 1 + %3 = and i32 %2, 2 + %4 = tail call fast float @air.convert.f.f32.u.i32(i32 %3) #14 + %5 = insertelement <2 x float> undef, float %4, i64 0 + %6 = and i32 %0, 2 + %7 = tail call fast float @air.convert.f.f32.u.i32(i32 %6) #14 + %8 = insertelement <2 x float> %5, float %7, i64 1 + %9 = fmul fast <2 x float> %8, + %10 = fadd fast <2 x float> %9, + %11 = shufflevector <2 x float> %10, <2 x float> poison, <4 x i32> + %12 = shufflevector <4 x float> %11, <4 x float> , <4 x i32> + %13 = insertvalue <{ <4 x float> }> undef, <4 x float> %12, 0 + ret <{ <4 x float> }> %13 +} + +; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn +declare float @air.convert.f.f32.u.i32(i32) local_unnamed_addr #1 + +; Function Attrs: mustprogress nofree norecurse nosync nounwind readnone willreturn +define <{ <4 x float> }> @a8r_half_vertex(i32 noundef %0) local_unnamed_addr #2 { + %2 = icmp eq i32 %0, 1 + %3 = select fast i1 %2, float 1.000000e+00, float -1.000000e+00 + %4 = icmp eq i32 %0, 2 + %5 = select fast i1 %4, float 1.000000e+00, float -1.000000e+00 + %6 = insertelement <4 x float> , float %3, i64 0 + %7 = insertelement <4 x float> %6, float %5, i64 1 + %8 = insertvalue <{ <4 x float> }> undef, <4 x float> %7, 0 + ret <{ <4 x float> }> %8 +} + +; Function Attrs: mustprogress nofree norecurse nosync nounwind readnone willreturn +define <4 x float> @a8r_fill(<4 x float> %0, <4 x float> addrspace(2)* nocapture noundef readonly "air-buffer-no-alias" %1) local_unnamed_addr #3 { + %3 = load <4 x float>, <4 x float> addrspace(2)* %1, align 16, !tbaa !58, !alias.scope !61 + ret <4 x float> %3 +} + +; Function Attrs: mustprogress nofree norecurse nosync nounwind readnone willreturn +define <{ <4 x float>, <4 x float> }> @a8r_dual(<4 x float> %0, <4 x float> addrspace(2)* nocapture noundef readonly "air-buffer-no-alias" %1) local_unnamed_addr #3 { + %3 = load <4 x float>, <4 x float> addrspace(2)* %1, align 16, !tbaa !58, !alias.scope !64 + %4 = getelementptr inbounds <4 x float>, <4 x float> addrspace(2)* %1, i64 1 + %5 = load <4 x float>, <4 x float> addrspace(2)* %4, align 16, !tbaa !58, !alias.scope !64 + %6 = insertvalue <{ <4 x float>, <4 x float> }> undef, <4 x float> %3, 0 + %7 = insertvalue <{ <4 x float>, <4 x float> }> %6, <4 x float> %5, 1 + ret <{ <4 x float>, <4 x float> }> %7 +} + +; Function Attrs: argmemonly mustprogress nofree nosync nounwind willreturn writeonly +define <4 x float> @a8r_fetch(<4 x float> %0, <4 x float> noundef %1, <4 x float> addrspace(2)* nocapture noundef readonly "air-buffer-no-alias" %2, <4 x float> addrspace(1)* nocapture noundef writeonly "air-buffer-no-alias" %3) local_unnamed_addr #4 { + %5 = shufflevector <4 x float> %0, <4 x float> poison, <2 x i32> + %6 = tail call <2 x i32> @air.convert.u.v2i32.f.v2f32(<2 x float> %5) #14 + %7 = extractelement <2 x i32> %6, i64 1 + %8 = shl i32 %7, 3 + %9 = extractelement <2 x i32> %6, i64 0 + %10 = add i32 %8, %9 + %11 = zext i32 %10 to i64 + %12 = getelementptr inbounds <4 x float>, <4 x float> addrspace(1)* %3, i64 %11 + store <4 x float> %1, <4 x float> addrspace(1)* %12, align 16, !tbaa !58, !alias.scope !67, !noalias !70 + %13 = load <4 x float>, <4 x float> addrspace(2)* %2, align 16, !tbaa !58, !alias.scope !70, !noalias !67 + ret <4 x float> %13 +} + +; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn +declare <2 x i32> @air.convert.u.v2i32.f.v2f32(<2 x float>) local_unnamed_addr #1 + +; Function Attrs: argmemonly mustprogress nounwind willreturn +define void @a8r_write(%struct._texture_2d_t addrspace(1)* nocapture %0, <4 x float> addrspace(2)* nocapture noundef readonly "air-buffer-no-alias" %1, <2 x i32> noundef %2) local_unnamed_addr #5 { + %4 = load <4 x float>, <4 x float> addrspace(2)* %1, align 16, !tbaa !58, !alias.scope !72, !noalias !75 + tail call void @air.write_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture %0, <2 x i32> %2, <4 x float> %4, i32 0, i32 2) #15, !alias.scope !75, !noalias !72 + ret void +} + +; Function Attrs: argmemonly mustprogress nounwind willreturn +define void @a8r_write_half(%struct._texture_2d_t addrspace(1)* nocapture %0, <4 x float> addrspace(2)* nocapture noundef readonly "air-buffer-no-alias" %1, <2 x i32> noundef %2) local_unnamed_addr #6 { + %4 = load <4 x float>, <4 x float> addrspace(2)* %1, align 16, !tbaa !58, !alias.scope !77, !noalias !80 + %5 = tail call fast <4 x half> @air.convert.f.v4f16.f.v4f32(<4 x float> %4) #14 + tail call void @air.write_texture_2d.v4f16(%struct._texture_2d_t addrspace(1)* nocapture %0, <2 x i32> %2, <4 x half> %5, i32 0, i32 2) #15, !alias.scope !80, !noalias !77 + ret void +} + +; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn +declare <4 x half> @air.convert.f.v4f16.f.v4f32(<4 x float>) local_unnamed_addr #1 + +; Function Attrs: mustprogress nofree nounwind willreturn +define void @a8r_read(%struct._texture_2d_t addrspace(1)* nocapture readonly %0, <4 x float> addrspace(1)* nocapture noundef writeonly "air-buffer-no-alias" %1, <2 x i32> noundef %2) local_unnamed_addr #7 { + %4 = tail call %struct._sampler_t addrspace(2)* @air.get_read_sampler() #16 + %5 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly %0, %struct._sampler_t addrspace(2)* %4, <2 x i32> %2, <2 x i32> zeroinitializer, i32 0, i32 1) #17 + %6 = extractvalue { <4 x float>, i8 } %5, 0 + %7 = extractelement <2 x i32> %2, i64 1 + %8 = shl i32 %7, 3 + %9 = extractelement <2 x i32> %2, i64 0 + %10 = add i32 %8, %9 + %11 = zext i32 %10 to i64 + %12 = getelementptr inbounds <4 x float>, <4 x float> addrspace(1)* %1, i64 %11 + store <4 x float> %6, <4 x float> addrspace(1)* %12, align 16, !tbaa !58, !alias.scope !82, !noalias !85 + ret void +} + +; Function Attrs: argmemonly convergent mustprogress nofree nounwind willreturn +define void @a8r_sample(%struct._texture_2d_t addrspace(1)* nocapture readonly %0, %struct._sampler_t addrspace(2)* nocapture readonly %1, <4 x float> addrspace(1)* nocapture noundef writeonly "air-buffer-no-alias" %2, <2 x i32> noundef %3) local_unnamed_addr #8 { + %5 = tail call fast <2 x float> @air.convert.f.v2f32.u.v2i32(<2 x i32> %3) #14 + %6 = fadd fast <2 x float> %5, + %7 = fmul fast <2 x float> %6, + %8 = tail call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly %0, %struct._sampler_t addrspace(2)* nocapture readonly %1, <2 x float> %7, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0) #18, !alias.scope !87, !noalias !91 + %9 = extractvalue { <4 x float>, i8 } %8, 0 + %10 = extractelement <2 x i32> %3, i64 1 + %11 = shl i32 %10, 3 + %12 = extractelement <2 x i32> %3, i64 0 + %13 = add i32 %11, %12 + %14 = zext i32 %13 to i64 + %15 = getelementptr inbounds <4 x float>, <4 x float> addrspace(1)* %2, i64 %14 + store <4 x float> %9, <4 x float> addrspace(1)* %15, align 16, !tbaa !58, !alias.scope !91, !noalias !87 + ret void +} + +; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn +declare <2 x float> @air.convert.f.v2f32.u.v2i32(<2 x i32>) local_unnamed_addr #1 + +; Function Attrs: mustprogress nounwind willreturn +define void @a8r_read_write(%struct._texture_2d_t addrspace(1)* %0, <4 x float> addrspace(2)* nocapture noundef readonly "air-buffer-no-alias" %1, <4 x float> addrspace(1)* nocapture noundef writeonly "air-buffer-no-alias" %2, <2 x i32> noundef %3) local_unnamed_addr #9 { + %5 = tail call %struct._sampler_t addrspace(2)* @air.get_read_sampler() #16 + %6 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly %0, %struct._sampler_t addrspace(2)* %5, <2 x i32> %3, <2 x i32> zeroinitializer, i32 0, i32 3) #17 + %7 = extractvalue { <4 x float>, i8 } %6, 0 + %8 = extractelement <2 x i32> %3, i64 1 + %9 = shl i32 %8, 3 + %10 = extractelement <2 x i32> %3, i64 0 + %11 = add i32 %9, %10 + %12 = zext i32 %11 to i64 + %13 = getelementptr inbounds <4 x float>, <4 x float> addrspace(1)* %2, i64 %12 + store <4 x float> %7, <4 x float> addrspace(1)* %13, align 16, !tbaa !58, !alias.scope !93, !noalias !96 + %14 = load <4 x float>, <4 x float> addrspace(2)* %1, align 16, !tbaa !58, !alias.scope !99, !noalias !100 + tail call void @air.write_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture %0, <2 x i32> %3, <4 x float> %14, i32 0, i32 3) #15, !alias.scope !101, !noalias !102 + ret void +} + +; Function Attrs: argmemonly mustprogress nounwind willreturn +declare void @air.write_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture, <2 x i32>, <4 x float>, i32, i32) local_unnamed_addr #10 + +; Function Attrs: argmemonly mustprogress nounwind willreturn +declare void @air.write_texture_2d.v4f16(%struct._texture_2d_t addrspace(1)* nocapture, <2 x i32>, <4 x half>, i32, i32) local_unnamed_addr #10 + +; Function Attrs: inaccessiblememonly mustprogress nofree nounwind readonly willreturn +declare %struct._sampler_t addrspace(2)* @air.get_read_sampler() local_unnamed_addr #11 + +; Function Attrs: argmemonly mustprogress nofree nounwind readonly willreturn +declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly, %struct._sampler_t addrspace(2)*, <2 x i32>, <2 x i32>, i32, i32) local_unnamed_addr #12 + +; Function Attrs: argmemonly convergent mustprogress nofree nounwind readonly willreturn +declare { <4 x float>, i8 } @air.sample_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly, %struct._sampler_t addrspace(2)* nocapture readonly, <2 x float>, i1, <2 x i32>, i1, float, float, i32) local_unnamed_addr #13 + +attributes #0 = { mustprogress nofree nosync nounwind readnone willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #1 = { mustprogress nofree nosync nounwind readnone willreturn } +attributes #2 = { mustprogress nofree norecurse nosync nounwind readnone willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #3 = { mustprogress nofree norecurse nosync nounwind readnone willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #4 = { argmemonly mustprogress nofree nosync nounwind willreturn writeonly "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #5 = { argmemonly mustprogress nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #6 = { argmemonly mustprogress nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="64" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #7 = { mustprogress nofree nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #8 = { argmemonly convergent mustprogress nofree nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #9 = { mustprogress nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #10 = { argmemonly mustprogress nounwind willreturn } +attributes #11 = { inaccessiblememonly mustprogress nofree nounwind readonly willreturn } +attributes #12 = { argmemonly mustprogress nofree nounwind readonly willreturn } +attributes #13 = { argmemonly convergent mustprogress nofree nounwind readonly willreturn } +attributes #14 = { nounwind readnone willreturn } +attributes #15 = { argmemonly nounwind willreturn } +attributes #16 = { inaccessiblememonly nounwind readonly willreturn } +attributes #17 = { argmemonly nounwind readonly willreturn } +attributes #18 = { argmemonly convergent nounwind readonly willreturn } + +!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} +!air.vertex = !{!9, !14} +!air.fragment = !{!15, !21, !25} +!air.kernel = !{!31, !36, !39, !43, !49} +!air.compile_options = !{!52, !53, !54} +!llvm.ident = !{!55} +!air.version = !{!56} +!air.language_version = !{!57} + +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 27, i32 0]} +!1 = !{i32 1, !"wchar_size", i32 4} +!2 = !{i32 7, !"frame-pointer", i32 2} +!3 = !{i32 7, !"air.max_device_buffers", i32 31} +!4 = !{i32 7, !"air.max_constant_buffers", i32 31} +!5 = !{i32 7, !"air.max_threadgroup_buffers", i32 31} +!6 = !{i32 7, !"air.max_textures", i32 128} +!7 = !{i32 7, !"air.max_read_write_textures", i32 8} +!8 = !{i32 7, !"air.max_samplers", i32 16} +!9 = !{<{ <4 x float> }> (i32)* @a8r_vertex, !10, !12} +!10 = !{!11} +!11 = !{!"air.position", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"} +!12 = !{!13} +!13 = !{i32 0, !"air.vertex_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"id"} +!14 = !{<{ <4 x float> }> (i32)* @a8r_half_vertex, !10, !12} +!15 = !{<4 x float> (<4 x float>, <4 x float> addrspace(2)*)* @a8r_fill, !16, !18} +!16 = !{!17} +!17 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"} +!18 = !{!19, !20} +!19 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position", !"air.arg_unused"} +!20 = !{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"color"} +!21 = !{<{ <4 x float>, <4 x float> }> (<4 x float>, <4 x float> addrspace(2)*)* @a8r_dual, !22, !18} +!22 = !{!23, !24} +!23 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4", !"air.arg_name", !"first"} +!24 = !{!"air.render_target", i32 0, i32 1, !"air.arg_type_name", !"float4", !"air.arg_name", !"second"} +!25 = !{<4 x float> (<4 x float>, <4 x float>, <4 x float> addrspace(2)*, <4 x float> addrspace(1)*)* @a8r_fetch, !16, !26} +!26 = !{!27, !28, !29, !30} +!27 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"} +!28 = !{i32 1, !"air.render_target", i32 0, !"air.arg_type_name", !"float4", !"air.arg_name", !"held"} +!29 = !{i32 2, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"color"} +!30 = !{i32 3, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"} +!31 = !{void (%struct._texture_2d_t addrspace(1)*, <4 x float> addrspace(2)*, <2 x i32>)* @a8r_write, !32, !33} +!32 = !{} +!33 = !{!34, !20, !35} +!34 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} +!35 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"g"} +!36 = !{void (%struct._texture_2d_t addrspace(1)*, <4 x float> addrspace(2)*, <2 x i32>)* @a8r_write_half, !32, !37} +!37 = !{!38, !20, !35} +!38 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} +!39 = !{void (%struct._texture_2d_t addrspace(1)*, <4 x float> addrspace(1)*, <2 x i32>)* @a8r_read, !32, !40} +!40 = !{!41, !42, !35} +!41 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} +!42 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"} +!43 = !{void (%struct._texture_2d_t addrspace(1)*, %struct._sampler_t addrspace(2)*, <4 x float> addrspace(1)*, <2 x i32>)* @a8r_sample, !32, !44} +!44 = !{!45, !46, !47, !48} +!45 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} +!46 = !{i32 1, !"air.sampler", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"sampler", !"air.arg_name", !"s"} +!47 = !{i32 2, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"} +!48 = !{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"g"} +!49 = !{void (%struct._texture_2d_t addrspace(1)*, <4 x float> addrspace(2)*, <4 x float> addrspace(1)*, <2 x i32>)* @a8r_read_write, !32, !50} +!50 = !{!51, !20, !47, !48} +!51 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} +!52 = !{!"air.compile.denorms_disable"} +!53 = !{!"air.compile.fast_math_enable"} +!54 = !{!"air.compile.framebuffer_fetch_enable"} +!55 = !{!"Apple metal version 32023.921 (metalfe-32023.921.6)"} +!56 = !{i32 2, i32 8, i32 0} +!57 = !{!"Metal", i32 4, i32 0, i32 0} +!58 = !{!59, !59, i64 0} +!59 = !{!"omnipotent char", !60, i64 0} +!60 = !{!"Simple C++ TBAA"} +!61 = !{!62} +!62 = distinct !{!62, !63, !"air-alias-scope-arg(1)"} +!63 = distinct !{!63, !"air-alias-scopes(a8r_fill)"} +!64 = !{!65} +!65 = distinct !{!65, !66, !"air-alias-scope-arg(1)"} +!66 = distinct !{!66, !"air-alias-scopes(a8r_dual)"} +!67 = !{!68} +!68 = distinct !{!68, !69, !"air-alias-scope-arg(3)"} +!69 = distinct !{!69, !"air-alias-scopes(a8r_fetch)"} +!70 = !{!71} +!71 = distinct !{!71, !69, !"air-alias-scope-arg(2)"} +!72 = !{!73} +!73 = distinct !{!73, !74, !"air-alias-scope-arg(1)"} +!74 = distinct !{!74, !"air-alias-scopes(a8r_write)"} +!75 = !{!76} +!76 = distinct !{!76, !74, !"air-alias-scope-textures"} +!77 = !{!78} +!78 = distinct !{!78, !79, !"air-alias-scope-arg(1)"} +!79 = distinct !{!79, !"air-alias-scopes(a8r_write_half)"} +!80 = !{!81} +!81 = distinct !{!81, !79, !"air-alias-scope-textures"} +!82 = !{!83} +!83 = distinct !{!83, !84, !"air-alias-scope-arg(1)"} +!84 = distinct !{!84, !"air-alias-scopes(a8r_read)"} +!85 = !{!86} +!86 = distinct !{!86, !84, !"air-alias-scope-textures"} +!87 = !{!88, !90} +!88 = distinct !{!88, !89, !"air-alias-scope-textures"} +!89 = distinct !{!89, !"air-alias-scopes(a8r_sample)"} +!90 = distinct !{!90, !89, !"air-alias-scope-samplers"} +!91 = !{!92} +!92 = distinct !{!92, !89, !"air-alias-scope-arg(2)"} +!93 = !{!94} +!94 = distinct !{!94, !95, !"air-alias-scope-arg(2)"} +!95 = distinct !{!95, !"air-alias-scopes(a8r_read_write)"} +!96 = !{!97, !98} +!97 = distinct !{!97, !95, !"air-alias-scope-textures"} +!98 = distinct !{!98, !95, !"air-alias-scope-arg(1)"} +!99 = !{!98} +!100 = !{!97, !94} +!101 = !{!97} +!102 = !{!98, !94} diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/a8r_targets.ll b/crates/metal2vulkan-validation/fixtures/public/engine/a8r_targets.ll new file mode 100644 index 000000000..4bfb666bc --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/engine/a8r_targets.ll @@ -0,0 +1,289 @@ +; Generated by scripts/regen-air-fixtures from a8r_targets.metal (llvm-dis of a8r_targets.air). Do not edit. +; ModuleID = '' +source_filename = "-" +target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" +target triple = "air64_v28-apple-macosx26.0.0" + +; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none) +define <{ <4 x float> }> @a8r_vertex(i32 noundef %0) local_unnamed_addr #0 { + %2 = shl i32 %0, 1 + %3 = and i32 %2, 2 + %4 = tail call fast float @air.convert.f.f32.u.i32(i32 %3) #14 + %5 = insertelement <2 x float> undef, float %4, i64 0 + %6 = and i32 %0, 2 + %7 = tail call fast float @air.convert.f.f32.u.i32(i32 %6) #14 + %8 = insertelement <2 x float> %5, float %7, i64 1 + %9 = fmul fast <2 x float> %8, splat (float 2.000000e+00) + %10 = fadd fast <2 x float> %9, splat (float -1.000000e+00) + %11 = shufflevector <2 x float> %10, <2 x float> poison, <4 x i32> + %12 = shufflevector <4 x float> %11, <4 x float> , <4 x i32> + %13 = insertvalue <{ <4 x float> }> undef, <4 x float> %12, 0 + ret <{ <4 x float> }> %13 +} + +; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none) +declare float @air.convert.f.f32.u.i32(i32) local_unnamed_addr #1 + +; Function Attrs: mustprogress nofree norecurse nosync nounwind willreturn memory(none) +define <{ <4 x float> }> @a8r_half_vertex(i32 noundef %0) local_unnamed_addr #2 { + %2 = icmp eq i32 %0, 1 + %3 = select fast i1 %2, float 1.000000e+00, float -1.000000e+00 + %4 = icmp eq i32 %0, 2 + %5 = select fast i1 %4, float 1.000000e+00, float -1.000000e+00 + %6 = insertelement <4 x float> , float %3, i64 0 + %7 = insertelement <4 x float> %6, float %5, i64 1 + %8 = insertvalue <{ <4 x float> }> undef, <4 x float> %7, 0 + ret <{ <4 x float> }> %8 +} + +; Function Attrs: mustprogress nofree norecurse nosync nounwind willreturn memory(none) +define <4 x float> @a8r_fill(<4 x float> %0, ptr addrspace(2) noundef readonly captures(none) "air-buffer-no-alias" %1) local_unnamed_addr #3 { + %3 = load <4 x float>, ptr addrspace(2) %1, align 16, !tbaa !58, !alias.scope !61 + ret <4 x float> %3 +} + +; Function Attrs: mustprogress nofree norecurse nosync nounwind willreturn memory(none) +define <{ <4 x float>, <4 x float> }> @a8r_dual(<4 x float> %0, ptr addrspace(2) noundef readonly captures(none) "air-buffer-no-alias" %1) local_unnamed_addr #3 { + %3 = load <4 x float>, ptr addrspace(2) %1, align 16, !tbaa !58, !alias.scope !64 + %4 = getelementptr inbounds <4 x float>, ptr addrspace(2) %1, i64 1 + %5 = load <4 x float>, ptr addrspace(2) %4, align 16, !tbaa !58, !alias.scope !64 + %6 = insertvalue <{ <4 x float>, <4 x float> }> undef, <4 x float> %3, 0 + %7 = insertvalue <{ <4 x float>, <4 x float> }> %6, <4 x float> %5, 1 + ret <{ <4 x float>, <4 x float> }> %7 +} + +; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(argmem: write) +define <4 x float> @a8r_fetch(<4 x float> %0, <4 x float> noundef %1, ptr addrspace(2) noundef readonly captures(none) "air-buffer-no-alias" %2, ptr addrspace(1) noundef writeonly captures(none) "air-buffer-no-alias" %3) local_unnamed_addr #4 { + %5 = shufflevector <4 x float> %0, <4 x float> poison, <2 x i32> + %6 = tail call <2 x i32> @air.convert.u.v2i32.f.v2f32(<2 x float> %5) #14 + %7 = extractelement <2 x i32> %6, i64 1 + %8 = shl i32 %7, 3 + %9 = extractelement <2 x i32> %6, i64 0 + %10 = add i32 %8, %9 + %11 = zext i32 %10 to i64 + %12 = getelementptr inbounds <4 x float>, ptr addrspace(1) %3, i64 %11 + store <4 x float> %1, ptr addrspace(1) %12, align 16, !tbaa !58, !alias.scope !67, !noalias !70 + %13 = load <4 x float>, ptr addrspace(2) %2, align 16, !tbaa !58, !alias.scope !70, !noalias !67 + ret <4 x float> %13 +} + +; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none) +declare <2 x i32> @air.convert.u.v2i32.f.v2f32(<2 x float>) local_unnamed_addr #1 + +; Function Attrs: mustprogress nounwind willreturn memory(argmem: readwrite) +define void @a8r_write(ptr addrspace(1) captures(none) %0, ptr addrspace(2) noundef readonly captures(none) "air-buffer-no-alias" %1, <2 x i32> noundef %2) local_unnamed_addr #5 { + %4 = load <4 x float>, ptr addrspace(2) %1, align 16, !tbaa !58, !alias.scope !72, !noalias !75 + tail call void @air.write_texture_2d.v4f32(ptr addrspace(1) captures(none) %0, <2 x i32> %2, <4 x float> %4, i32 0, i32 2) #15, !alias.scope !75, !noalias !72 + ret void +} + +; Function Attrs: mustprogress nounwind willreturn memory(argmem: readwrite) +define void @a8r_write_half(ptr addrspace(1) captures(none) %0, ptr addrspace(2) noundef readonly captures(none) "air-buffer-no-alias" %1, <2 x i32> noundef %2) local_unnamed_addr #6 { + %4 = load <4 x float>, ptr addrspace(2) %1, align 16, !tbaa !58, !alias.scope !77, !noalias !80 + %5 = tail call fast <4 x half> @air.convert.f.v4f16.f.v4f32(<4 x float> %4) #14 + tail call void @air.write_texture_2d.v4f16(ptr addrspace(1) captures(none) %0, <2 x i32> %2, <4 x half> %5, i32 0, i32 2) #15, !alias.scope !80, !noalias !77 + ret void +} + +; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none) +declare <4 x half> @air.convert.f.v4f16.f.v4f32(<4 x float>) local_unnamed_addr #1 + +; Function Attrs: mustprogress nofree nounwind willreturn +define void @a8r_read(ptr addrspace(1) readonly captures(none) %0, ptr addrspace(1) noundef writeonly captures(none) "air-buffer-no-alias" %1, <2 x i32> noundef %2) local_unnamed_addr #7 { + %4 = tail call ptr addrspace(2) @air.get_read_sampler() #16 + %5 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) readonly captures(none) %0, ptr addrspace(2) %4, <2 x i32> %2, <2 x i32> zeroinitializer, i32 0, i32 1) #17 + %6 = extractvalue { <4 x float>, i8 } %5, 0 + %7 = extractelement <2 x i32> %2, i64 1 + %8 = shl i32 %7, 3 + %9 = extractelement <2 x i32> %2, i64 0 + %10 = add i32 %8, %9 + %11 = zext i32 %10 to i64 + %12 = getelementptr inbounds <4 x float>, ptr addrspace(1) %1, i64 %11 + store <4 x float> %6, ptr addrspace(1) %12, align 16, !tbaa !58, !alias.scope !82, !noalias !85 + ret void +} + +; Function Attrs: convergent mustprogress nofree nounwind willreturn memory(argmem: readwrite) +define void @a8r_sample(ptr addrspace(1) readonly captures(none) %0, ptr addrspace(2) readonly captures(none) %1, ptr addrspace(1) noundef writeonly captures(none) "air-buffer-no-alias" %2, <2 x i32> noundef %3) local_unnamed_addr #8 { + %5 = tail call fast <2 x float> @air.convert.f.v2f32.u.v2i32(<2 x i32> %3) #14 + %6 = fadd fast <2 x float> %5, splat (float 5.000000e-01) + %7 = fmul fast <2 x float> %6, splat (float 1.250000e-01) + %8 = tail call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) readonly captures(none) %0, ptr addrspace(2) readonly captures(none) %1, <2 x float> %7, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0) #18, !alias.scope !87, !noalias !91 + %9 = extractvalue { <4 x float>, i8 } %8, 0 + %10 = extractelement <2 x i32> %3, i64 1 + %11 = shl i32 %10, 3 + %12 = extractelement <2 x i32> %3, i64 0 + %13 = add i32 %11, %12 + %14 = zext i32 %13 to i64 + %15 = getelementptr inbounds <4 x float>, ptr addrspace(1) %2, i64 %14 + store <4 x float> %9, ptr addrspace(1) %15, align 16, !tbaa !58, !alias.scope !91, !noalias !87 + ret void +} + +; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none) +declare <2 x float> @air.convert.f.v2f32.u.v2i32(<2 x i32>) local_unnamed_addr #1 + +; Function Attrs: mustprogress nounwind willreturn +define void @a8r_read_write(ptr addrspace(1) %0, ptr addrspace(2) noundef readonly captures(none) "air-buffer-no-alias" %1, ptr addrspace(1) noundef writeonly captures(none) "air-buffer-no-alias" %2, <2 x i32> noundef %3) local_unnamed_addr #9 { + %5 = tail call ptr addrspace(2) @air.get_read_sampler() #16 + %6 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) readonly captures(none) %0, ptr addrspace(2) %5, <2 x i32> %3, <2 x i32> zeroinitializer, i32 0, i32 3) #17 + %7 = extractvalue { <4 x float>, i8 } %6, 0 + %8 = extractelement <2 x i32> %3, i64 1 + %9 = shl i32 %8, 3 + %10 = extractelement <2 x i32> %3, i64 0 + %11 = add i32 %9, %10 + %12 = zext i32 %11 to i64 + %13 = getelementptr inbounds <4 x float>, ptr addrspace(1) %2, i64 %12 + store <4 x float> %7, ptr addrspace(1) %13, align 16, !tbaa !58, !alias.scope !93, !noalias !96 + %14 = load <4 x float>, ptr addrspace(2) %1, align 16, !tbaa !58, !alias.scope !99, !noalias !100 + tail call void @air.write_texture_2d.v4f32(ptr addrspace(1) captures(none) %0, <2 x i32> %3, <4 x float> %14, i32 0, i32 3) #15, !alias.scope !101, !noalias !102 + ret void +} + +; Function Attrs: mustprogress nounwind willreturn memory(argmem: readwrite) +declare void @air.write_texture_2d.v4f32(ptr addrspace(1) captures(none), <2 x i32>, <4 x float>, i32, i32) local_unnamed_addr #10 + +; Function Attrs: mustprogress nounwind willreturn memory(argmem: readwrite) +declare void @air.write_texture_2d.v4f16(ptr addrspace(1) captures(none), <2 x i32>, <4 x half>, i32, i32) local_unnamed_addr #10 + +; Function Attrs: mustprogress nofree nounwind willreturn memory(inaccessiblemem: read) +declare ptr addrspace(2) @air.get_read_sampler() local_unnamed_addr #11 + +; Function Attrs: mustprogress nofree nounwind willreturn memory(argmem: read) +declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) readonly captures(none), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) local_unnamed_addr #12 + +; Function Attrs: convergent mustprogress nofree nounwind willreturn memory(argmem: read) +declare { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) readonly captures(none), ptr addrspace(2) readonly captures(none), <2 x float>, i1, <2 x i32>, i1, float, float, i32) local_unnamed_addr #13 + +attributes #0 = { mustprogress nofree nosync nounwind willreturn memory(none) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #1 = { mustprogress nofree nosync nounwind willreturn memory(none) } +attributes #2 = { mustprogress nofree norecurse nosync nounwind willreturn memory(none) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #3 = { mustprogress nofree norecurse nosync nounwind willreturn memory(none) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #4 = { mustprogress nofree nosync nounwind willreturn memory(argmem: write) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #5 = { mustprogress nounwind willreturn memory(argmem: readwrite) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #6 = { mustprogress nounwind willreturn memory(argmem: readwrite) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="64" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #7 = { mustprogress nofree nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #8 = { convergent mustprogress nofree nounwind willreturn memory(argmem: readwrite) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #9 = { mustprogress nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #10 = { mustprogress nounwind willreturn memory(argmem: readwrite) } +attributes #11 = { mustprogress nofree nounwind willreturn memory(inaccessiblemem: read) } +attributes #12 = { mustprogress nofree nounwind willreturn memory(argmem: read) } +attributes #13 = { convergent mustprogress nofree nounwind willreturn memory(argmem: read) } +attributes #14 = { nounwind willreturn memory(none) } +attributes #15 = { nounwind willreturn memory(argmem: readwrite) } +attributes #16 = { nounwind willreturn memory(inaccessiblemem: read) } +attributes #17 = { nounwind willreturn memory(argmem: read) } +attributes #18 = { convergent nounwind willreturn memory(argmem: read) } + +!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} +!air.vertex = !{!9, !14} +!air.fragment = !{!15, !21, !25} +!air.kernel = !{!31, !36, !39, !43, !49} +!air.compile_options = !{!52, !53, !54} +!llvm.ident = !{!55} +!air.version = !{!56} +!air.language_version = !{!57} + +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 27, i32 0]} +!1 = !{i32 1, !"wchar_size", i32 4} +!2 = !{i32 7, !"frame-pointer", i32 2} +!3 = !{i32 7, !"air.max_device_buffers", i32 31} +!4 = !{i32 7, !"air.max_constant_buffers", i32 31} +!5 = !{i32 7, !"air.max_threadgroup_buffers", i32 31} +!6 = !{i32 7, !"air.max_textures", i32 128} +!7 = !{i32 7, !"air.max_read_write_textures", i32 8} +!8 = !{i32 7, !"air.max_samplers", i32 16} +!9 = !{ptr @a8r_vertex, !10, !12} +!10 = !{!11} +!11 = !{!"air.position", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"} +!12 = !{!13} +!13 = !{i32 0, !"air.vertex_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"id"} +!14 = !{ptr @a8r_half_vertex, !10, !12} +!15 = !{ptr @a8r_fill, !16, !18} +!16 = !{!17} +!17 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"} +!18 = !{!19, !20} +!19 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position", !"air.arg_unused"} +!20 = !{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"color"} +!21 = !{ptr @a8r_dual, !22, !18} +!22 = !{!23, !24} +!23 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4", !"air.arg_name", !"first"} +!24 = !{!"air.render_target", i32 0, i32 1, !"air.arg_type_name", !"float4", !"air.arg_name", !"second"} +!25 = !{ptr @a8r_fetch, !16, !26} +!26 = !{!27, !28, !29, !30} +!27 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"} +!28 = !{i32 1, !"air.render_target", i32 0, !"air.arg_type_name", !"float4", !"air.arg_name", !"held"} +!29 = !{i32 2, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"color"} +!30 = !{i32 3, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"} +!31 = !{ptr @a8r_write, !32, !33} +!32 = !{} +!33 = !{!34, !20, !35} +!34 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} +!35 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"g"} +!36 = !{ptr @a8r_write_half, !32, !37} +!37 = !{!38, !20, !35} +!38 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} +!39 = !{ptr @a8r_read, !32, !40} +!40 = !{!41, !42, !35} +!41 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} +!42 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"} +!43 = !{ptr @a8r_sample, !32, !44} +!44 = !{!45, !46, !47, !48} +!45 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} +!46 = !{i32 1, !"air.sampler", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"sampler", !"air.arg_name", !"s"} +!47 = !{i32 2, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"} +!48 = !{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"g"} +!49 = !{ptr @a8r_read_write, !32, !50} +!50 = !{!51, !20, !47, !48} +!51 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} +!52 = !{!"air.compile.denorms_disable"} +!53 = !{!"air.compile.fast_math_enable"} +!54 = !{!"air.compile.framebuffer_fetch_enable"} +!55 = !{!"Apple metal version 32023.921 (metalfe-32023.921.6)"} +!56 = !{i32 2, i32 8, i32 0} +!57 = !{!"Metal", i32 4, i32 0, i32 0} +!58 = !{!59, !59, i64 0} +!59 = !{!"omnipotent char", !60, i64 0} +!60 = !{!"Simple C++ TBAA"} +!61 = !{!62} +!62 = distinct !{!62, !63, !"air-alias-scope-arg(1)"} +!63 = distinct !{!63, !"air-alias-scopes(a8r_fill)"} +!64 = !{!65} +!65 = distinct !{!65, !66, !"air-alias-scope-arg(1)"} +!66 = distinct !{!66, !"air-alias-scopes(a8r_dual)"} +!67 = !{!68} +!68 = distinct !{!68, !69, !"air-alias-scope-arg(3)"} +!69 = distinct !{!69, !"air-alias-scopes(a8r_fetch)"} +!70 = !{!71} +!71 = distinct !{!71, !69, !"air-alias-scope-arg(2)"} +!72 = !{!73} +!73 = distinct !{!73, !74, !"air-alias-scope-arg(1)"} +!74 = distinct !{!74, !"air-alias-scopes(a8r_write)"} +!75 = !{!76} +!76 = distinct !{!76, !74, !"air-alias-scope-textures"} +!77 = !{!78} +!78 = distinct !{!78, !79, !"air-alias-scope-arg(1)"} +!79 = distinct !{!79, !"air-alias-scopes(a8r_write_half)"} +!80 = !{!81} +!81 = distinct !{!81, !79, !"air-alias-scope-textures"} +!82 = !{!83} +!83 = distinct !{!83, !84, !"air-alias-scope-arg(1)"} +!84 = distinct !{!84, !"air-alias-scopes(a8r_read)"} +!85 = !{!86} +!86 = distinct !{!86, !84, !"air-alias-scope-textures"} +!87 = !{!88, !90} +!88 = distinct !{!88, !89, !"air-alias-scope-textures"} +!89 = distinct !{!89, !"air-alias-scopes(a8r_sample)"} +!90 = distinct !{!90, !89, !"air-alias-scope-samplers"} +!91 = !{!92} +!92 = distinct !{!92, !89, !"air-alias-scope-arg(2)"} +!93 = !{!94} +!94 = distinct !{!94, !95, !"air-alias-scope-arg(2)"} +!95 = distinct !{!95, !"air-alias-scopes(a8r_read_write)"} +!96 = !{!97, !98} +!97 = distinct !{!97, !95, !"air-alias-scope-textures"} +!98 = distinct !{!98, !95, !"air-alias-scope-arg(1)"} +!99 = !{!98} +!100 = !{!97, !94} +!101 = !{!97} +!102 = !{!98, !94} diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/a8r_targets.metal b/crates/metal2vulkan-validation/fixtures/public/engine/a8r_targets.metal new file mode 100644 index 000000000..bff364650 --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/engine/a8r_targets.metal @@ -0,0 +1,76 @@ +// The functions of the `A8Unorm` lane (validation/src/runtime_lane/alpha_in_red.rs), our own MSL: +// a fullscreen triangle and one over the lower left half of the target, fragments writing the +// color in buffer 0 (and the second color as a second output), one also reading its attachment, +// and kernels that write, read, sample and read-and-write an 8 x 8 texture at every texel. +#include +using namespace metal; + +struct Position { + float4 position [[position]]; +}; + +vertex Position a8r_vertex(uint id [[vertex_id]]) { + float2 p = float2((id << 1) & 2, id & 2); + Position out; + out.position = float4(p * 2.0 - 1.0, 0.0, 1.0); + return out; +} + +// Its edge runs through the target's texel centers on the diagonal from the top left. +vertex Position a8r_half_vertex(uint id [[vertex_id]]) { + float2 p = float2(id == 1 ? 1.0 : -1.0, id == 2 ? 1.0 : -1.0); + Position out; + out.position = float4(p, 0.0, 1.0); + return out; +} + +fragment float4 a8r_fill(Position in [[stage_in]], constant float4 *color [[buffer(0)]]) { + return color[0]; +} + +struct Dual { + float4 first [[color(0), index(0)]]; + float4 second [[color(0), index(1)]]; +}; + +fragment Dual a8r_dual(Position in [[stage_in]], constant float4 *color [[buffer(0)]]) { + Dual out; + out.first = color[0]; + out.second = color[1]; + return out; +} + +fragment float4 a8r_fetch(Position in [[stage_in]], float4 held [[color(0)]], + constant float4 *color [[buffer(0)]], device float4 *out [[buffer(1)]]) { + uint2 p = uint2(in.position.xy); + out[p.y * 8 + p.x] = held; + return color[0]; +} + +kernel void a8r_write(texture2d t [[texture(0)]], + constant float4 *color [[buffer(0)]], uint2 g [[thread_position_in_grid]]) { + t.write(color[0], g); +} + +kernel void a8r_write_half(texture2d t [[texture(0)]], + constant float4 *color [[buffer(0)]], + uint2 g [[thread_position_in_grid]]) { + t.write(half4(color[0]), g); +} + +kernel void a8r_read(texture2d t [[texture(0)]], + device float4 *out [[buffer(1)]], uint2 g [[thread_position_in_grid]]) { + out[g.y * 8 + g.x] = t.read(g); +} + +kernel void a8r_sample(texture2d t [[texture(0)]], sampler s [[sampler(0)]], + device float4 *out [[buffer(1)]], uint2 g [[thread_position_in_grid]]) { + out[g.y * 8 + g.x] = t.sample(s, (float2(g) + 0.5) / 8.0); +} + +kernel void a8r_read_write(texture2d t [[texture(0)]], + constant float4 *color [[buffer(0)]], device float4 *out [[buffer(1)]], + uint2 g [[thread_position_in_grid]]) { + out[g.y * 8 + g.x] = t.read(g); + t.write(color[0], g); +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index 171a668f8..3a8f3c3db 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -215,6 +215,8 @@ mod absent_reads; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod address_maps; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod alpha_in_red; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod amplified_draws; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod anisotropic_filter; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/alpha_in_red.rs b/crates/metal2vulkan-validation/src/runtime_lane/alpha_in_red.rs new file mode 100644 index 000000000..99ab5aeec --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/alpha_in_red.rs @@ -0,0 +1,1372 @@ +//! `A8Unorm` textures on a device that holds no `A8_UNORM` image, on the device the cfg selects, +//! under the validation layer. The device is made with `VK_KHR_maintenance5` and its feature +//! withheld, so at the runtime's Vulkan 1.2 instance it exposes no `A8_UNORM` (core only from +//! Vulkan 1.4), and an `A8Unorm` texture is an `R8_UNORM` image holding Metal's alpha in red +//! (`FormatEmulation::AlphaInRed`): a storage slot reads the byte as alpha and writes a texel's +//! alpha (`StorageImageClass::AlphaInRed`), and a color attachment takes the fragment's alpha in +//! red, the write mask's alpha bit, the clear's alpha and Metal's alpha blend there. +//! +//! Every byte is checked against Metal's, measured with our own probe `a8` on an Apple M3 Max +//! under macOS 27.0.1, 8 x 8 textures: a kernel's `float` and `half` writes of (0.2, 0.4, 0.6, +//! 0.8) store 204; a read, a sample and a `read_write` read of the byte 153 are (0, 0, 0, 0.6), and +//! that slot's write of (0.1, 0.3, 0.5, 0.7) stores 178; a render of (0.2, 0.4, 0.6, 0.8) and a +//! clear to it store 204, and of the write masks only the alpha bit writes; each of the 167 blend +//! states of [`BLENDS`] over the byte 102 stores its byte (an output of alpha 0.65, a second +//! output of alpha 0.45, a blend color of alpha 0.35, and color factors that would read other +//! values); a 4-sample render resolves as `R8Unorm`'s does (in the device's own `A8_UNORM` too, +//! where its resolve is Metal's rule). A blend is the device's blend unit's, +//! which rounds its own way (`PrecisionNote::DeviceColorConversion`): each is checked within a code +//! of Metal's, and exactly against the same blend into the device's own `A8_UNORM` texture where +//! the device has the format (a device made with the extension). A fetch of such an attachment +//! reads `(0, 0, 0, a)`, at one sample and at four (through sample planes where the device reads +//! them), and the write after it stores the alpha as the write mask lets it; alpha-to-coverage +//! through it as attachment 0 covers as through +//! `RGBA8Unorm` (probe `a8`'s uses, the same M3 Max: a fetch of the byte 153 reads +//! `(0, 0, 0, 0.6)`, and at every alpha in 1/32 steps the masks and resolves of the two formats +//! are the same; a resolve here is held within a code where the device's average makes it). A +//! texture buffer's bytes are viewed as `R8_UNORM` there, and an argument buffer's storage texture +//! is converted by its handle's class: each reads the byte as alpha and writes a texel's alpha as +//! Metal's does (the same probe's texture buffers, swizzled ones among them, and argument buffers). + +use super::degrade_notices::resolve_kind; +use super::{buffer_with, read_buffer, validated_device_with, Messages, ScratchCache, WAIT}; +use crate::air_library::AirLibrary; +use crate::gpu::TEST_DEVICE; +use metal2vulkan::bind::SamplerDescriptor; +use metal2vulkan::device::{VkExtension, VkFeature}; +use metal2vulkan::error::{Feature, Needs}; +use metal2vulkan::metal::format::alpha_in_red; +use metal2vulkan::metal::{ + BlendFactor, BlendOperation, ColorWriteMask, PixelFormat, PrimitiveType, ResourceUsage, + TextureSwizzle, TextureType, TextureUsage, +}; +use metal2vulkan::pipeline::{ + ColorAttachmentDescriptor, ComputePipelineDescriptor, RenderPipelineDescriptor, StageSource, +}; +use metal2vulkan_devtools::{engine_dir, llvm_assemble}; +use metal2vulkan_runtime::{ + Buffer, ClearColor, CommandBufferStatus, CommandQueue, Degradation, Device, Error, Library, + LoadAction, PipelineOptions, Region, RenderPassDescriptor, ResourceOptions, Size, StoreAction, + Texture, TextureDescriptor, TextureSwizzleChannels, +}; + +/// The textures' side. +const SIDE: u64 = 8; +const TEXELS: usize = (SIDE * SIDE) as usize; + +/// The color the writes, renders and clears take. +const COLOR: [f32; 4] = [0.2, 0.4, 0.6, 0.8]; +/// The byte Metal stores of [`COLOR`]'s alpha. +const STORED: u8 = 204; + +/// One blend state of the probe: Metal's alpha operation and source and destination alpha factors, +/// and the byte Metal stored over 102. +type Blend = (BlendOperation, BlendFactor, BlendFactor, u8); + +/// The probe's blends (the module docs): each alpha factor against `One`, and itself on both +/// sides, under `Add`, `Subtract` and `ReverseSubtract`, and `Min` and `Max`. +const BLENDS: [Blend; 167] = { + use BlendFactor as F; + use BlendOperation as O; + [ + (O::Add, F::Zero, F::Zero, 0), + (O::Add, F::Zero, F::One, 102), + (O::Add, F::One, F::Zero, 166), + (O::Add, F::One, F::One, 255), + (O::Add, F::One, F::SourceColor, 232), + (O::Add, F::One, F::OneMinusSourceColor, 201), + (O::Add, F::One, F::SourceAlpha, 232), + (O::Add, F::One, F::OneMinusSourceAlpha, 201), + (O::Add, F::One, F::DestinationColor, 207), + (O::Add, F::One, F::OneMinusDestinationColor, 227), + (O::Add, F::One, F::DestinationAlpha, 207), + (O::Add, F::One, F::OneMinusDestinationAlpha, 227), + (O::Add, F::One, F::SourceAlphaSaturated, 255), + (O::Add, F::One, F::BlendColor, 201), + (O::Add, F::One, F::OneMinusBlendColor, 232), + (O::Add, F::One, F::BlendAlpha, 201), + (O::Add, F::One, F::OneMinusBlendAlpha, 232), + (O::Add, F::One, F::Source1Color, 212), + (O::Add, F::One, F::OneMinusSource1Color, 222), + (O::Add, F::One, F::Source1Alpha, 212), + (O::Add, F::One, F::OneMinusSource1Alpha, 222), + (O::Add, F::SourceColor, F::One, 210), + (O::Add, F::SourceColor, F::SourceColor, 174), + (O::Add, F::OneMinusSourceColor, F::One, 160), + (O::Add, F::OneMinusSourceColor, F::OneMinusSourceColor, 94), + (O::Add, F::SourceAlpha, F::One, 210), + (O::Add, F::SourceAlpha, F::SourceAlpha, 174), + (O::Add, F::OneMinusSourceAlpha, F::One, 160), + (O::Add, F::OneMinusSourceAlpha, F::OneMinusSourceAlpha, 94), + (O::Add, F::DestinationColor, F::One, 168), + (O::Add, F::DestinationColor, F::DestinationColor, 107), + (O::Add, F::OneMinusDestinationColor, F::One, 201), + ( + O::Add, + F::OneMinusDestinationColor, + F::OneMinusDestinationColor, + 161, + ), + (O::Add, F::DestinationAlpha, F::One, 168), + (O::Add, F::DestinationAlpha, F::DestinationAlpha, 107), + (O::Add, F::OneMinusDestinationAlpha, F::One, 201), + ( + O::Add, + F::OneMinusDestinationAlpha, + F::OneMinusDestinationAlpha, + 161, + ), + (O::Add, F::SourceAlphaSaturated, F::One, 255), + ( + O::Add, + F::SourceAlphaSaturated, + F::SourceAlphaSaturated, + 255, + ), + (O::Add, F::BlendColor, F::One, 160), + (O::Add, F::BlendColor, F::BlendColor, 94), + (O::Add, F::OneMinusBlendColor, F::One, 210), + (O::Add, F::OneMinusBlendColor, F::OneMinusBlendColor, 174), + (O::Add, F::BlendAlpha, F::One, 160), + (O::Add, F::BlendAlpha, F::BlendAlpha, 94), + (O::Add, F::OneMinusBlendAlpha, F::One, 210), + (O::Add, F::OneMinusBlendAlpha, F::OneMinusBlendAlpha, 174), + (O::Add, F::Source1Color, F::One, 177), + (O::Add, F::Source1Color, F::Source1Color, 120), + (O::Add, F::OneMinusSource1Color, F::One, 193), + ( + O::Add, + F::OneMinusSource1Color, + F::OneMinusSource1Color, + 147, + ), + (O::Add, F::Source1Alpha, F::One, 177), + (O::Add, F::Source1Alpha, F::Source1Alpha, 120), + (O::Add, F::OneMinusSource1Alpha, F::One, 193), + ( + O::Add, + F::OneMinusSource1Alpha, + F::OneMinusSource1Alpha, + 147, + ), + (O::Subtract, F::Zero, F::Zero, 0), + (O::Subtract, F::Zero, F::One, 0), + (O::Subtract, F::One, F::Zero, 166), + (O::Subtract, F::One, F::One, 64), + (O::Subtract, F::One, F::SourceColor, 99), + (O::Subtract, F::One, F::OneMinusSourceColor, 130), + (O::Subtract, F::One, F::SourceAlpha, 99), + (O::Subtract, F::One, F::OneMinusSourceAlpha, 130), + (O::Subtract, F::One, F::DestinationColor, 125), + (O::Subtract, F::One, F::OneMinusDestinationColor, 105), + (O::Subtract, F::One, F::DestinationAlpha, 125), + (O::Subtract, F::One, F::OneMinusDestinationAlpha, 105), + (O::Subtract, F::One, F::SourceAlphaSaturated, 64), + (O::Subtract, F::One, F::BlendColor, 130), + (O::Subtract, F::One, F::OneMinusBlendColor, 99), + (O::Subtract, F::One, F::BlendAlpha, 130), + (O::Subtract, F::One, F::OneMinusBlendAlpha, 99), + (O::Subtract, F::One, F::Source1Color, 120), + (O::Subtract, F::One, F::OneMinusSource1Color, 110), + (O::Subtract, F::One, F::Source1Alpha, 120), + (O::Subtract, F::One, F::OneMinusSource1Alpha, 110), + (O::Subtract, F::SourceColor, F::One, 6), + (O::Subtract, F::SourceColor, F::SourceColor, 41), + (O::Subtract, F::OneMinusSourceColor, F::One, 0), + ( + O::Subtract, + F::OneMinusSourceColor, + F::OneMinusSourceColor, + 22, + ), + (O::Subtract, F::SourceAlpha, F::One, 6), + (O::Subtract, F::SourceAlpha, F::SourceAlpha, 41), + (O::Subtract, F::OneMinusSourceAlpha, F::One, 0), + ( + O::Subtract, + F::OneMinusSourceAlpha, + F::OneMinusSourceAlpha, + 22, + ), + (O::Subtract, F::DestinationColor, F::One, 0), + (O::Subtract, F::DestinationColor, F::DestinationColor, 25), + (O::Subtract, F::OneMinusDestinationColor, F::One, 0), + ( + O::Subtract, + F::OneMinusDestinationColor, + F::OneMinusDestinationColor, + 38, + ), + (O::Subtract, F::DestinationAlpha, F::One, 0), + (O::Subtract, F::DestinationAlpha, F::DestinationAlpha, 25), + (O::Subtract, F::OneMinusDestinationAlpha, F::One, 0), + ( + O::Subtract, + F::OneMinusDestinationAlpha, + F::OneMinusDestinationAlpha, + 38, + ), + (O::Subtract, F::SourceAlphaSaturated, F::One, 64), + ( + O::Subtract, + F::SourceAlphaSaturated, + F::SourceAlphaSaturated, + 64, + ), + (O::Subtract, F::BlendColor, F::One, 0), + (O::Subtract, F::BlendColor, F::BlendColor, 22), + (O::Subtract, F::OneMinusBlendColor, F::One, 6), + ( + O::Subtract, + F::OneMinusBlendColor, + F::OneMinusBlendColor, + 41, + ), + (O::Subtract, F::BlendAlpha, F::One, 0), + (O::Subtract, F::BlendAlpha, F::BlendAlpha, 22), + (O::Subtract, F::OneMinusBlendAlpha, F::One, 6), + ( + O::Subtract, + F::OneMinusBlendAlpha, + F::OneMinusBlendAlpha, + 41, + ), + (O::Subtract, F::Source1Color, F::One, 0), + (O::Subtract, F::Source1Color, F::Source1Color, 29), + (O::Subtract, F::OneMinusSource1Color, F::One, 0), + ( + O::Subtract, + F::OneMinusSource1Color, + F::OneMinusSource1Color, + 35, + ), + (O::Subtract, F::Source1Alpha, F::One, 0), + (O::Subtract, F::Source1Alpha, F::Source1Alpha, 29), + (O::Subtract, F::OneMinusSource1Alpha, F::One, 0), + ( + O::Subtract, + F::OneMinusSource1Alpha, + F::OneMinusSource1Alpha, + 35, + ), + (O::ReverseSubtract, F::Zero, F::Zero, 0), + (O::ReverseSubtract, F::Zero, F::One, 102), + (O::ReverseSubtract, F::One, F::Zero, 0), + (O::ReverseSubtract, F::One, F::One, 0), + (O::ReverseSubtract, F::One, F::SourceColor, 0), + (O::ReverseSubtract, F::One, F::OneMinusSourceColor, 0), + (O::ReverseSubtract, F::One, F::SourceAlpha, 0), + (O::ReverseSubtract, F::One, F::OneMinusSourceAlpha, 0), + (O::ReverseSubtract, F::One, F::DestinationColor, 0), + (O::ReverseSubtract, F::One, F::OneMinusDestinationColor, 0), + (O::ReverseSubtract, F::One, F::DestinationAlpha, 0), + (O::ReverseSubtract, F::One, F::OneMinusDestinationAlpha, 0), + (O::ReverseSubtract, F::One, F::SourceAlphaSaturated, 0), + (O::ReverseSubtract, F::One, F::BlendColor, 0), + (O::ReverseSubtract, F::One, F::OneMinusBlendColor, 0), + (O::ReverseSubtract, F::One, F::BlendAlpha, 0), + (O::ReverseSubtract, F::One, F::OneMinusBlendAlpha, 0), + (O::ReverseSubtract, F::One, F::Source1Color, 0), + (O::ReverseSubtract, F::One, F::OneMinusSource1Color, 0), + (O::ReverseSubtract, F::One, F::Source1Alpha, 0), + (O::ReverseSubtract, F::One, F::OneMinusSource1Alpha, 0), + (O::ReverseSubtract, F::SourceColor, F::One, 0), + (O::ReverseSubtract, F::SourceColor, F::SourceColor, 0), + (O::ReverseSubtract, F::OneMinusSourceColor, F::One, 44), + ( + O::ReverseSubtract, + F::OneMinusSourceColor, + F::OneMinusSourceColor, + 0, + ), + (O::ReverseSubtract, F::SourceAlpha, F::One, 0), + (O::ReverseSubtract, F::SourceAlpha, F::SourceAlpha, 0), + (O::ReverseSubtract, F::OneMinusSourceAlpha, F::One, 44), + ( + O::ReverseSubtract, + F::OneMinusSourceAlpha, + F::OneMinusSourceAlpha, + 0, + ), + (O::ReverseSubtract, F::DestinationColor, F::One, 36), + ( + O::ReverseSubtract, + F::DestinationColor, + F::DestinationColor, + 0, + ), + (O::ReverseSubtract, F::OneMinusDestinationColor, F::One, 3), + ( + O::ReverseSubtract, + F::OneMinusDestinationColor, + F::OneMinusDestinationColor, + 0, + ), + (O::ReverseSubtract, F::DestinationAlpha, F::One, 36), + ( + O::ReverseSubtract, + F::DestinationAlpha, + F::DestinationAlpha, + 0, + ), + (O::ReverseSubtract, F::OneMinusDestinationAlpha, F::One, 3), + ( + O::ReverseSubtract, + F::OneMinusDestinationAlpha, + F::OneMinusDestinationAlpha, + 0, + ), + (O::ReverseSubtract, F::SourceAlphaSaturated, F::One, 0), + ( + O::ReverseSubtract, + F::SourceAlphaSaturated, + F::SourceAlphaSaturated, + 0, + ), + (O::ReverseSubtract, F::BlendColor, F::One, 44), + (O::ReverseSubtract, F::BlendColor, F::BlendColor, 0), + (O::ReverseSubtract, F::OneMinusBlendColor, F::One, 0), + ( + O::ReverseSubtract, + F::OneMinusBlendColor, + F::OneMinusBlendColor, + 0, + ), + (O::ReverseSubtract, F::BlendAlpha, F::One, 44), + (O::ReverseSubtract, F::BlendAlpha, F::BlendAlpha, 0), + (O::ReverseSubtract, F::OneMinusBlendAlpha, F::One, 0), + ( + O::ReverseSubtract, + F::OneMinusBlendAlpha, + F::OneMinusBlendAlpha, + 0, + ), + (O::ReverseSubtract, F::Source1Color, F::One, 27), + (O::ReverseSubtract, F::Source1Color, F::Source1Color, 0), + (O::ReverseSubtract, F::OneMinusSource1Color, F::One, 11), + ( + O::ReverseSubtract, + F::OneMinusSource1Color, + F::OneMinusSource1Color, + 0, + ), + (O::ReverseSubtract, F::Source1Alpha, F::One, 27), + (O::ReverseSubtract, F::Source1Alpha, F::Source1Alpha, 0), + (O::ReverseSubtract, F::OneMinusSource1Alpha, F::One, 11), + ( + O::ReverseSubtract, + F::OneMinusSource1Alpha, + F::OneMinusSource1Alpha, + 0, + ), + (O::Min, F::Zero, F::Zero, 102), + (O::Max, F::Zero, F::Zero, 166), + ] +}; + +/// The blend's source, its second output, and the blend color (the module docs). +const SOURCE: [f32; 8] = [0.2, 0.4, 0.6, 0.65, 0.9, 0.15, 0.25, 0.45]; +const BLEND_COLOR: [f32; 4] = [0.1, 0.3, 0.5, 0.35]; +/// The byte a blend's target holds before it. +const BELOW: u8 = 102; + +struct Lane { + device: Device, + queue: CommandQueue, + library: Library, + /// The owned fixture `a8r_buffers`: texture-buffer and argument-buffer kernels. + buffers: Library, +} + +impl Lane { + /// The lane's device, `VK_KHR_maintenance5` and its feature withheld where `withheld`, with the owned fixtures + /// `a8r_targets` and `a8r_buffers`. + fn new(messages: &Messages, cache: &ScratchCache, withheld: bool) -> Lane { + let device = validated_device_with(TEST_DEVICE, messages, cache.path(), |options| { + if withheld { + options + .withheld_extensions + .insert(VkExtension::KhrMaintenance5); + options.withheld_features.insert(VkFeature::Maintenance5); + } + }) + .unwrap(); + let bitcode = llvm_assemble(&engine_dir().join("a8r_targets.ll")).unwrap(); + let buffers = llvm_assemble(&engine_dir().join("a8r_buffers.ll")).unwrap(); + Lane { + queue: device.new_command_queue().unwrap(), + library: device.new_library_with_air(&bitcode).unwrap(), + buffers: device.new_library_with_air(&buffers).unwrap(), + device, + } + } + + /// Whether the device holds `A8Unorm` in red. + fn in_red(&self) -> bool { + alpha_in_red(PixelFormat::A8Unorm, self.device.compile_device().profile()) + } + + fn function(&self, name: &str) -> StageSource { + StageSource::Function( + self.library + .new_function_with_name(name) + .unwrap() + .function_descriptor(), + ) + } + + /// A shared texture of `pf`, `samples` deep, of `usage`, holding `fill` where single-sampled. + fn texture(&self, pf: PixelFormat, samples: u64, usage: TextureUsage, fill: u8) -> Texture { + let mut d = TextureDescriptor::texture_2d(pf, SIDE, SIDE, false); + d.usage = usage; + if samples > 1 { + d.texture_type = TextureType::Type2DMultisample; + d.sample_count = samples; + d.resource_options = ResourceOptions::private(); + } else { + d.resource_options = ResourceOptions::shared(); + } + let t = self + .device + .new_texture(&d) + .unwrap_or_else(|e| panic!("a {pf:?} texture: {e}")); + if samples == 1 { + let bytes = vec![fill; TEXELS]; + t.replace_region(Region::new_2d(0, 0, SIDE, SIDE), 0, 0, &bytes, SIDE, 0) + .unwrap(); + } + t + } + + fn bytes(&self, t: &Texture) -> Vec { + self.wide_bytes(t, 1) + } + + /// The bytes of `t`, of `texel` bytes a texel. + fn wide_bytes(&self, t: &Texture, texel: u64) -> Vec { + let mut out = vec![0u8; TEXELS * texel as usize]; + t.get_bytes( + &mut out, + SIDE * texel, + 0, + Region::new_2d(0, 0, SIDE, SIDE), + 0, + 0, + ) + .unwrap(); + out + } + + /// A texture of `pf`, `samples` deep, of `usage`, its texels as made (a pass clears it). + fn bare(&self, pf: PixelFormat, samples: u64, usage: TextureUsage) -> Texture { + let mut d = TextureDescriptor::texture_2d(pf, SIDE, SIDE, false); + d.usage = usage; + if samples > 1 { + d.texture_type = TextureType::Type2DMultisample; + d.sample_count = samples; + d.resource_options = ResourceOptions::private(); + } else { + d.resource_options = ResourceOptions::shared(); + } + self.device + .new_texture(&d) + .unwrap_or_else(|e| panic!("a {pf:?} texture: {e}")) + } + + /// `kernel` over every texel of `t`, with `color` at buffer 0, and buffer 1's `float4`s. + fn dispatch(&self, kernel: &str, t: &Texture, color: [f32; 4]) -> Vec<[f32; 4]> { + let state = self + .device + .new_compute_pipeline_state( + &ComputePipelineDescriptor::new(self.function(kernel)), + &PipelineOptions::default(), + ) + .unwrap_or_else(|e| panic!("{kernel}: {e}")); + let color: Vec = color.iter().flat_map(|v| v.to_le_bytes()).collect(); + let color = buffer_with(&self.device, &color).unwrap(); + let out = buffer_with(&self.device, &vec![0xee; 16 * TEXELS]).unwrap(); + let sampler = self + .device + .new_sampler_state(&SamplerDescriptor::new()) + .unwrap(); + let command_buffer = self.queue.command_buffer().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(&state).unwrap(); + encoder.set_buffer(Some(&color), 0, 0).unwrap(); + encoder.set_buffer(Some(&out), 0, 1).unwrap(); + encoder.set_texture(Some(t), 0).unwrap(); + encoder.set_sampler_state(Some(&sampler), 0).unwrap(); + encoder + .dispatch_threads(Size::new(SIDE, SIDE, 1), Size::new(SIDE, SIDE, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + let bytes = read_buffer(&out, 0, 16 * TEXELS as u64).unwrap(); + bytes + .chunks(16) + .map(|t| { + std::array::from_fn(|i| f32::from_le_bytes(t[4 * i..4 * i + 4].try_into().unwrap())) + }) + .collect() + } + + /// A pipeline of `vertex` and `fragment` into `color`, at `samples`, with alpha-to-coverage + /// where `coverage`; the runtime's refusal where it refuses it. + fn pipeline( + &self, + (vertex, fragment): (&str, &str), + color: ColorAttachmentDescriptor, + samples: u32, + coverage: bool, + ) -> Result { + let mut d = RenderPipelineDescriptor::new(self.function(vertex)); + d.fragment = Some(self.function(fragment)); + d.color_attachments[0] = Some(color); + d.raster_sample_count = samples; + d.alpha_to_coverage = coverage; + self.device + .new_render_pipeline_state(&d, &PipelineOptions::default()) + } + + /// A pass into `target` (resolved into `resolve`), loaded or cleared to `clear`, drawing + /// `values` through `pipeline` where one is given. + fn pass( + &self, + target: &Texture, + resolve: Option<&Texture>, + clear: Option<[f64; 4]>, + draw: Option<(&metal2vulkan_runtime::RenderPipelineState, &[f32])>, + ) { + let mut pass = RenderPassDescriptor::new(); + let a = &mut pass.color_attachments[0]; + a.texture = Some(target.clone()); + match clear { + Some([r, g, b, alpha]) => { + a.load_action = LoadAction::Clear; + a.clear_color = ClearColor::new(r, g, b, alpha); + } + None => a.load_action = LoadAction::Load, + } + match resolve { + Some(r) => { + a.resolve_texture = Some(r.clone()); + a.store_action = StoreAction::MultisampleResolve; + } + None => a.store_action = StoreAction::Store, + } + let held = draw.map(|(_, values)| { + let bytes: Vec = values.iter().flat_map(|v| v.to_le_bytes()).collect(); + buffer_with(&self.device, &bytes).unwrap() + }); + let command_buffer = self.queue.command_buffer().unwrap(); + let mut e = command_buffer.render_command_encoder(&pass).unwrap(); + if let (Some((pipeline, _)), Some(values)) = (draw, &held) { + e.set_render_pipeline_state(pipeline).unwrap(); + let [r, g, b, alpha] = BLEND_COLOR; + e.set_blend_color(r, g, b, alpha); + e.set_fragment_buffer(Some(values), 0, 0).unwrap(); + e.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0) + .unwrap(); + } + e.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + } + + /// A pass into `target` (resolved into `resolve`), loaded or cleared to `clear`, drawing + /// [`COLOR`] through `pipeline`, a function that reads its attachment and writes what it read + /// at each texel to buffer 1 (`a8r_fetch`): those reads; the draw's refusal where the runtime + /// refuses it. + fn fetch_pass( + &self, + target: &Texture, + resolve: Option<&Texture>, + clear: Option<[f64; 4]>, + pipeline: &metal2vulkan_runtime::RenderPipelineState, + ) -> Result, Error> { + let mut pass = RenderPassDescriptor::new(); + let a = &mut pass.color_attachments[0]; + a.texture = Some(target.clone()); + match clear { + Some([r, g, b, alpha]) => { + a.load_action = LoadAction::Clear; + a.clear_color = ClearColor::new(r, g, b, alpha); + } + None => a.load_action = LoadAction::Load, + } + match resolve { + Some(r) => { + a.resolve_texture = Some(r.clone()); + a.store_action = StoreAction::MultisampleResolve; + } + None => a.store_action = StoreAction::Store, + } + let color: Vec = COLOR.iter().flat_map(|v| v.to_le_bytes()).collect(); + let color = buffer_with(&self.device, &color).unwrap(); + let out = buffer_with(&self.device, &vec![0xee; 16 * TEXELS]).unwrap(); + let command_buffer = self.queue.command_buffer().unwrap(); + let mut e = command_buffer.render_command_encoder(&pass).unwrap(); + e.set_render_pipeline_state(pipeline).unwrap(); + e.set_fragment_buffer(Some(&color), 0, 0).unwrap(); + e.set_fragment_buffer(Some(&out), 0, 1).unwrap(); + let drawn = e.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0); + e.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + drawn?; + let bytes = read_buffer(&out, 0, 16 * TEXELS as u64).unwrap(); + Ok(bytes + .chunks(16) + .map(|t| { + std::array::from_fn(|i| f32::from_le_bytes(t[4 * i..4 * i + 4].try_into().unwrap())) + }) + .collect()) + } + + /// Whether the device's fetch of a multisampled attachment reads its sample planes: the pixel + /// interlock (no rasterization-order color attachment access, with which a fetch reads input + /// attachments) on a device without multisampled storage images (`sample_planes.rs`). + fn reads_planes(&self) -> bool { + let profile = self.device.compile_device().profile(); + !profile.fragment().rasterization_order_color_access + && !profile.images().storage_multisample + } + + /// `kernel` of `a8r_buffers` over a `grid` of [`TEXELS`] threads (one row for a texture buffer, + /// [`SIDE`] rows for the argument buffer's textures), with `colors` at buffer 0, the texture buffer + /// `t` at texture 0 where one is given, `held` at buffer 2 where given, with the textures it + /// names resident: buffer 1's `float4`s. + fn buffer_dispatch( + &self, + kernel: &str, + grid: [u64; 2], + colors: &[[f32; 4]], + t: Option<&Texture>, + held: Option<(&Buffer, &[&Texture])>, + ) -> Vec<[f32; 4]> { + let function = self + .buffers + .new_function_with_name(kernel) + .unwrap() + .function_descriptor(); + let state = self + .device + .new_compute_pipeline_state( + &ComputePipelineDescriptor::new(StageSource::Function(function)), + &PipelineOptions::default(), + ) + .unwrap_or_else(|e| panic!("{kernel}: {e}")); + let colors: Vec = colors + .iter() + .flatten() + .flat_map(|v| v.to_le_bytes()) + .collect(); + let colors = buffer_with(&self.device, &colors).unwrap(); + let out = buffer_with(&self.device, &vec![0xee; 16 * TEXELS]).unwrap(); + let command_buffer = self.queue.command_buffer().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(&state).unwrap(); + encoder.set_buffer(Some(&colors), 0, 0).unwrap(); + encoder.set_buffer(Some(&out), 0, 1).unwrap(); + if let Some(t) = t { + encoder.set_texture(Some(t), 0).unwrap(); + } + if let Some((held, textures)) = held { + encoder.set_buffer(Some(held), 0, 2).unwrap(); + for t in textures { + let usage = ResourceUsage::READ | ResourceUsage::WRITE; + encoder.use_resource(t.as_resource(), usage).unwrap(); + } + } + let [x, y] = grid; + encoder + .dispatch_threads(Size::new(x, y, 1), Size::new(x, y, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + let bytes = read_buffer(&out, 0, 16 * TEXELS as u64).unwrap(); + bytes + .chunks(16) + .map(|t| { + std::array::from_fn(|i| f32::from_le_bytes(t[4 * i..4 * i + 4].try_into().unwrap())) + }) + .collect() + } + + /// A texture buffer of [`TEXELS`] `A8Unorm` texels of `usage`, made with `swizzle`, over a + /// shared buffer holding `bytes`, and the buffer. + fn texture_buffer( + &self, + usage: TextureUsage, + swizzle: TextureSwizzleChannels, + bytes: &[u8], + ) -> (Texture, Buffer) { + let buffer = buffer_with(&self.device, bytes).unwrap(); + let options = buffer.resource_options(); + let mut d = + TextureDescriptor::texture_buffer(PixelFormat::A8Unorm, TEXELS as u64, options, usage); + d.swizzle = swizzle; + let t = buffer + .new_texture(&d, 0, TEXELS as u64) + .unwrap_or_else(|e| panic!("an A8Unorm texture buffer: {e}")); + (t, buffer) + } + + /// The byte a draw of [`SOURCE`] stores over [`BELOW`] under `blend`; `None` where the device + /// refuses the pipeline as a need of its own (`dualSrcBlend`). + fn blended(&self, (op, src, dst, ..): Blend) -> Option { + let mut c = ColorAttachmentDescriptor::new(PixelFormat::A8Unorm); + c.blending_enabled = true; + c.source_rgb_blend_factor = BlendFactor::OneMinusDestinationColor; + c.destination_rgb_blend_factor = BlendFactor::SourceAlphaSaturated; + c.rgb_blend_operation = BlendOperation::Add; + c.source_alpha_blend_factor = src; + c.destination_alpha_blend_factor = dst; + c.alpha_blend_operation = op; + let dual = [src, dst].iter().any(|f| { + matches!( + f, + BlendFactor::Source1Color + | BlendFactor::OneMinusSource1Color + | BlendFactor::Source1Alpha + | BlendFactor::OneMinusSource1Alpha + ) + }); + let fragment = if dual { "a8r_dual" } else { "a8r_fill" }; + let pipeline = match self.pipeline(("a8r_vertex", fragment), c, 1, false) { + Ok(p) => p, + Err(Error::Unsupported(u)) if u.needs != Needs::NotImplemented => return None, + Err(e) => panic!("{op:?} {src:?} {dst:?}: {e}"), + }; + let target = self.texture(PixelFormat::A8Unorm, 1, TextureUsage::RENDER_TARGET, BELOW); + self.pass(&target, None, None, Some((&pipeline, &SOURCE))); + let bytes = self.bytes(&target); + assert!( + bytes.iter().all(|&b| b == bytes[0]), + "{op:?} {src:?} {dst:?}: {bytes:?}" + ); + Some(bytes[0]) + } +} + +/// Every texel of `got` is `want`, else the first that differs. +fn every(what: &str, got: &[u8], want: u8) { + if let Some(i) = got.iter().position(|&b| b != want) { + panic!("{what}: texel {i} holds {}, Metal's {want}", got[i]); + } +} + +/// A kernel's writes store the texel's alpha, and its reads, samples and `read_write` reads give +/// the byte as alpha, `(0, 0, 0, a)`, as Metal's do. +#[test] +fn a8_without_a8_unorm_writes_and_reads_alpha_as_metal() { + let messages = Messages::default(); + let cache = ScratchCache::new().unwrap(); + let lane = Lane::new(&messages, &cache, true); + assert!( + lane.in_red(), + "{}: A8Unorm is not held in red", + lane.device.name() + ); + let usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; + for kernel in ["a8r_write", "a8r_write_half"] { + let t = lane.texture(PixelFormat::A8Unorm, 1, usage, 0x11); + lane.dispatch(kernel, &t, COLOR); + every(kernel, &lane.bytes(&t), STORED); + } + let alpha = [0.0, 0.0, 0.0, 153.0 / 255.0]; + for kernel in ["a8r_read", "a8r_sample"] { + let t = lane.texture(PixelFormat::A8Unorm, 1, usage, 153); + let got = lane.dispatch(kernel, &t, COLOR); + assert!(got.iter().all(|&v| v == alpha), "{kernel}: {got:?}"); + } + let t = lane.texture(PixelFormat::A8Unorm, 1, usage, 153); + let got = lane.dispatch("a8r_read_write", &t, [0.1, 0.3, 0.5, 0.7]); + assert!(got.iter().all(|&v| v == alpha), "a8r_read_write: {got:?}"); + every("a8r_read_write", &lane.bytes(&t), 178); + drop(lane); + assert!(messages.take().is_empty(), "the validation layer reported"); +} + +/// A render stores the fragment's alpha, a clear the color's, only the alpha bit of a write mask +/// writes, and each blend of [`BLENDS`] stores Metal's byte (within a code), and the +/// device's own `A8_UNORM` texture's where it has the format. +#[test] +fn a8_without_a8_unorm_renders_masks_clears_and_blends_as_metal() { + let messages = Messages::default(); + let cache = ScratchCache::new().unwrap(); + let lane = Lane::new(&messages, &cache, true); + let name = lane.device.name().to_owned(); + assert!(lane.in_red(), "{name}: A8Unorm is not held in red"); + let usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + let unblended = |mask: ColorWriteMask| { + let mut c = ColorAttachmentDescriptor::new(PixelFormat::A8Unorm); + c.write_mask = mask; + lane.pipeline(("a8r_vertex", "a8r_fill"), c, 1, false) + .unwrap() + }; + let t = lane.texture(PixelFormat::A8Unorm, 1, usage, 0x11); + lane.pass( + &t, + None, + None, + Some((&unblended(ColorWriteMask::ALL), &COLOR)), + ); + every("a render", &lane.bytes(&t), STORED); + lane.pass(&t, None, Some(COLOR.map(f64::from)), None); + every("a clear", &lane.bytes(&t), STORED); + let rgb = ColorWriteMask::RED + .union(ColorWriteMask::GREEN) + .union(ColorWriteMask::BLUE); + for (mask, want) in [ + (rgb, 0x11), + (ColorWriteMask::ALPHA, STORED), + (ColorWriteMask::RED, 0x11), + (ColorWriteMask::empty(), 0x11), + ] { + let t = lane.texture(PixelFormat::A8Unorm, 1, usage, 0x11); + lane.pass(&t, None, None, Some((&unblended(mask), &COLOR))); + every(&format!("mask {mask:?}"), &lane.bytes(&t), want); + } + let mut got = Vec::new(); + let (mut wrong, mut refused, mut off_by_one) = (Vec::new(), 0, 0); + for blend in BLENDS { + let (op, src, dst, want) = blend; + let Some(byte) = lane.blended(blend) else { + refused += 1; + got.push(None); + continue; + }; + got.push(Some(byte)); + match byte.abs_diff(want) { + 0 => {} + 1 => off_by_one += 1, + _ => wrong.push(format!("{op:?} {src:?} {dst:?}: {byte}, Metal's {want}")), + } + } + drop(lane); + assert!(messages.take().is_empty(), "the validation layer reported"); + // The same blends into the device's own `A8_UNORM` texture, where it has the format. + let own = Lane::new(&messages, &cache, false); + let mut unlike = Vec::new(); + if !own.in_red() { + for (blend, held) in BLENDS.into_iter().zip(&got) { + let (op, src, dst, ..) = blend; + if let (Some(direct), Some(held)) = (own.blended(blend), held) { + if direct != *held { + unlike.push(format!( + "{op:?} {src:?} {dst:?}: {held}, A8_UNORM's {direct}" + )); + } + } + } + } + drop(own); + assert!(messages.take().is_empty(), "the validation layer reported"); + for line in wrong.iter().chain(&unlike) { + println!("A8-IN-RED-DIFFERS {name}: {line}"); + } + println!( + "A8-IN-RED {name}: {} blends checked, {refused} refused, {off_by_one} a code from \ + Metal's, {} further, {} differ from A8_UNORM's", + BLENDS.len() - refused, + wrong.len(), + unlike.len() + ); + assert!(wrong.is_empty() && unlike.is_empty()); + assert!(refused < BLENDS.len() / 4, "{refused} refused"); +} + +/// A 4-sample render over the lower left half of the target resolves as `R8Unorm`'s does, at the +/// edge too, and as Metal's away from it (229 below it, 0 above), where every texel's samples +/// agree: on the device without `A8_UNORM` (its `R8_UNORM` image's resolve), and with its own +/// where it has the format, whose resolve under the lanes' `ResolvePolicy::Exact` is Metal's 8-bit +/// unorm rule, as `R8Unorm`'s (probe `a8`: an `A8Unorm` resolve is `RGBA8Unorm`'s alpha; +/// `bind::ColorResolveFormat::of`), where the device's average is not Metal's already. +#[test] +fn a8_resolves_as_r8_unorm() { + let messages = Messages::default(); + let cache = ScratchCache::new().unwrap(); + for withheld in [true, false] { + let lane = Lane::new(&messages, &cache, withheld); + let name = lane.device.name().to_owned(); + if withheld { + assert!(lane.in_red(), "{name}: A8Unorm is not held in red"); + } else if lane.in_red() { + println!("A8-RESOLVE {name}: no A8_UNORM, its own format not checked"); + continue; + } + let form = if withheld { "R8_UNORM" } else { "A8_UNORM" }; + a8_resolve_leg(&lane, &format!("{name} {form}")); + drop(lane); + assert!(messages.take().is_empty(), "the validation layer reported"); + } +} + +/// One leg of [`a8_resolves_as_r8_unorm`] on `lane`, named `what`. +fn a8_resolve_leg(lane: &Lane, what: &str) { + let kinds = + [PixelFormat::A8Unorm, PixelFormat::R8Unorm].map(|pf| resolve_kind(&lane.device, pf, 4)); + assert_eq!(kinds[0], kinds[1], "{what}: the resolve's kind"); + let resolved = |pf: PixelFormat| { + let ms = lane.texture(pf, 4, TextureUsage::RENDER_TARGET, 0); + let one = lane.texture( + pf, + 1, + TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ, + 0, + ); + let pipeline = lane + .pipeline( + ("a8r_half_vertex", "a8r_fill"), + ColorAttachmentDescriptor::new(pf), + 4, + false, + ) + .unwrap(); + lane.pass( + &ms, + Some(&one), + Some([0.0; 4]), + Some((&pipeline, &[0.9; 4])), + ); + lane.bytes(&one) + }; + let a8 = resolved(PixelFormat::A8Unorm); + let r8 = resolved(PixelFormat::R8Unorm); + assert_eq!(a8, r8, "{what}: A8Unorm's resolve against R8Unorm's"); + for y in 0..SIDE as usize { + for x in 0..SIDE as usize { + let want = match x.cmp(&y) { + std::cmp::Ordering::Less => 229, + std::cmp::Ordering::Greater => 0, + std::cmp::Ordering::Equal => continue, + }; + assert_eq!( + a8[y * SIDE as usize + x], + want, + "{what}: texel ({x}, {y}): {a8:?}" + ); + } + } + println!("A8-RESOLVE {what}: as R8Unorm's ({:?})", kinds[0]); +} + +/// The fetches of the probe (`a8`'s uses): a read of the byte 153 through `[[color(0)]]`, every +/// texel `(0, 0, 0, 0.6)`, then a write of [`COLOR`] under each write mask, the byte left (only the +/// alpha bit writes); and at four samples, a target cleared to 0.6 read so at every sample and +/// resolved to the write's 204. +const FETCH_MASKS: [(ColorWriteMask, u8); 3] = [ + (ColorWriteMask::ALPHA, STORED), + ( + ColorWriteMask::RED + .union(ColorWriteMask::GREEN) + .union(ColorWriteMask::BLUE), + 153, + ), + (ColorWriteMask::empty(), 153), +]; + +/// A color input (`[[color(0)]]`) of an `A8Unorm` attachment reads Metal's alpha in `.a`, and the +/// function's write after it stores the alpha as the write mask lets it, at one sample and at four, +/// as Metal's do: on the device without `A8_UNORM` (its `R8_UNORM` image read through the input +/// attachment or the interlocked storage form, whichever the device orders fetch with), and with +/// its own `A8_UNORM` where it has the format. +#[test] +fn a8_color_input_reads_alpha_as_metal() { + let messages = Messages::default(); + let cache = ScratchCache::new().unwrap(); + for withheld in [true, false] { + let lane = Lane::new(&messages, &cache, withheld); + let name = lane.device.name().to_owned(); + if withheld { + assert!(lane.in_red(), "{name}: A8Unorm is not held in red"); + } else if lane.in_red() { + println!("A8-FETCH {name}: no A8_UNORM, its own format not checked"); + continue; + } + let form = if withheld { "R8_UNORM" } else { "A8_UNORM" }; + let alpha = [0.0, 0.0, 0.0, 153.0 / 255.0]; + let usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + for (mask, want) in FETCH_MASKS { + let mut c = ColorAttachmentDescriptor::new(PixelFormat::A8Unorm); + c.write_mask = mask; + let pipeline = lane + .pipeline(("a8r_vertex", "a8r_fetch"), c, 1, false) + .unwrap_or_else(|e| panic!("{name} {form}: a fetch under {mask:?}: {e}")); + let t = lane.texture(PixelFormat::A8Unorm, 1, usage, 153); + let read = lane + .fetch_pass(&t, None, None, &pipeline) + .unwrap_or_else(|e| panic!("{name} {form}: a fetch under {mask:?}: {e}")); + assert!( + read.iter().all(|&v| v == alpha), + "{name} {form}: the fetch under {mask:?} read {read:?}" + ); + every( + &format!("{name} {form}: the write under {mask:?}"), + &lane.bytes(&t), + want, + ); + } + let pipeline = lane + .pipeline( + ("a8r_vertex", "a8r_fetch"), + ColorAttachmentDescriptor::new(PixelFormat::A8Unorm), + 4, + false, + ) + .unwrap_or_else(|e| panic!("{name} {form}: a fetch at four samples: {e}")); + let ms = lane.texture(PixelFormat::A8Unorm, 4, TextureUsage::RENDER_TARGET, 0); + let one = lane.texture(PixelFormat::A8Unorm, 1, usage, 0); + // Through sample planes where the device reads them, `A8_UNORM`'s held in its own format + // (`bind::PlanesCopy::Alpha8`), as its bits copy holds an `R8_UNORM` image's. + let planes = if lane.reads_planes() { + "through sample planes" + } else { + "directly" + }; + let ran = lane.fetch_pass(&ms, Some(&one), Some([0.6; 4]), &pipeline); + let read = + ran.unwrap_or_else(|e| panic!("{name} {form}: a fetch at four samples, {planes}: {e}")); + assert!( + read.iter().all(|&v| v == alpha), + "{name} {form}: the fetch at four samples read {read:?}" + ); + every( + &format!("{name} {form}: the resolve"), + &lane.bytes(&one), + STORED, + ); + println!("A8-FETCH {name} {form}: as Metal's, at four samples {planes}"); + drop(lane); + assert!(messages.take().is_empty(), "the validation layer reported"); + } +} + +/// [`a8_color_input_reads_alpha_as_metal`]'s four-sample fetch through sample planes on the device +/// made as Intel's ANV is for this (without `rasterizationOrderColorAttachmentAccess`, +/// `shaderStorageImageMultisample` and `shaderStorageImageReadWithoutFormat`), with its own +/// `A8_UNORM`: the fetch reads the planes in the pixel interlock, declared without a format by the +/// format's own bit, and the planes are held in `A8_UNORM` itself (`bind::PlanesCopy::Alpha8`), as +/// no unsigned view reads its class. A target cleared to 0.6 reads `(0, 0, 0, 0.6)` at every +/// sample, and the write of [`COLOR`] after it resolves to 204, as Metal's (probe `a8`'s uses). +#[test] +fn a8_color_input_through_sample_planes_reads_alpha_as_metal() { + let messages = Messages::default(); + let cache = ScratchCache::new().unwrap(); + let withheld = [ + VkFeature::RasterizationOrderColorAttachmentAccess, + VkFeature::ShaderStorageImageMultisample, + VkFeature::ShaderStorageImageReadWithoutFormat, + ]; + let lane = Lane::withholding(&messages, &cache, false, &withheld); + let name = lane.device.name().to_owned(); + if lane.in_red() || !lane.reads_planes() { + println!( + "A8-PLANES {name}: no A8_UNORM, or no sample planes (in red {}, planes {})", + lane.in_red(), + lane.reads_planes() + ); + drop(lane); + assert!(messages.take().is_empty(), "the validation layer reported"); + return; + } + let pipeline = lane + .pipeline( + ("a8r_vertex", "a8r_fetch"), + ColorAttachmentDescriptor::new(PixelFormat::A8Unorm), + 4, + false, + ) + .unwrap_or_else(|e| panic!("{name}: a fetch at four samples: {e}")); + let usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + let ms = lane.texture(PixelFormat::A8Unorm, 4, TextureUsage::RENDER_TARGET, 0); + let one = lane.texture(PixelFormat::A8Unorm, 1, usage, 0); + let read = lane + .fetch_pass(&ms, Some(&one), Some([0.6; 4]), &pipeline) + .unwrap_or_else(|e| panic!("{name}: a fetch at four samples through sample planes: {e}")); + let alpha = [0.0, 0.0, 0.0, 153.0 / 255.0]; + assert!( + read.iter().all(|&v| v == alpha), + "{name}: the fetch through sample planes read {read:?}" + ); + every(&format!("{name}: the resolve"), &lane.bytes(&one), STORED); + println!("A8-PLANES {name}: as Metal's, through A8_UNORM sample planes"); + drop(lane); + assert!(messages.take().is_empty(), "the validation layer reported"); +} + +/// Alpha-to-coverage through an `A8Unorm` attachment 0 at four samples covers by the output's +/// alpha as through an `RGBA8Unorm` one, as Metal's does (probe `a8`'s uses: at every alpha in +/// 1/32 steps, the masks and the resolved bytes of the two are the same, every texel 0 at alpha 0 +/// and 255 at alpha 1): the output (0.9, 0.1, 0.5, a), whose blue differs from its alpha, over a +/// target cleared to 0, resolved, against the resolved alpha of the same draw into `RGBA8Unorm`, +/// on the device without `A8_UNORM` and with its own where it has the format. How the alpha +/// becomes a mask is the device's (Vulkan names no algorithm), so the bytes are held to +/// `RGBA8Unorm`'s on the same device: exactly where both resolve by Metal's rule, else within the +/// code the device's average may round a tie to (`device-rounded-resolve`), which still tells +/// every count of covered samples +/// apart (adjacent counts lie a quarter of the alpha's code apart, two codes or more past alpha 0). +#[test] +fn a8_alpha_to_coverage_covers_as_rgba8() { + let messages = Messages::default(); + let cache = ScratchCache::new().unwrap(); + for withheld in [true, false] { + let lane = Lane::new(&messages, &cache, withheld); + let name = lane.device.name().to_owned(); + if withheld { + assert!(lane.in_red(), "{name}: A8Unorm is not held in red"); + } else if lane.in_red() { + println!("A8-COVERAGE {name}: no A8_UNORM, its own format not checked"); + continue; + } + let form = if withheld { "R8_UNORM" } else { "A8_UNORM" }; + let resolved = |pf: PixelFormat, alpha: f32| { + let pipeline = lane + .pipeline( + ("a8r_vertex", "a8r_fill"), + ColorAttachmentDescriptor::new(pf), + 4, + true, + ) + .unwrap_or_else(|e| panic!("{name} {form}: {pf:?} under coverage: {e}")); + let ms = lane.bare(pf, 4, TextureUsage::RENDER_TARGET); + let one = lane.bare( + pf, + 1, + TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ, + ); + lane.pass( + &ms, + Some(&one), + Some([0.0; 4]), + Some((&pipeline, &[0.9, 0.1, 0.5, alpha])), + ); + one + }; + let rounded = [PixelFormat::A8Unorm, PixelFormat::RGBA8Unorm] + .into_iter() + .any(|pf| resolve_kind(&lane.device, pf, 4) == Some(Degradation::DeviceRoundedResolve)); + let codes = u8::from(rounded); + for step in 0..=32u8 { + let alpha = f32::from(step) / 32.0; + let a8 = lane.bytes(&resolved(PixelFormat::A8Unorm, alpha)); + let rgba = lane.wide_bytes(&resolved(PixelFormat::RGBA8Unorm, alpha), 4); + let rgba_alpha: Vec = rgba.chunks(4).map(|t| t[3]).collect(); + let apart = a8 + .iter() + .zip(&rgba_alpha) + .position(|(a, b)| a.abs_diff(*b) > codes); + assert_eq!( + apart, None, + "{name} {form}: alpha {step}/32, A8Unorm's resolve against RGBA8Unorm's alpha \ + (within {codes} codes): {a8:?} against {rgba_alpha:?}" + ); + match step { + 0 => every(&format!("{name} {form}: alpha 0"), &a8, 0), + 32 => every(&format!("{name} {form}: alpha 1"), &a8, 255), + _ => {} + } + } + println!("A8-COVERAGE {name} {form}: as RGBA8Unorm's at 33 alphas, within {codes} codes"); + drop(lane); + assert!(messages.take().is_empty(), "the validation layer reported"); + } +} + +/// A texture buffer's dispatch: one row of [`TEXELS`] threads. +const ROW: [u64; 2] = [TEXELS as u64, 1]; + +/// The bytes of a texture buffer's reads: 152 at the even texels, 0 at the odd ones. +fn buffer_bytes() -> Vec { + (0..TEXELS) + .map(|i| if i % 2 == 0 { 152 } else { 0 }) + .collect() +} + +/// An `A8Unorm` texture buffer reads its bytes as alpha, `(0, 0, 0, a)`, as `float` and as `half`, +/// through its swizzle where it was made with one, stores a written texel's alpha, and a +/// `read_write` one does both, as Metal's does (probe `a8`'s texture buffers, an M3 Max under +/// macOS 27.0.1: a read of the byte 152 is (0, 0, 0, 0.596078455), as `half` (0, 0, 0, 0.596191406), +/// of the byte 0 all zero; made with the swizzle (A, 0, 0, 1) the read is (0.596078455, 0, 0, 1), +/// with (A, A, R, G) (0.596078455, 0.596078455, 0, 0); a write of (0.2, 0.4, 0.6, 0.8) stores 204; +/// a `read_write` read of 152 is (0, 0, 0, 0.596078455) and its write of (0.1, 0.3, 0.5, 0.7) +/// stores 178. Metal's validation refuses a swizzle with `ShaderWrite`), through the bytes' +/// `R8_UNORM` view on the device without `A8_UNORM`, and through its own where it has the format. +#[test] +fn a8_texture_buffer_reads_and_writes_alpha_as_metal() { + use TextureSwizzle::{Alpha as A, Green as G, One as O, Red as R, Zero as Z}; + let messages = Messages::default(); + let cache = ScratchCache::new().unwrap(); + for withheld in [true, false] { + let lane = Lane::new(&messages, &cache, withheld); + let name = lane.device.name().to_owned(); + if withheld { + assert!(lane.in_red(), "{name}: A8Unorm is not held in red"); + } else if lane.in_red() { + println!("A8-BUFFER {name}: no A8_UNORM, its own format not checked"); + continue; + } + let form = if withheld { "R8_UNORM" } else { "A8_UNORM" }; + let a = 152.0 / 255.0; + // The half nearest 152 / 255. + let half = 1221.0 / 2048.0; + let reads = [ + ( + "a8r_buffer_read", + TextureSwizzleChannels::DEFAULT, + [0.0, 0.0, 0.0, a], + ), + ( + "a8r_buffer_read_half", + TextureSwizzleChannels::DEFAULT, + [0.0, 0.0, 0.0, half], + ), + ( + "a8r_buffer_read", + TextureSwizzleChannels::new(A, Z, Z, O), + [a, 0.0, 0.0, 1.0], + ), + ( + "a8r_buffer_read_half", + TextureSwizzleChannels::new(A, Z, Z, O), + [half, 0.0, 0.0, 1.0], + ), + ( + "a8r_buffer_read", + TextureSwizzleChannels::new(A, A, R, G), + [a, a, 0.0, 0.0], + ), + ]; + for (kernel, swizzle, want) in reads { + let (t, _bytes) = + lane.texture_buffer(TextureUsage::SHADER_READ, swizzle, &buffer_bytes()); + let got = lane.buffer_dispatch(kernel, ROW, &[COLOR], Some(&t), None); + for (i, v) in got.iter().enumerate() { + let want = match i % 2 { + 0 => want, + _ => want.map(|c| if c == 1.0 { 1.0 } else { 0.0 }), + }; + assert_eq!(*v, want, "{name} {form}: {kernel} {swizzle:?} at texel {i}"); + } + } + let usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; + let (t, bytes) = + lane.texture_buffer(usage, TextureSwizzleChannels::DEFAULT, &[0x11; TEXELS]); + lane.buffer_dispatch("a8r_buffer_write", ROW, &[COLOR], Some(&t), None); + let stored = read_buffer(&bytes, 0, TEXELS as u64).unwrap(); + every(&format!("{name} {form}: a8r_buffer_write"), &stored, STORED); + let (t, bytes) = + lane.texture_buffer(usage, TextureSwizzleChannels::DEFAULT, &[152; TEXELS]); + let got = lane.buffer_dispatch( + "a8r_buffer_read_write", + ROW, + &[[0.1, 0.3, 0.5, 0.7]], + Some(&t), + None, + ); + assert!( + got.iter().all(|&v| v == [0.0, 0.0, 0.0, a]), + "{name} {form}: a8r_buffer_read_write read {got:?}" + ); + let stored = read_buffer(&bytes, 0, TEXELS as u64).unwrap(); + every( + &format!("{name} {form}: a8r_buffer_read_write"), + &stored, + 178, + ); + println!("A8-BUFFER {name} {form}: as Metal's"); + drop(lane); + assert!(messages.take().is_empty(), "the validation layer reported"); + } +} + +/// The storage textures an argument buffer holds read an `A8Unorm` texture's byte as alpha, +/// `(0, 0, 0, a)`, and store a written texel's alpha, as Metal's do (probe `a8`'s argument buffers, +/// an M3 Max under macOS 27.0.1: a `read_write` member of the byte 153 reads (0, 0, 0, 0.6) and +/// its write of (0.8, 0.6, 0.4, 0.2) stores 51, and a `write` member's write of +/// (0.2, 0.4, 0.6, 0.8) stores 204), through the texture's `R8_UNORM` image on the device without +/// `A8_UNORM`, and its own where it has the format. A device without +/// `shaderStorageImageReadWithoutFormat` (ANV) refuses the kernel, `ArgumentBufferTextures`. +#[test] +fn a8_argument_buffer_storage_reads_and_writes_alpha_as_metal() { + let messages = Messages::default(); + let cache = ScratchCache::new().unwrap(); + for withheld in [true, false] { + let lane = Lane::new(&messages, &cache, withheld); + let name = lane.device.name().to_owned(); + if withheld { + assert!(lane.in_red(), "{name}: A8Unorm is not held in red"); + } else if lane.in_red() { + println!("A8-HELD {name}: no A8_UNORM, its own format not checked"); + continue; + } + let form = if withheld { "R8_UNORM" } else { "A8_UNORM" }; + // A heap's storage reads are declared without a format and need the device's feature + // (its formats' own bits do not serve a heap, docs/FAST-PATHS.md): refused without it. + let profile = lane.device.compile_device().profile(); + let feature = VkFeature::ShaderStorageImageReadWithoutFormat; + if !profile.enabled().features.contains(&feature) { + let function = lane + .buffers + .new_function_with_name("a8r_held") + .unwrap() + .function_descriptor(); + let made = lane.device.new_compute_pipeline_state( + &ComputePipelineDescriptor::new(StageSource::Function(function)), + &PipelineOptions::default(), + ); + let Err(Error::Unsupported(refused)) = made else { + panic!("{name} {form}: the argument buffer's kernel made without {feature:?}"); + }; + assert_eq!( + refused.feature, + Feature::ArgumentBufferTextures, + "{name} {form}: {refused}" + ); + println!("A8-HELD {name} {form}: refused without {feature:?}: {refused}"); + drop(lane); + assert!(messages.take().is_empty(), "the validation layer reported"); + continue; + } + let usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; + let rw = lane.texture(PixelFormat::A8Unorm, 1, usage, 153); + let w = lane.texture(PixelFormat::A8Unorm, 1, usage, 0x11); + let ids: Vec = [&rw, &w] + .iter() + .flat_map(|t| t.gpu_resource_id().0.to_le_bytes()) + .collect(); + let held = buffer_with(&lane.device, &ids).unwrap(); + let got = lane.buffer_dispatch( + "a8r_held", + [SIDE, SIDE], + &[[0.8, 0.6, 0.4, 0.2], COLOR], + None, + Some((&held, &[&rw, &w])), + ); + let alpha = [0.0, 0.0, 0.0, 153.0 / 255.0]; + assert!( + got.iter().all(|&v| v == alpha), + "{name} {form}: the read_write member read {got:?}" + ); + every( + &format!("{name} {form}: the read_write member"), + &lane.bytes(&rw), + 51, + ); + every( + &format!("{name} {form}: the write member"), + &lane.bytes(&w), + STORED, + ); + println!("A8-HELD {name} {form}: as Metal's"); + drop(lane); + assert!(messages.take().is_empty(), "the validation layer reported"); + } +} diff --git a/crates/metal2vulkan/src/bind/color_resolve.rs b/crates/metal2vulkan/src/bind/color_resolve.rs index 4b65e91a7..0d989ab9f 100644 --- a/crates/metal2vulkan/src/bind/color_resolve.rs +++ b/crates/metal2vulkan/src/bind/color_resolve.rs @@ -76,7 +76,9 @@ //! [`ResolveSource::InputAttachment`] does. //! - [`ResolveSource::Planes`]: the attachment's sample planes (`bind::PlanesCopy`), a sampled //! 2D-array view of every layer in the copy format, layer `s` holding sample `s`: each channel's -//! code is its bits in the texel `(FragCoord.xy, s)` (a half's, unpacked to its `float`). +//! code is its bits in the texel `(FragCoord.xy, s)` (a half's, unpacked to its `float`), or, +//! for planes held in `A8_UNORM` itself (`PlanesCopy::Alpha8`), its float's code as an input +//! attachment's is. //! //! Draw it into a render pass whose one color attachment is the resolve texture's single-sampled //! level and layer in [`ColorResolveFormat::written_format`] (its own format, or its raw twin @@ -230,8 +232,10 @@ impl ColorResolveFormat { /// its 8- and 16-bit snorm ones, its 8-bit sRGB ones, its 32-bit float ones, its packed 16-bit /// unorm ones (each Vulkan layout that holds one, its red and blue twin included), and its /// 16-bit float, `RG11B10Float` and `RGB9E5Float` ones, whose rules hold at 2 and 4 samples - /// ([`ColorResolveFormat::resolves`]), as Vulkan formats. `None` for another format (the - /// module docs). + /// ([`ColorResolveFormat::resolves`]), as Vulkan formats; `A8Unorm`'s alpha resolves by the + /// 8-bit unorm rule, as `R8Unorm`'s red (probe `a8`, an M3 Max under macOS 27.0.1: at every + /// alpha in 1/32 steps an `A8Unorm` resolve is `RGBA8Unorm`'s alpha). `None` for another format + /// (the module docs). pub fn of(format: Format) -> Option { use ResolveRule::{Float16 as F16, Float32 as F32, SharedExponent as E9, Srgb as S}; const H1: ResolveRule = ResolveRule::HalfUnorm { bits: 1 }; @@ -248,6 +252,7 @@ impl ColorResolveFormat { const U2: ResolveRule = ResolveRule::Unorm { bits: 2 }; let channels = match format { Format::R8_UNORM => [at(U8, 0), None, None, None], + Format::A8_UNORM => [None, None, None, at(U8, 0)], Format::R8G8_UNORM => [at(U8, 0), at(U8, 8), None, None], Format::R8G8B8A8_UNORM => [at(U8, 0), at(U8, 8), at(U8, 16), at(U8, 24)], Format::B8G8R8A8_UNORM => [at(U8, 16), at(U8, 8), at(U8, 0), at(U8, 24)], @@ -374,6 +379,15 @@ pub enum ResolveSource { Planes(PlanesCopy), } +impl ResolveSource { + /// Whether the source's texels are the attachment's bits, in an unsigned-integer copy format: + /// sample planes of a bits copy (`PlanesCopy::moves_bits`). Else they are the format's + /// `float`s. + fn reads_bits(self) -> bool { + matches!(self, ResolveSource::Planes(copy) if copy.moves_bits()) + } +} + /// The crate-owned resolve modules of one format, sample count and source on one device, /// validated like any output. #[non_exhaustive] @@ -723,7 +737,7 @@ fn code( source: ResolveSource, ) -> BResult { let bits = u32::from(channel.rule.bits()); - if let ResolveSource::Planes(_) = source { + if source.reads_bits() { let offset = u32::from(channel.offset); let word = f.composite_extract(texel, &[offset / 32])?; let shift = uint(f, t, offset % 32)?; @@ -1326,9 +1340,9 @@ fn alike( len: 4, })?; let words = |f: &mut FunctionBuilder<'_>, texel: Value| -> BResult { - match source { - ResolveSource::Planes(_) => Ok(texel), - ResolveSource::InputAttachment => f.convert(ConvOp::Bitcast, texel, uvec4), + match source.reads_bits() { + true => Ok(texel), + false => f.convert(ConvOp::Bitcast, texel, uvec4), } }; let (&first, rest) = texels @@ -1452,9 +1466,12 @@ pub fn fragment_typed_module( None, ) } - ResolveSource::Planes(_) => { + ResolveSource::Planes(copy) => { let ty = b.ty(Type::Image(ImageType { - sampled_type: t.u32_, + sampled_type: match copy.moves_bits() { + true => t.u32_, + false => t.f32_, + }, dim: Dim::D2, depth: false, arrayed: true, diff --git a/crates/metal2vulkan/src/bind/color_resolve/tests.rs b/crates/metal2vulkan/src/bind/color_resolve/tests.rs index 774b5f6fc..c05b5ca61 100644 --- a/crates/metal2vulkan/src/bind/color_resolve/tests.rs +++ b/crates/metal2vulkan/src/bind/color_resolve/tests.rs @@ -10,8 +10,9 @@ use crate::spirv::testing::{assert_valid, committed_profiles}; use std::path::PathBuf; /// Every format the module docs list. -const CLOSED: [Format; 34] = [ +const CLOSED: [Format; 35] = [ Format::R8_UNORM, + Format::A8_UNORM, Format::R8G8_UNORM, Format::R8G8B8A8_UNORM, Format::B8G8R8A8_UNORM, @@ -145,7 +146,8 @@ fn needs(m: TypedModule) -> Requirements { .requirements } -/// A format of each rule, each with its sample planes' copy format. +/// A format of each rule, and `A8_UNORM` (its planes held in its own format), each with its sample +/// planes' copy format. fn representatives() -> Vec<(ColorResolveFormat, PlanesCopy)> { [ Format::R8G8B8A8_UNORM, @@ -158,12 +160,13 @@ fn representatives() -> Vec<(ColorResolveFormat, PlanesCopy)> { Format::A1R5G5B5_UNORM_PACK16, Format::B10G11R11_UFLOAT_PACK32, Format::E5B9G9R9_UFLOAT_PACK32, + Format::A8_UNORM, ] .into_iter() .map(|format| { ( ColorResolveFormat::of(format).expect("closed"), - PlanesCopy::for_format(format).expect("copy"), + PlanesCopy::for_planes(format).expect("copy"), ) }) .collect() @@ -245,8 +248,9 @@ const RESOLVED_OUT: ResourceSlot = ResourceSlot { }; /// A kernel running the fragment stage's arithmetic: invocation `i` reads its `samples` texels as -/// four words each from `SAMPLES_IN` (the planes' bits for [`ResolveSource::Planes`], the -/// attachment's floats' bits for [`ResolveSource::InputAttachment`]), and writes the output +/// four words each from `SAMPLES_IN` (the planes' bits for [`ResolveSource::Planes`] of a bits +/// copy, the attachment's floats' bits for [`ResolveSource::InputAttachment`] and for planes held +/// in `A8_UNORM`, its raw twin's for [`ResolveSource::RawInputAttachment`]), and writes the output /// floats' bits to `RESOLVED_OUT`. fn arithmetic_module( format: ColorResolveFormat, @@ -299,9 +303,9 @@ fn arithmetic_module( lanes.push(f.load(p, MemAccess::default())?); } let texel = f.composite_construct(uvec4, &lanes)?; - texels.push(match source { - ResolveSource::Planes(_) => texel, - _ => f.convert(ConvOp::Bitcast, texel, t.vec4)?, + texels.push(match source.reads_bits() { + true => texel, + false => f.convert(ConvOp::Bitcast, texel, t.vec4)?, }); } let four = uint(f, t, 4)?; @@ -748,7 +752,7 @@ fn sample_words( let Some(channel) = channel else { continue }; let code = sample[component]; match source { - ResolveSource::Planes(_) => { + _ if source.reads_bits() => { let offset = u32::from(channel.offset); words[(offset / 32) as usize] |= code << (offset % 32); } @@ -876,12 +880,23 @@ fn small_float_bits(r: &mut SplitMix, mantissa: u8) -> u32 { } } -/// Every pair of 8-bit codes of `format` at 2 samples, through both sources. +/// Every pair of 8-bit codes of `format`'s one channel at 2 samples, through every source +/// ([`sources`]). fn every_pair_of_8_bit_codes(format: Format) { let resolve = ColorResolveFormat::of(format).expect("closed"); - let copy = PlanesCopy::for_format(format).expect("copy"); + let copy = PlanesCopy::for_planes(format).expect("copy"); + let component = resolve + .channels() + .iter() + .position(Option::is_some) + .expect("a channel"); + let sample = |code: u32| { + let mut codes = [0; 4]; + codes[component] = code; + codes + }; let texels: Vec> = (0..65536u32) - .map(|p| vec![[p & 0xff, 0, 0, 0], [p >> 8, 0, 0, 0]]) + .map(|p| vec![sample(p & 0xff), sample(p >> 8)]) .collect(); for (resolve, source) in cases(resolve, copy) { check(resolve, 2, source, &texels); @@ -893,6 +908,13 @@ fn every_pair_of_unorm_codes_resolves_as_metal() { every_pair_of_8_bit_codes(Format::R8_UNORM); } +/// `A8_UNORM`'s alpha, from its input attachment and from sample planes held in its own format +/// (`PlanesCopy::Alpha8`). +#[test] +fn every_pair_of_alpha_codes_resolves_as_metal() { + every_pair_of_8_bit_codes(Format::A8_UNORM); +} + #[test] fn every_pair_of_srgb_codes_resolves_as_metal() { every_pair_of_8_bit_codes(Format::R8_SRGB); @@ -1670,7 +1692,7 @@ fn alike_samples_resolve_as_metal() { continue; } let resolve = ColorResolveFormat::of(format).expect("closed"); - let copy = PlanesCopy::for_format(format).expect("copy"); + let copy = PlanesCopy::for_planes(format).expect("copy"); for samples in [2usize, 4, 8] .into_iter() .filter(|&n| resolve.resolves(n as u32)) diff --git a/crates/metal2vulkan/src/bind/graphics.rs b/crates/metal2vulkan/src/bind/graphics.rs index b6bad97ae..2882924a7 100644 --- a/crates/metal2vulkan/src/bind/graphics.rs +++ b/crates/metal2vulkan/src/bind/graphics.rs @@ -1794,6 +1794,7 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result Option c.vk_format, + false => crate::metal::format::direct_format(pixel_format) + .ok_or_else(|| internal("a storage heap member without a format"))?, + }; // The declaration names no format, so the member's format must serve those accesses // without one. let gaps = without_format_gaps(format, use_, profile); diff --git a/crates/metal2vulkan/src/bind/heap/tests.rs b/crates/metal2vulkan/src/bind/heap/tests.rs index d54721ba6..caf934edd 100644 --- a/crates/metal2vulkan/src/bind/heap/tests.rs +++ b/crates/metal2vulkan/src/bind/heap/tests.rs @@ -598,7 +598,11 @@ fn resource_id_placement_puts_a_sampler_at_its_element() { /// without an alias, the view the class's formatless declaration serves, or a half-float format's /// rounding, which a heap write takes from its handle's class; one needing a conversion view (bgra8 /// or sRGB where the profile cannot store them directly) is a typed refusal. Both occur on the -/// committed profiles, and every profile views a half-float member directly. +/// committed profiles, and every profile views a half-float member directly. An `A8Unorm` member +/// held in red (`StorageImageClass::AlphaInRed`) is viewed through its `R8_UNORM` image, whose +/// texels a heap access converts where the handle carries `A8Unorm`'s class: unswizzled, or +/// swizzled to read as unswizzled; a swizzle that moves its alpha carries another class and is +/// refused. #[test] fn a_storage_member_needing_a_conversion_view_is_refused() { let s2d = class( @@ -608,7 +612,7 @@ fn a_storage_member_needing_a_conversion_view_is_refused() { SampledType::Float, ImageAccess::Storage, ); - let (mut direct, mut refused) = (0, 0); + let (mut direct, mut refused, mut in_red) = (0, 0, 0); for (stem, p) in committed_profiles().expect("profiles") { let planner = HeapPlanner { profile: &p, @@ -640,6 +644,7 @@ fn a_storage_member_needing_a_conversion_view_is_refused() { PixelFormat::RGBA8UnormSRGB, PixelFormat::R16Float, PixelFormat::RGBA16Float, + PixelFormat::A8Unorm, ] { let m = shape(TextureType::Type2D, pf, 1, WRITE); let got = planner.view(&m, &s2d, vk::ImageLayout::GENERAL); @@ -655,6 +660,38 @@ fn a_storage_member_needing_a_conversion_view_is_refused() { assert_eq!(v.layout, vk::ImageLayout::GENERAL); direct += 1; } + Ok(c) if c.class == StorageImageClass::AlphaInRed => { + let v = got.unwrap_or_else(|e| panic!("{stem} {pf:?}: {e}")); + assert_eq!(v.format, vk::Format::R8_UNORM, "{stem}"); + use crate::metal::TextureSwizzle as S; + for (swizzle, kept) in [ + ((S::Zero, S::Zero, S::Zero, S::Alpha), true), + ((S::Alpha, S::Zero, S::Zero, S::One), false), + ] { + let mut swizzled = m; + if let TextureShape::Texture { swizzle: s, .. } = &mut swizzled { + *s = crate::metal::TextureSwizzleChannels::new( + swizzle.0, swizzle.1, swizzle.2, swizzle.3, + ); + } + let got = planner.view(&swizzled, &s2d, vk::ImageLayout::GENERAL); + match kept { + true => assert_eq!( + got.map(|v| v.format), + Ok(vk::Format::R8_UNORM), + "{stem} {swizzle:?}" + ), + false => assert_eq!( + got, + Err(BindError::Unsupported(Unsupported::not_implemented( + Feature::ArgumentBufferTextures + ))), + "{stem} {swizzle:?}" + ), + } + } + in_red += 1; + } Ok(_) => { assert_eq!( got, @@ -670,8 +707,8 @@ fn a_storage_member_needing_a_conversion_view_is_refused() { } } assert!( - direct > 0 && refused > 0, - "direct {direct}, refused {refused}" + direct > 0 && refused > 0 && in_red > 0, + "direct {direct}, refused {refused}, in red {in_red}" ); } diff --git a/crates/metal2vulkan/src/bind/plan/compute.rs b/crates/metal2vulkan/src/bind/plan/compute.rs index 3ae569acd..7e2cfb2c5 100644 --- a/crates/metal2vulkan/src/bind/plan/compute.rs +++ b/crates/metal2vulkan/src/bind/plan/compute.rs @@ -460,6 +460,7 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result { pub diagnostics: Vec, pub uses: Vec, pub template: ResourceTemplate, + /// The texture-buffer slots whose texel view reads an `A8Unorm` texture buffer's bytes as + /// `R8_UNORM` with no storage class to convert them (`metal::format::texel_buffer_alpha_in_red`): + /// their reads take Metal's alpha from red through the slot's swizzle + /// ([`ResourcePlanner::texture_swizzle`]). + pub alpha_red_texels: BTreeSet, } /// The type a texture binding declares (the neutral's input). @@ -1108,14 +1113,34 @@ impl ResourcePlanner<'_> { // The `R64_UINT` view of a `ulong` slot's bytes. _ if ulong_atomic => Some(vk::Format::R64_UINT), // The storage texel view reads the choice's view format (an alias of the - // bound format's bytes), which must itself support the usage. + // bound format's bytes, or an `A8Unorm` texture buffer's bytes as `R8_UNORM`, + // Metal's alpha in red), which must itself support the usage. Some(c) => Some( - c.alias - .map(|_| c.vk_format) - .or_else(|| direct_format(pixel_format)) - .ok_or_else(|| internal("a storage choice without a format"))?, + match (c.alias, c.class) { + (Some(_), _) | (None, StorageImageClass::AlphaInRed) => { + Some(c.vk_format) + } + (None, _) => direct_format(pixel_format), + } + .ok_or_else(|| internal("a storage choice without a format"))?, ), - None => None, + // An `A8Unorm` texture buffer's bytes as `R8_UNORM` where the device views + // no `A8_UNORM` texels for the usage: the slot's reads take Metal's alpha + // from red through its swizzle, which every texture-buffer read applies but a + // `ulong` one, whose texel no `A8Unorm` texture buffer binds. + None => match texel_buffer_alpha_in_red(pixel_format, usage, self.profile) { + Some(held) => { + if t.access.read && !self.has_fact(RuntimeFact::TextureSwizzle { slot }) + { + return Err(BindError::Unsupported(Unsupported::not_implemented( + Feature::Format, + ))); + } + self.alpha_red_texels.insert(slot); + Some(held) + } + None => None, + }, }; let format = match view { Some(view) => { @@ -1202,8 +1227,16 @@ impl ResourcePlanner<'_> { let format = match choice { _ if ulong_atomic => vk::Format::R64_UINT, Some(c) if c.alias.is_some() => c.vk_format, - // The write shadow's own format. - Some(c) if c.class == StorageImageClass::YCbCrWrite => c.vk_format, + // The write shadow's own format, and the `R8_UNORM` image an `A8Unorm` + // texture holds its alpha in. + Some(c) + if matches!( + c.class, + StorageImageClass::YCbCrWrite | StorageImageClass::AlphaInRed + ) => + { + c.vk_format + } _ => direct_format(pixel_format) .ok_or_else(|| internal("a storage texture without a format"))?, }; @@ -1930,6 +1963,11 @@ impl ResourcePlanner<'_> { /// texture, takes the identity's. pub fn texture_swizzle(&self, slot: SlotRef) -> u64 { let swizzle = match self.texture_shape(slot) { + Some(&TextureShape::Buffer { swizzle, .. }) + if self.alpha_red_texels.contains(&slot) => + { + swizzle.alpha_in_red() + } Some(&TextureShape::Buffer { swizzle, .. }) => swizzle, Some(&TextureShape::Texture { swizzle, .. }) if self.variant.swizzled_storage.contains(&slot) => diff --git a/crates/metal2vulkan/src/bind/plan/resources/tests.rs b/crates/metal2vulkan/src/bind/plan/resources/tests.rs index 99ab0317a..dffa47cf2 100644 --- a/crates/metal2vulkan/src/bind/plan/resources/tests.rs +++ b/crates/metal2vulkan/src/bind/plan/resources/tests.rs @@ -278,6 +278,7 @@ fn a_numeric_slot_binds_either_integer_type() { diagnostics: Vec::new(), uses: Vec::new(), template: Default::default(), + alpha_red_texels: Default::default(), }; let (write, _) = planner .plain_texture(0, 1, vk::DescriptorType::STORAGE_IMAGE, texture, false) @@ -594,6 +595,7 @@ fn runtime_sampler_values_are_checked_at_plan_time() { diagnostics: Vec::new(), uses: Vec::new(), template: Default::default(), + alpha_red_texels: Default::default(), }; let planned = planner.sampler(slot); match vk_sampler(desc, SamplerUse::new(compare, false), &p) { @@ -629,6 +631,7 @@ fn runtime_sampler_values_are_checked_at_plan_time() { diagnostics: Vec::new(), uses: Vec::new(), template: Default::default(), + alpha_red_texels: Default::default(), }; assert_eq!( planner.sampler(slot), @@ -709,6 +712,7 @@ fn an_immutable_linear_sampler_needs_a_filterable_view() { diagnostics: Vec::new(), uses: Vec::new(), template: Default::default(), + alpha_red_texels: Default::default(), }; let immutable = vk_sampler(&linear, SamplerUse::new(false, integer), &p).expect("maps"); let sampler = CombinedSampler::new(SamplerRef::Constexpr([0, 0]), false, integer); @@ -809,6 +813,7 @@ fn a_linear_compare_sampler_needs_no_filterable_view() { diagnostics: Vec::new(), uses: Vec::new(), template: Default::default(), + alpha_red_texels: Default::default(), }; let immutable = vk_sampler(&pcf, SamplerUse::new(compare, false), &p).expect("maps"); @@ -904,6 +909,7 @@ fn bicubic_texels_follow_the_bound_format() { diagnostics: Vec::new(), uses: Vec::new(), template: Default::default(), + alpha_red_texels: Default::default(), }; planner.bicubic_texels(texture) }; @@ -1000,6 +1006,7 @@ fn an_explicit_cube_gradient_binding_takes_an_anisotropic_sampler_isotropically( diagnostics: Vec::new(), uses: Vec::new(), template: Default::default(), + alpha_red_texels: Default::default(), }; let sampler = CombinedSampler::new(SamplerRef::Slot(sampler_slot.index), false, false) @@ -1107,6 +1114,7 @@ fn sampler_state_follows_the_bound_sampler() { diagnostics: Vec::new(), uses: Vec::new(), template: Default::default(), + alpha_red_texels: Default::default(), }; [W::PIXEL_COORDINATES, W::PIXEL_NEAREST, W::FIELDS] .map(|fields| planner.sampler_state(slot, fields) as u32) @@ -1174,6 +1182,7 @@ fn texel_format_follows_the_bound_format() { diagnostics: Vec::new(), uses: Vec::new(), template: Default::default(), + alpha_red_texels: Default::default(), }; planner.texel_format(texture) }; @@ -1392,6 +1401,7 @@ fn a_separate_pair_takes_the_combined_pairs_checks() { diagnostics: Vec::new(), uses: Vec::new(), template: Default::default(), + alpha_red_texels: Default::default(), }; // The runtime pair. let runtime = @@ -1447,3 +1457,134 @@ fn a_separate_pair_takes_the_combined_pairs_checks() { "refused on {refused:?}, passed on {passed:?}" ); } + +/// On a device without `A8_UNORM` (lavapipe's profile), an `A8Unorm` texture buffer's bytes are +/// viewed as `R8_UNORM`, Metal's alpha in red: a storage slot through its choice's class +/// (`StorageImageClass::AlphaInRed`), whose swizzle stays the texture's; a uniform one with no +/// class, whose swizzle takes the alpha from red (`TextureSwizzleChannels::alpha_in_red`). A +/// uniform slot that reads without applying the swizzle is refused there. Where the device has +/// `A8_UNORM` (MoltenVK's), the uniform view is `A8_UNORM` and its swizzle the texture's. +#[test] +fn an_a8_texture_buffer_without_a8_unorm_views_its_bytes_in_red() { + use crate::metal::{TextureSwizzle as S, TextureSwizzleChannels}; + use crate::pipeline::facts::{Mechanism, RuntimeFact}; + let slot = |index| SlotRef { + stage: Stage::Kernel, + class: SlotClass::Texture, + index, + }; + let (uniform, storage) = (slot(0), slot(1)); + let mut read = slot_iface(TextureType::TextureBuffer, SampledType::Float); + read.access = TextureAccess::new(false, true, false); + let mut read_write = read; + read_write.access = TextureAccess::new(false, true, true); + let slots = BTreeMap::from([ + (uniform, SlotInterface::Texture(read)), + (storage, SlotInterface::Texture(read_write)), + ]); + let shape = |swizzle| { + let mut stage = StageShape::default(); + for index in [0, 1] { + let pixel_format = PixelFormat::A8Unorm; + let buffer = TextureShape::Buffer { + pixel_format, + swizzle, + }; + stage.textures.insert(index, buffer); + } + BTreeMap::from([(Stage::Kernel, stage)]) + }; + let swizzle = TextureSwizzleChannels::new(S::Alpha, S::Zero, S::Green, S::One); + let swizzled = shape(swizzle); + let stated = [uniform, storage].map(|slot| { + let fact = RuntimeFact::TextureSwizzle { slot }; + RuntimeDependency::new(fact, Mechanism::Specialization) + }); + fn make<'a>( + profile: &'a DeviceProfile, + shape: &'a BTreeMap, + slots: &'a BTreeMap, + dependencies: &'a [RuntimeDependency], + ) -> ResourcePlanner<'a> { + ResourcePlanner { + profile, + shape, + slots, + dependencies, + stage_flags: |_| vk::PipelineStageFlags2::COMPUTE_SHADER, + variant: VariantKey::new(), + diagnostics: Vec::new(), + uses: Vec::new(), + template: Default::default(), + alpha_red_texels: Default::default(), + } + } + let uniform_ty = vk::DescriptorType::UNIFORM_TEXEL_BUFFER; + let storage_ty = vk::DescriptorType::STORAGE_TEXEL_BUFFER; + for (profile, held) in [("lavapipe", true), ("moltenvk-m3", false)] { + let p = crate::pipeline::testing::profile(profile, crate::device::DevicePolicy::default()) + .expect("profile"); + let a8 = PixelFormat::A8Unorm; + assert_eq!( + crate::metal::format::alpha_in_red(a8, &p), + held, + "{profile}" + ); + let mut planner = make(&p, &swizzled, &slots, &stated); + let own = match held { + true => vk::Format::R8_UNORM, + false => vk::Format::A8_UNORM, + }; + let planned = planner.plain_texture(0, 0, uniform_ty, uniform, false); + let Ok((WriteSource::TexelBuffer { format, .. }, _)) = planned else { + panic!("{profile}: {planned:?}"); + }; + assert_eq!(format, own, "{profile}: the uniform view"); + let planned = planner.plain_texture(0, 1, storage_ty, storage, false); + let Ok((WriteSource::TexelBuffer { format, .. }, _)) = planned else { + panic!("{profile}: {planned:?}"); + }; + // A storage view takes `R8_UNORM` wherever `A8_UNORM` does not serve the use, the device's + // images aside. + let class = planner + .variant + .storage_images + .get(&storage) + .map(|c| c.class); + let in_red = class == Some(StorageImageClass::AlphaInRed); + assert!(in_red || !held, "{profile}: {class:?}"); + let view = match in_red { + true => vk::Format::R8_UNORM, + false => vk::Format::A8_UNORM, + }; + assert_eq!(format, view, "{profile}: the storage view"); + let read_swizzle = match held { + true => TextureSwizzleChannels::new(S::Red, S::Zero, S::Zero, S::One), + false => swizzle, + }; + assert_eq!( + planner.texture_swizzle(uniform), + u64::from(read_swizzle.word()), + "{profile}: the uniform slot's swizzle" + ); + assert_eq!( + planner.texture_swizzle(storage), + u64::from(swizzle.word()), + "{profile}: the storage slot's swizzle" + ); + // A read that does not apply the swizzle. + let plain = shape(TextureSwizzleChannels::DEFAULT); + let mut planner = make(&p, &plain, &slots, &[]); + let planned = planner.plain_texture(0, 0, uniform_ty, uniform, false); + match held { + true => assert_eq!( + planned.map(|(w, _)| w), + Err(BindError::Unsupported(Unsupported::not_implemented( + Feature::Format + ))), + "{profile}" + ), + false => assert!(planned.is_ok(), "{profile}: {planned:?}"), + } + } +} diff --git a/crates/metal2vulkan/src/bind/sample_interleave.rs b/crates/metal2vulkan/src/bind/sample_interleave.rs index 776462622..dd162ed7f 100644 --- a/crates/metal2vulkan/src/bind/sample_interleave.rs +++ b/crates/metal2vulkan/src/bind/sample_interleave.rs @@ -317,12 +317,18 @@ fn finish( /// The split module of `copy` at `samples` on `device`, built, verified, serialized and /// numbered. Refused, `Unsupported` (feature `Format`) naming what the device lacks: an extended -/// copy format's storage without `shaderStorageImageExtendedFormats`. +/// copy format's storage without `shaderStorageImageExtendedFormats`; and `NotImplemented` for a +/// copy that moves no bits ([`PlanesCopy::Alpha8`], the sample planes' alone). pub fn interleave_split_module( device: &Device, copy: PlanesCopy, samples: u32, ) -> Result { + if !copy.moves_bits() { + return Err(Error::Unsupported(Unsupported::not_implemented( + Feature::Format, + ))); + } let (spirv, requirements) = finish( device, split_typed_module(copy, samples)?, diff --git a/crates/metal2vulkan/src/bind/sample_interleave/tests.rs b/crates/metal2vulkan/src/bind/sample_interleave/tests.rs index bf20b97a4..7aa769562 100644 --- a/crates/metal2vulkan/src/bind/sample_interleave/tests.rs +++ b/crates/metal2vulkan/src/bind/sample_interleave/tests.rs @@ -21,7 +21,7 @@ fn needs(m: TypedModule) -> Requirements { /// `shaderStorageImageExtendedFormats`, the merge's fragment stage `sampleRateShading`. #[test] fn each_module_needs_what_its_docs_say() { - for copy in PlanesCopy::ALL { + for copy in PlanesCopy::ALL.into_iter().filter(|c| c.moves_bits()) { for samples in SAMPLES { let r = needs(split_typed_module(copy, samples).expect("split")); let extended = !matches!(copy, PlanesCopy::R32 | PlanesCopy::Rgba32); @@ -99,7 +99,7 @@ fn the_modules_are_valid_where_the_device_has_what_they_need() { let mut built = 0; for (name, device) in committed_devices() { let profile = device.profile(); - for copy in PlanesCopy::ALL { + for copy in PlanesCopy::ALL.into_iter().filter(|c| c.moves_bits()) { for samples in SAMPLES { let fits = profile .check(&needs(split_typed_module(copy, samples).expect("split"))) @@ -116,6 +116,14 @@ fn the_modules_are_valid_where_the_device_has_what_they_need() { } } } + // The sample planes' copy of floats moves no bits: no interleave takes it. + assert_eq!( + interleave_split_module(&device, PlanesCopy::Alpha8, 4).err(), + Some(Error::Unsupported(Unsupported::not_implemented( + Feature::Format + ))), + "{name}" + ); for samples in SAMPLES { let fits = profile .check(&needs( diff --git a/crates/metal2vulkan/src/bind/sample_planes.rs b/crates/metal2vulkan/src/bind/sample_planes.rs index 859b9e0e9..4ddb0741a 100644 --- a/crates/metal2vulkan/src/bind/sample_planes.rs +++ b/crates/metal2vulkan/src/bind/sample_planes.rs @@ -6,7 +6,9 @@ //! addressed `(x, y, SampleId)`. The consumer keeps the planes and moves the samples between //! them and the attachment around the fetching draws. These crate-owned modules are the two //! moves, each through an unsigned-integer view of the attachment format's texel size -//! ([`PlanesCopy`]), so every texel's bits cross unchanged whatever the format: +//! ([`PlanesCopy`]), so every texel's bits cross unchanged whatever the format; `A8_UNORM`, whose +//! class no unsigned format shares, moves through its own format's `float`s +//! ([`PlanesCopy::Alpha8`]), which keep each 8-bit code: //! //! - **The split** ([`planes_split_module`], one per [`PlanesCopy`]): one `GLCompute` entry `main` //! with local size ([`PlanesSplitModule::LOCAL_SIZE`], [`PlanesSplitModule::LOCAL_SIZE`], 1) @@ -15,7 +17,7 @@ //! | Binding | Image | View | //! |---|---|---| //! | [`PlanesSplitModule::SOURCE_BINDING`] | the multisampled attachment | a sampled 2D view of its level and layer, in [`PlanesCopy::format`] | -//! | [`PlanesSplitModule::PLANES_BINDING`] | the planes | a storage 2D-array view of every layer, in [`PlanesCopy::format`] | +//! | [`PlanesSplitModule::PLANES_BINDING`] | the planes | a storage 2D-array view of every layer, in [`PlanesCopy::format`] (declared without a format for [`PlanesCopy::Alpha8`]) | //! //! Invocation `(x, y, s)` inside the planes' size fetches sample `s` of pixel `(x, y)` and //! writes it to texel `(x, y)` of layer `s`. Dispatch `ceil(width / LOCAL_SIZE)`, @@ -24,8 +26,8 @@ //! the whole viewport from `VertexIndex` 0 to 2 (no vertex input), and a `Fragment` entry `main` //! with one sampled 2D-array image, the planes in [`PlanesCopy::format`], at //! [`PlanesMergeModules::PLANES_BINDING`] of set 0. Each invocation fetches texel -//! `(FragCoord.xy, SampleId)` and writes it, an unsigned `uvec4`, to the color output at -//! `Location` 0. Run at sample rate (`sampleShadingEnable`, `minSampleShading` 1) into a +//! `(FragCoord.xy, SampleId)` and writes it, an unsigned `uvec4` (a `vec4` for +//! [`PlanesCopy::Alpha8`]), to the color output at `Location` 0. Run at sample rate (`sampleShadingEnable`, `minSampleShading` 1) into a //! render pass whose one color attachment is the multisampled attachment's view in //! [`PlanesCopy::format`], over the render area, without blending: each invocation writes its //! own sample. The fragment module reads `SampleId`, so it needs `sampleRateShading`. @@ -68,24 +70,30 @@ pub enum PlanesCopy { Rg32, /// Sixteen bytes: `R32G32B32A32_UINT`. Rgba32, + /// One byte of `A8_UNORM`'s own compatibility class ("8-bit alpha"), which no view of another + /// format reads: moved through `A8_UNORM` views as the `float` each reads, `code / 255` in + /// alpha, which its store keeps as the code. Not a bits copy ([`PlanesCopy::for_format`]): + /// the sample planes' copies alone take it ([`PlanesCopy::for_planes`]). + Alpha8, } impl PlanesCopy { - /// Every copy format, by texel size. - pub const ALL: [PlanesCopy; 5] = [ + /// Every copy format, by texel size, then [`PlanesCopy::Alpha8`]. + pub const ALL: [PlanesCopy; 6] = [ PlanesCopy::R8, PlanesCopy::R16, PlanesCopy::R32, PlanesCopy::Rg32, PlanesCopy::Rgba32, + PlanesCopy::Alpha8, ]; - /// The copy format of `format`: a color format of one texel per block, of 1, 2, 4, 8 or 16 - /// bytes, which shares the compatibility class of that unsigned format, so a view of it - /// moves the texel's bits. `None` for a depth, stencil, compressed, multi-planar or - /// 3-component 96-bit format, and for one of a class of its own (`A8_UNORM`'s "8-bit - /// alpha", the 4-pack 10- and 12-bit formats', the 4:2:2 formats'), which no view of - /// another format reads (the scout's VUID-VkImageCreateInfo-pNext-06722). + /// The copy format of `format` through which a copy moves its texels' bits: a color format + /// of one texel per block, of 1, 2, 4, 8 or 16 bytes, which shares the compatibility class of + /// that unsigned format, so a view of it moves the texel's bits. `None` for a depth, stencil, + /// compressed, multi-planar or 3-component 96-bit format, and for one of a class of its own + /// (`A8_UNORM`'s "8-bit alpha", the 4-pack 10- and 12-bit formats', the 4:2:2 formats'), + /// which no view of another format reads (VUID-VkImageCreateInfo-pNext-06722). pub fn for_format(format: Format) -> Option { let block = format.block()?; if block.color.is_none() || block.depth.is_some() || block.stencil.is_some() { @@ -108,7 +116,16 @@ impl PlanesCopy { .then_some(copy) } - /// The unsigned-integer Vulkan format of the copy. + /// The copy format of the sample planes of a color attachment of `format`: its bits copy + /// ([`PlanesCopy::for_format`]), else [`PlanesCopy::Alpha8`] for `A8_UNORM`, whose one 8-bit + /// unorm channel its own views' `float`s keep. `None` for another format. + pub fn for_planes(format: Format) -> Option { + PlanesCopy::for_format(format) + .or_else(|| (format == Format::A8_UNORM).then_some(PlanesCopy::Alpha8)) + } + + /// The Vulkan format of the copy's views: an unsigned-integer one, or `A8_UNORM` for + /// [`PlanesCopy::Alpha8`]. pub fn format(self) -> Format { match self { PlanesCopy::R8 => Format::R8_UINT, @@ -116,10 +133,18 @@ impl PlanesCopy { PlanesCopy::R32 => Format::R32_UINT, PlanesCopy::Rg32 => Format::R32G32_UINT, PlanesCopy::Rgba32 => Format::R32G32B32A32_UINT, + PlanesCopy::Alpha8 => Format::A8_UNORM, } } - /// The SPIR-V image format of a storage view in [`PlanesCopy::format`]. + /// Whether the copy moves texels as their bits, through an unsigned-integer format; else as + /// the `float`s of their own format ([`PlanesCopy::Alpha8`]). + pub fn moves_bits(self) -> bool { + self != PlanesCopy::Alpha8 + } + + /// The SPIR-V image format of a storage view in [`PlanesCopy::format`]: `Unknown` for + /// [`PlanesCopy::Alpha8`], whose format no SPIR-V format names. pub(crate) fn spirv_format(self) -> crate::spv::ImageFormat { match self { PlanesCopy::R8 => crate::spv::ImageFormat::R8ui, @@ -127,6 +152,7 @@ impl PlanesCopy { PlanesCopy::R32 => crate::spv::ImageFormat::R32ui, PlanesCopy::Rg32 => crate::spv::ImageFormat::Rg32ui, PlanesCopy::Rgba32 => crate::spv::ImageFormat::Rgba32ui, + PlanesCopy::Alpha8 => crate::spv::ImageFormat::Unknown, } } } @@ -139,7 +165,9 @@ pub struct PlanesSplitModule { pub spirv: Arc<[u32]>, /// What the module needs from the device: a storage image of an extended format /// (`shaderStorageImageExtendedFormats`) for [`PlanesCopy::R8`], [`PlanesCopy::R16`] and - /// [`PlanesCopy::Rg32`]. + /// [`PlanesCopy::Rg32`], and a storage write without a format (the SPIR-V capability + /// `StorageImageWriteWithoutFormat`, which the device resolves, `Requirements`) for + /// [`PlanesCopy::Alpha8`]. pub requirements: Requirements, } @@ -161,7 +189,8 @@ pub struct PlanesMergeModules { /// The vertex stage: SPIR-V 1.5 words, entry point `main`, no resources. pub vertex: Arc<[u32]>, /// The fragment stage: SPIR-V 1.5 words, entry point `main`, the planes at - /// [`PlanesMergeModules::PLANES_BINDING`] of set 0, the output at `Location` 0. + /// [`PlanesMergeModules::PLANES_BINDING`] of set 0, the output at `Location` 0: a `uvec4`, or + /// a `vec4` for [`PlanesCopy::Alpha8`]. pub fragment: Arc<[u32]>, /// What the two stages need from the device: `sampleRateShading`. pub requirements: Requirements, @@ -204,15 +233,26 @@ fn u32_ty(b: &mut ModuleBuilder) -> BResult { }) } -/// An unsigned 2D image type of `usage` and `format`, arrayed or multisampled as asked. -fn uint_image( +/// The scalar type of `copy`'s texels: unsigned 32-bit, or 32-bit float for a copy that does not +/// move bits ([`PlanesCopy::moves_bits`]). +fn texel_scalar(b: &mut ModuleBuilder, copy: PlanesCopy) -> BResult { + match copy.moves_bits() { + true => u32_ty(b), + false => b.ty(Type::Float { width: 32 }), + } +} + +/// A 2D image type of `copy`'s texels ([`texel_scalar`]), of `usage` and `format`, arrayed or +/// multisampled as asked. +fn copy_image( b: &mut ModuleBuilder, + copy: PlanesCopy, usage: ImageUsage, format: crate::spv::ImageFormat, arrayed: bool, multisampled: bool, ) -> BResult { - let sampled_type = u32_ty(b)?; + let sampled_type = texel_scalar(b, copy)?; b.ty(Type::Image(ImageType { sampled_type, dim: Dim::D2, @@ -239,9 +279,10 @@ pub fn split_typed_module(copy: PlanesCopy) -> BResult { let uvec2 = b.ty(Type::Vector { elem: u32_, len: 2 })?; let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?; let unknown = crate::spv::ImageFormat::Unknown; - let source_ty = uint_image(&mut b, ImageUsage::Sampled, unknown, false, true)?; - let planes_ty = uint_image( + let source_ty = copy_image(&mut b, copy, ImageUsage::Sampled, unknown, false, true)?; + let planes_ty = copy_image( &mut b, + copy, ImageUsage::Storage, copy.spirv_format(), true, @@ -359,10 +400,12 @@ pub fn merge_vertex_typed_module() -> BResult { b.finalize() } -/// The merge's fragment stage as a typed module. Its binding is the symbol [`MERGE_PLANES`]. -pub fn merge_fragment_typed_module() -> BResult { +/// The merge's fragment stage of `copy` as a typed module. Its binding is the symbol +/// [`MERGE_PLANES`]. +pub fn merge_fragment_typed_module(copy: PlanesCopy) -> BResult { let mut b = ModuleBuilder::new(); let u32_ = u32_ty(&mut b)?; + let scalar = texel_scalar(&mut b, copy)?; let i32_ = b.ty(Type::Int { width: 32, signed: true, @@ -370,13 +413,16 @@ pub fn merge_fragment_typed_module() -> BResult { let f32_ = b.ty(Type::Float { width: 32 })?; let vec4 = b.ty(Type::Vector { elem: f32_, len: 4 })?; let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?; - let uvec4 = b.ty(Type::Vector { elem: u32_, len: 4 })?; + let texel4 = b.ty(Type::Vector { + elem: scalar, + len: 4, + })?; let unknown = crate::spv::ImageFormat::Unknown; - let planes_ty = uint_image(&mut b, ImageUsage::Sampled, unknown, true, false)?; + let planes_ty = copy_image(&mut b, copy, ImageUsage::Sampled, unknown, true, false)?; let planes = b.resource(MERGE_PLANES, StorageClass::UniformConstant, planes_ty)?; let coord = b.builtin(crate::spv::BuiltIn::FragCoord, IoDir::Input, vec4)?; let sample = b.builtin(crate::spv::BuiltIn::SampleId, IoDir::Input, i32_)?; - let output = b.fixed_io(0, IoDir::Output, uvec4, false)?; + let output = b.fixed_io(0, IoDir::Output, texel4, false)?; let void = b.ty(Type::Void)?; let mut f = b.function(void)?; let coord = f.module().global_value(coord)?; @@ -455,16 +501,20 @@ pub fn planes_split_module(device: &Device, copy: PlanesCopy) -> Result Result { +/// The merge modules of `copy` on `device`, built and checked as [`planes_split_module`] is; +/// refused likewise where the device lacks `sampleRateShading`. Every bits copy +/// ([`PlanesCopy::moves_bits`]) takes the same modules. +pub fn planes_merge_modules( + device: &Device, + copy: PlanesCopy, +) -> Result { let (vertex, vertex_needs) = finish( device, merge_vertex_typed_module()?, "planes merge's vertex stage", )?; let (fragment, fragment_needs) = - finish(device, merge_fragment_typed_module()?, "planes merge")?; + finish(device, merge_fragment_typed_module(copy)?, "planes merge")?; let requirements = device .profile() .union_requirements(&vertex_needs, &fragment_needs); diff --git a/crates/metal2vulkan/src/bind/sample_planes/tests.rs b/crates/metal2vulkan/src/bind/sample_planes/tests.rs index 38631afbf..506a4de22 100644 --- a/crates/metal2vulkan/src/bind/sample_planes/tests.rs +++ b/crates/metal2vulkan/src/bind/sample_planes/tests.rs @@ -8,7 +8,8 @@ use crate::spirv::testing::assert_valid; use std::path::PathBuf; /// The copy format follows the texel size of a single-texel color format that shares its -/// compatibility class, and no other format has one. +/// compatibility class, and no other format has one; the sample planes' copies take `A8_UNORM`'s +/// own format besides. #[test] fn the_copy_format_is_the_texel_size() { for (format, copy) in [ @@ -31,13 +32,20 @@ fn the_copy_format_is_the_texel_size() { (Format::G8B8G8R8_422_UNORM, None), ] { assert_eq!(PlanesCopy::for_format(format), copy, "{format:?}"); + let planes = match format { + Format::A8_UNORM => Some(PlanesCopy::Alpha8), + _ => copy, + }; + assert_eq!(PlanesCopy::for_planes(format), planes, "{format:?}"); } for copy in PlanesCopy::ALL { assert_eq!( - PlanesCopy::for_format(copy.format()), + PlanesCopy::for_planes(copy.format()), Some(copy), "{copy:?}" ); + let bits = copy.moves_bits().then_some(copy); + assert_eq!(PlanesCopy::for_format(copy.format()), bits, "{copy:?}"); } } @@ -49,26 +57,35 @@ fn needs(m: TypedModule) -> Requirements { } /// Each module needs exactly what the module docs say: the split of an extended storage format -/// `shaderStorageImageExtendedFormats`, the merge's fragment stage `sampleRateShading`, and -/// nothing else of the device. +/// `shaderStorageImageExtendedFormats`, the split of `A8_UNORM`'s planes a storage write without a +/// format (the capability, which the device resolves), the merge's fragment stage +/// `sampleRateShading`, and nothing else of the device. #[test] fn each_module_needs_what_its_docs_say() { + let write_without = crate::device::requirements::SpirvCapability::of( + crate::spv::Capability::StorageImageWriteWithoutFormat, + ); for copy in PlanesCopy::ALL { let r = needs(split_typed_module(copy).expect("split")); - let extended = !matches!(copy, PlanesCopy::R32 | PlanesCopy::Rgba32); + let extended = matches!(copy, PlanesCopy::R8 | PlanesCopy::R16 | PlanesCopy::Rg32); assert_eq!( r.features .contains(&VkFeature::ShaderStorageImageExtendedFormats), extended, "{copy:?}: {r:?}" ); + assert_eq!( + r.spirv_capabilities.contains(&write_without), + !copy.moves_bits(), + "{copy:?}: {r:?}" + ); assert!( !r.features.contains(&VkFeature::SampleRateShading), "{copy:?}" ); + let r = needs(merge_fragment_typed_module(copy).expect("fragment")); + assert!(r.features.contains(&VkFeature::SampleRateShading), "{r:?}"); } - let r = needs(merge_fragment_typed_module().expect("fragment")); - assert!(r.features.contains(&VkFeature::SampleRateShading), "{r:?}"); let r = needs(merge_vertex_typed_module().expect("vertex")); assert!(r.features.is_empty(), "{r:?}"); } @@ -119,18 +136,19 @@ fn the_modules_are_valid_where_the_device_has_what_they_need() { Err(other) => panic!("{name} {copy:?}: {other}"), } } - let fits = profile - .check(&needs(merge_fragment_typed_module().expect("fragment"))) - .is_ok(); - match planes_merge_modules(&device) { - Ok(modules) => { - assert!(fits, "{name}"); - assert_valid(merge_vertex_typed_module().expect("vertex"), profile); - assert_valid(merge_fragment_typed_module().expect("fragment"), profile); - assert!(!modules.vertex.is_empty() && !modules.fragment.is_empty()); + for copy in [PlanesCopy::R32, PlanesCopy::Alpha8] { + let fragment = || merge_fragment_typed_module(copy).expect("fragment"); + let fits = profile.check(&needs(fragment())).is_ok(); + match planes_merge_modules(&device, copy) { + Ok(modules) => { + assert!(fits, "{name} {copy:?}"); + assert_valid(merge_vertex_typed_module().expect("vertex"), profile); + assert_valid(fragment(), profile); + assert!(!modules.vertex.is_empty() && !modules.fragment.is_empty()); + } + Err(Error::Unsupported(_)) => assert!(!fits, "{name} {copy:?}"), + Err(other) => panic!("{name} {copy:?}: {other}"), } - Err(Error::Unsupported(_)) => assert!(!fits, "{name}"), - Err(other) => panic!("{name}: {other}"), } } assert!(built > 0); diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index f8b516827..d0740adc2 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -1071,7 +1071,7 @@ codec_struct! { sample_mask, rotated_colors, rotated_factors, rotated_blends, srgb_fetches, half_output_lanes, texture_write_rounding, uniform_outputs, uniform_inputs, instanced_attributes, selected_colors, half_blend_colors, half_fast_colors, - float_blend_colors, zero_indices, color_group, + float_blend_colors, zero_indices, color_group, word_colors, alpha_in_red_colors, } ColorGroup { present, width, group } WordField { shift, bits } diff --git a/crates/metal2vulkan/src/lower/fragment/color.rs b/crates/metal2vulkan/src/lower/fragment/color.rs index a094beb85..c64396587 100644 --- a/crates/metal2vulkan/src/lower/fragment/color.rs +++ b/crates/metal2vulkan/src/lower/fragment/color.rs @@ -52,6 +52,12 @@ //! fetch lane checks on every byte. The interface records the color (`StageIo::srgb_fetches`), //! which link holds the pipeline's to. //! +//! **An `A8Unorm` attachment whose image holds Metal's alpha in red** (`R8_UNORM` on a device +//! without `A8_UNORM`, `LoweringInputs::alpha_in_red_colors`) reads `(r, 0, 0, 1)` through its +//! input attachment, which the read turns into Metal's `(0, 0, 0, r)` ([`alpha_in_red`]); the +//! interface records the color (`StageIo::alpha_in_red_colors`), which link holds the pipeline's +//! to. +//! //! A color input in a raster order group is read like any other: the family runs the whole body //! inside the interlock, and the read's ordering against other fragments' color writes is still the //! ordering policy's (the interlock orders shader invocations, not the attachment writes that @@ -101,6 +107,9 @@ pub struct ColorInput { /// an input attachment's read snaps the device's decode back to its byte and decodes that by /// Metal's table. pub srgb: bool, + /// The attachment's image holds Metal's alpha in red (`LoweringInputs::alpha_in_red_colors`, + /// `A8Unorm` in `R8_UNORM`): a read, `(r, 0, 0, 1)` from the image, is Metal's `(0, 0, 0, r)`. + pub alpha_red: bool, } /// An upper estimate of the words one input attachment declares (type, variable, decorations). @@ -164,6 +173,7 @@ pub(super) fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result, b: &ParamBinding) -> Result, colors: &[ColorInput]) -> u64 { let srgb: Vec = colors.iter().filter(|c| c.srgb).copied().collect(); let snaps = self::uses(cx, &srgb); let snap = u64::from(3 * srgb::SEARCH_WORDS + 3 * srgb::STEP_WORDS) + 400; + // An alpha-in-red attachment's read moves its red to alpha: a shuffle and its zero. + let red: Vec = colors.iter().filter(|c| c.alpha_red).copied().collect(); + let moves = self::uses(cx, &red); let mut attachments: Vec = colors.iter().map(|c| c.color).collect(); attachments.sort_unstable(); attachments.dedup(); @@ -309,8 +337,13 @@ pub(super) fn words(cx: &SelectCx<'_>, colors: &[ColorInput]) -> u64 { .saturating_add(READ_WORDS.saturating_mul(uses)) .saturating_add(u64::from(extended_range::DECODE_WORDS + 120).saturating_mul(decodes)) .saturating_add(snap.saturating_mul(snaps)) + .saturating_add(ALPHA_IN_RED_WORDS.saturating_mul(moves)) } +/// An upper estimate of the words [`alpha_in_red`] adds: the shuffle, and the zero vector's +/// constant and type. +pub(super) const ALPHA_IN_RED_WORDS: u64 = 16; + /// Declare one input attachment per color index the plan reads, multisampled for a per-sample /// function (`multisampled`), or its storage image in the interlocked storage form (`fetch`), which /// holds the samples as its view states; the storage image of every other attachment in that form @@ -422,6 +455,8 @@ pub(super) fn value( let byte = math::pack(fb, PackFormat::Unorm4x8Srgb, f4, texel, Some(table), test)?; math::unpack(fb, PackFormat::Unorm4x8Srgb, f4, byte, Some(table))? } + // The image's red, Metal's alpha: `(0, 0, 0, r)`. + None if c.alpha_red => alpha_in_red(fb, texel)?, None => texel, }; let x = match c.form.lanes { @@ -436,6 +471,18 @@ pub(super) fn value( narrow::round(fb, c.form, x) } +/// Metal's texel of an `A8Unorm` attachment whose image holds Metal's alpha in red, from the +/// image's `texel` (a `vec4`, `(r, 0, 0, 1)`): `(0, 0, 0, r)`, as Metal reads such an attachment +/// (probe `a8`'s uses on an M3 Max under macOS 27.0.1: a fetch of the byte 153 is +/// `(0, 0, 0, 0.6)`, a scalar or two-lane fetch its leading lanes). +pub(super) fn alpha_in_red(fb: &mut FunctionBuilder<'_>, texel: SValue) -> BResult { + let f32_ = fb.module().ty(SType::Float { width: 32 })?; + let vec4 = fb.module().ty(SType::Vector { elem: f32_, len: 4 })?; + let zero = fb.module().constant(Constant::Null { ty: vec4 })?; + let zero = fb.module().const_value(zero)?; + fb.vector_shuffle(zero, texel, &[0, 1, 2, 4]) +} + /// The texel of color `color`'s input attachment, as the image reads it: at the calling /// fragment's own texel, at the invocation's sample for a per-sample function. pub(super) fn input_texel( diff --git a/crates/metal2vulkan/src/lower/fragment/fetch.rs b/crates/metal2vulkan/src/lower/fragment/fetch.rs index fb12ea96b..cbf316374 100644 --- a/crates/metal2vulkan/src/lower/fragment/fetch.rs +++ b/crates/metal2vulkan/src/lower/fragment/fetch.rs @@ -64,6 +64,12 @@ //! image or written to it with red and blue exchanged ([`metal_order`]): the device converts //! each channel as it converts the attachment's own, so a read, a write, the channels a write //! mask keeps and the per-sample forms hold the values the attachment's own view would; an +//! `A8Unorm` attachment whose image holds Metal's alpha in red (`R8_UNORM` on a device without +//! `A8_UNORM`, `StorageView::alpha_in_red`) through that image, every texel read from it taken +//! to Metal's `(0, 0, 0, r)` and every one written to it holding Metal's alpha in red +//! ([`metal_order`], [`image_order`]), so a read, a merge of the channels a write mask keeps +//! (in Metal's channels, of which only alpha is stored) and the per-sample forms are Metal's +//! (probe `a8`'s uses on an M3 Max under macOS 27.0.1); an //! 8-bit four-channel sRGB format //! (`RGBA8Unorm_sRGB`, `BGRA8Unorm_sRGB`) through a view of the attachment in `R32_UINT` //! (`StorageView::uint_view`), whose bytes the function converts by Metal's measured conversions @@ -680,6 +686,11 @@ pub struct StorageView { /// unsigned integer format, and a write encodes Metal's word ([`word_texel`]). `None` for /// another format and device. pub word: Option, + /// The attachment's image holds Metal's alpha in red (`metal::format::alpha_in_red`: + /// `A8Unorm` in `R8_UNORM` on a device without `A8_UNORM`): the view and the declaration are + /// `R8_UNORM`'s, a texel read from the image, `(r, 0, 0, 1)`, is Metal's `(0, 0, 0, r)`, and a + /// texel written to it holds Metal's alpha in red ([`metal_order`], [`image_order`]). + pub alpha_in_red: bool, } impl StorageView { @@ -974,11 +985,17 @@ pub(crate) fn storage_form( } let shader_blends = blend.is_some(); let blends = attachment.blending_enabled && !(attachment.replaces && !snorm) && !shader_blends; + // An `A8Unorm` attachment whose image holds Metal's alpha in red, for every use of the + // texture (`metal::format::alpha_in_red`), is read and written through its `R8_UNORM` image, + // the function moving Metal's alpha into and out of red. + let alpha_in_red = emulation == FormatEmulation::AlphaInRed + && crate::metal::format::alpha_in_red(pf, p) + && word.is_none(); // An unblended write of every channel stores Metal's write of the output. A padded 10-bit // attachment's tile value and blends are not measured: no storage form. let not_modelled = inputs.amplified || extended.is_some_and(ExtendedRange::padded) - || (mapping.emulation != FormatEmulation::Direct && extended.is_none()) + || (emulation != FormatEmulation::Direct && extended.is_none() && !alpha_in_red) || (extended.is_some() && stores && !shader_blends @@ -1077,6 +1094,7 @@ pub(crate) fn storage_form( uint_view, rgba_view, word, + alpha_in_red, })), _ => { // A BGRA-order format no declaration reaches, whose RGBA-order twin lacks something @@ -1611,6 +1629,16 @@ pub(super) fn plan(cx: &mut SelectCx<'_>) -> Result<(), Error> { nearest_even, }, ); + // An image holding Metal's alpha in red is read and written as Metal's alpha; the + // interface records the attachment, which link holds the pipeline's to + // (`color_writes::check`). + if view.alpha_in_red { + cx.families + .stage_io + .interface + .alpha_in_red_colors + .insert(color); + } cx.facts.insert(RuntimeFact::InterlockedFramebufferFetch { color, format: view.format, @@ -2029,6 +2057,8 @@ pub(super) fn words(cx: &SelectCx<'_>, uses: u64, rets: u64) -> u64 { .values() .filter(|sc| sc.view.rgba_view.is_some()) .count() as u64; + // An alpha-in-red image's read moves its red to alpha, and its write alpha to red. + let moved = fetch.values().filter(|sc| sc.view.alpha_in_red).count() as u64; let read = match ( fetch.values().any(|sc| sc.view.extended.is_some()), fetch.values().any(|sc| sc.view.uint_view.is_some()), @@ -2037,7 +2067,8 @@ pub(super) fn words(cx: &SelectCx<'_>, uses: u64, rets: u64) -> u64 { (false, true) => READ.saturating_add(u64::from(3 * srgb::STEP_WORDS) + 400), (false, false) => READ, } - .saturating_add(EXCHANGE.saturating_mul(exchanged)); + .saturating_add(EXCHANGE.saturating_mul(exchanged)) + .saturating_add(super::color::ALPHA_IN_RED_WORDS.saturating_mul(moved)); // An sRGB attachment's write encodes four channels (three through Metal's thresholds), // reorders its bytes, and merges kept ones from the texel it reads first. let srgb_writes = fetch @@ -2064,6 +2095,7 @@ pub(super) fn words(cx: &SelectCx<'_>, uses: u64, rets: u64) -> u64 { .saturating_add(word_write) .saturating_add((READ + WRITE + 8).saturating_mul(shadowed)) .saturating_add((2 * EXCHANGE).saturating_mul(exchanged)) + .saturating_add((EXCHANGE + super::color::ALPHA_IN_RED_WORDS).saturating_mul(moved)) .saturating_add(40); OBJECT .saturating_mul(fetch.len() as u64 + shadowed) @@ -2220,15 +2252,28 @@ fn read_texel( metal_order(fb, sc, texel) } -/// Texel `texel` of storage-form attachment `sc`, in Metal's channel order from the image's or in -/// the image's from Metal's: an attachment viewed in its RGBA-order twin -/// ([`StorageView::rgba_view`]) has red and blue exchanged, an exchange that is its own inverse; -/// any other is as it is. Every texel written to the attachment's image goes through here too -/// ([`emit_return`]). +/// Texel `texel` of storage-form attachment `sc`'s image, in Metal's channel order: an attachment +/// viewed in its RGBA-order twin ([`StorageView::rgba_view`]) has red and blue exchanged, and one +/// whose image holds Metal's alpha in red ([`StorageView::alpha_in_red`]) reads `(r, 0, 0, 1)` as +/// Metal's `(0, 0, 0, r)`; any other is as it is. Every texel read from the attachment's image +/// goes through here ([`read_texel`]), and every one written to it through [`image_order`]. fn metal_order(fb: &mut FunctionBuilder<'_>, sc: &StorageColor, texel: SValue) -> BResult { - match sc.view.rgba_view { - Some(_) => fb.vector_shuffle(texel, texel, &[2, 1, 0, 3]), - None => Ok(texel), + match (sc.view.rgba_view, sc.view.alpha_in_red) { + (Some(_), _) => fb.vector_shuffle(texel, texel, &[2, 1, 0, 3]), + (None, true) => super::color::alpha_in_red(fb, texel), + (None, false) => Ok(texel), + } +} + +/// Metal-ordered texel `texel` of storage-form attachment `sc`, in its image's channel order: +/// [`metal_order`]'s exchange of red and blue, which is its own inverse, and for an image holding +/// Metal's alpha in red, Metal's alpha in every lane (the image keeps its red). Every texel +/// written to the attachment's image goes through here ([`emit_return`]). +fn image_order(fb: &mut FunctionBuilder<'_>, sc: &StorageColor, texel: SValue) -> BResult { + match (sc.view.rgba_view, sc.view.alpha_in_red) { + (Some(_), _) => fb.vector_shuffle(texel, texel, &[2, 1, 0, 3]), + (None, true) => fb.vector_shuffle(texel, texel, &[3, 3, 3, 3]), + (None, false) => Ok(texel), } } @@ -2417,7 +2462,7 @@ pub(super) fn emit_return( } }; // The image's texel of the Metal-ordered one. - let texel = metal_order(fb, &sc, texel)?; + let texel = image_order(fb, &sc, texel)?; let (image, at, ops) = image_and_texel(cx, fb, color, sc.view.samples)?; texels.push((image, at, texel, ops)); if let Some(held) = held { diff --git a/crates/metal2vulkan/src/lower/stage_io/mod.rs b/crates/metal2vulkan/src/lower/stage_io/mod.rs index a2990a948..cc3ba29d6 100644 --- a/crates/metal2vulkan/src/lower/stage_io/mod.rs +++ b/crates/metal2vulkan/src/lower/stage_io/mod.rs @@ -298,6 +298,11 @@ pub struct PlannedOutput { /// with its channels rotated (`LoweringInputs::rotated_colors`): its four lanes are stored /// rotated (`metal::format::to_rotated_image`), after their conversion. pub rotated: bool, + /// A [`rotated`](Self::rotated) output to an attachment whose image holds Metal's alpha in + /// red (`LoweringInputs::alpha_in_red_colors`): the image's alpha lane holds Metal's alpha + /// too, not Metal's blue, so alpha to coverage reads Metal's alpha (the image keeps only its + /// red). + pub alpha_red: bool, /// A fragment function's first output to a rotated attachment whose blend takes /// `RotatedBlendForm::Premultiplied` (`LoweringInputs::rotated_blends`): after the rotation, /// the image's alpha lane (Metal's blue) holds Metal's blue times Metal's alpha, each clamped @@ -1990,10 +1995,12 @@ fn output_part( }, None => part, }; - // Metal's red, green, blue and alpha, held as the image's green, blue, alpha and red. - let part = match o.rotated { - true => fb.vector_shuffle(part, part, &[3, 0, 1, 2])?, - false => part, + // Metal's red, green, blue and alpha, held as the image's green, blue, alpha and red; an + // image holding Metal's alpha in red takes that alpha in its alpha lane as well. + let part = match (o.rotated, o.alpha_red) { + (true, false) => fb.vector_shuffle(part, part, &[3, 0, 1, 2])?, + (true, true) => fb.vector_shuffle(part, part, &[3, 0, 1, 3])?, + (false, _) => part, }; match o.premultiplied { true => premultiplied_blue(fb, o.link.form, part), diff --git a/crates/metal2vulkan/src/lower/stage_io/plan.rs b/crates/metal2vulkan/src/lower/stage_io/plan.rs index 070fb212c..8400ff19e 100644 --- a/crates/metal2vulkan/src/lower/stage_io/plan.rs +++ b/crates/metal2vulkan/src/lower/stage_io/plan.rs @@ -2040,6 +2040,7 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { below: None, color: None, rotated: false, + alpha_red: false, premultiplied: false, offset: offset(PushField::AmplificationLayerOffset), }); @@ -2193,6 +2194,7 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { below: None, color: None, rotated: false, + alpha_red: false, premultiplied: false, offset: offset(PushField::AmplificationViewportOffset), }); @@ -2242,8 +2244,11 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { } _ => None, }; - // An output to an attachment held with its channels rotated stores them rotated. + // An output to an attachment held with its channels rotated stores them rotated; one to an + // attachment holding Metal's alpha in red holds that alpha in the image's alpha lane too, + // where alpha to coverage reads it. let mut premultiplied = false; + let mut alpha_red = false; let rotated = match o.role { OutputRole::RenderTarget { attachment: AbiInt::Const(attachment), @@ -2259,6 +2264,10 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { } let sp = &mut cx.families.stage_io; sp.interface.rotated_colors.insert(attachment); + if cx.inputs.alpha_in_red_colors.contains(&attachment) { + sp.interface.alpha_in_red_colors.insert(attachment); + alpha_red = true; + } if let (0, Some(&lanes)) = (index, cx.inputs.rotated_factors.get(&attachment)) { seconds.push((attachment, o.field, link.form, lanes)); } @@ -2277,6 +2286,7 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { below: raw.map(|(_, count, _)| count), color, rotated, + alpha_red, premultiplied, offset: added, }); @@ -2293,6 +2303,7 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { below: None, color: None, rotated: false, + alpha_red: false, premultiplied: false, offset: added, }); diff --git a/crates/metal2vulkan/src/lower/texture/emit.rs b/crates/metal2vulkan/src/lower/texture/emit.rs index dec5af92b..220c7884b 100644 --- a/crates/metal2vulkan/src/lower/texture/emit.rs +++ b/crates/metal2vulkan/src/lower/texture/emit.rs @@ -770,6 +770,40 @@ fn rotate_argb(fb: &mut FunctionBuilder<'_>, x: SValue, read: bool) -> BResult, x: SValue, read: bool) -> BResult { + match read { + true => { + let zero = f32s(fb, 4, 0.0)?; + fb.vector_shuffle(zero, x, &[0, 1, 2, 4]) + } + false => fb.vector_shuffle(x, x, &[3, 3, 3, 3]), + } +} + +/// The words [`heap_alpha_in_red`] emits, at most: the class field's shift and mask, the +/// comparison, the shuffle and the select. +pub(crate) const HEAP_ALPHA_IN_RED_WORDS: u32 = 40; + +/// Image texel `x` (four `f32` lanes) of a storage access through heap handle `handle`, as +/// [`alpha_in_red`] converts it (`read`: the image's to Metal's; else Metal's to the image's) where +/// the handle's class index is `A8Unorm`'s (`metal::texel_format::heap_alpha_in_red_index`), as +/// it is elsewhere (`Read::heap_alpha_red`, `Write::heap_alpha_red`). +fn heap_alpha_in_red( + cx: &mut EmitCx<'_>, + fb: &mut FunctionBuilder<'_>, + handle: ValueId, + x: SValue, + read: bool, +) -> BResult { + let index = crate::metal::texel_format::heap_alpha_in_red_index(); + let is = heap_class_among(cx, fb, handle, &[index])?; + let held = alpha_in_red(fb, x, read)?; + fb.select(is, held, x) +} + /// The words [`srgb_codes`] emits, at most: `math::pack`'s `unorm4x8_srgb` (its exact products, /// three table searches, and the placement) and the codes' extraction and scale. pub(crate) const SRGB_WRITE_WORDS: u32 = @@ -854,6 +888,7 @@ fn from_image( return srgb_raw_texel(cx, fb, form, x, SRGB_TEXEL); } StorageImageClass::RotateArgb => rotate_argb(fb, x, true)?, + StorageImageClass::AlphaInRed => alpha_in_red(fb, x, true)?, // A `YCbCrWrite` slot is only written (`StorageImageClass::YCbCrWrite`). StorageImageClass::HalfTowardZero | StorageImageClass::HalfQuietNan @@ -1708,6 +1743,12 @@ pub fn to_image( let x = argb_codes(fb, form, x)?; rotate_argb(fb, x, false)? } + StorageImageClass::AlphaInRed if form.lanes == 4 => alpha_in_red(fb, x, false)?, + StorageImageClass::AlphaInRed => { + return Err(crate::spirv::error::BuildError::Type( + crate::spirv::error::TypeRule::FunctionSignature, + )) + } StorageImageClass::HalfTowardZero | StorageImageClass::HalfQuietNan | StorageImageClass::SmallFloatQuietNan => match form.conv { @@ -3274,6 +3315,12 @@ fn read(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BResult< } false => texel, }; + // An `A8Unorm` storage member's texel held in red, Metal's `(0, 0, 0, r)` before Metal's + // out-of-bounds texel is selected. + let texel = match (r.heap_alpha_red, r.image) { + (true, ImageRef::Heap { handle, .. }) => heap_alpha_in_red(cx, fb, handle, texel, true)?, + _ => texel, + }; // An extended-range texel's value, decoded from its raw code before Metal's out-of-bounds // texel is selected. let texel = match r.extended { @@ -3727,6 +3774,11 @@ fn write(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, w: &Write) -> BResul }; // An integer texel's lanes, saturated to the format's channels as Metal stores them. let texel = saturated(cx, fb, &decl, (w.saturate, w.texel), texel)?; + // An `A8Unorm` storage member's alpha, stored in its image's red. + let texel = match (w.heap_alpha_red, w.image) { + (true, ImageRef::Heap { handle, .. }) => heap_alpha_in_red(cx, fb, handle, texel, false)?, + _ => texel, + }; // A `float` through a heap handle, rounded where the handle's class is a half-float // format's. let texel = match (w.heap_half, w.image) { diff --git a/crates/metal2vulkan/src/lower/texture/mod.rs b/crates/metal2vulkan/src/lower/texture/mod.rs index 3ed80361e..a5c9b29b7 100644 --- a/crates/metal2vulkan/src/lower/texture/mod.rs +++ b/crates/metal2vulkan/src/lower/texture/mod.rs @@ -308,6 +308,10 @@ pub struct Read { /// the handle's class index names one (`heap_raw`): its raw texel fetched from the group's /// unsigned integer class (`HeapPlan::raw`), in place of the float array's neutral. pub heap_raw: bool, + /// The read, of a storage heap group, takes Metal's texel `(0, 0, 0, r)` from the image's red + /// where the handle's class index is `A8Unorm`'s, on a device that holds such a texture's alpha + /// in red ([`heap_alpha_in_red`]). + pub heap_alpha_red: bool, /// A `float` texel of the slot converts by the bound format's class (`float_texel`): its /// code recovered from the device's value and divided exactly. pub float_texel: bool, @@ -363,6 +367,11 @@ fn read_words(r: &Read) -> u32 { + if r.level_views { 48 } else { 0 } + if r.image.heap() { 32 } else { 0 } + if r.heap_raw { heap_raw::READ_WORDS } else { 0 } + + if r.heap_alpha_red { + emit::HEAP_ALPHA_IN_RED_WORDS + } else { + 0 + } + if r.edge.is_some() { 64 } else { 0 } + if r.raw || r.srgb_codes { SRGB_RAW_WORDS @@ -428,6 +437,10 @@ pub struct Write { /// texel class is a small float's (`StorageImageClass::SmallFloatQuietNan`, /// `emit::heap_small_float_format`). pub heap_small_floats: bool, + /// A `float` or `half` texel written through a heap handle stores its alpha in the image's + /// red where the handle's class index is `A8Unorm`'s, on a device that holds such a texture's + /// alpha in red ([`heap_alpha_in_red`]). + pub heap_alpha_red: bool, /// The slot is one of `LoweringInputs::swizzled_storage`: the write undoes the bound /// texture's swizzle on its held value, before converting it, under the slot's /// `TextureSwizzle` specialization (`emit::unswizzled`). @@ -893,6 +906,11 @@ impl TextureStrategy { true => heap_half_write_words(StorageImageClass::SmallFloatQuietNan), false => 0, } + + if w.heap_alpha_red { + emit::HEAP_ALPHA_IN_RED_WORDS + } else { + 0 + } + w.half_nans.words() + w.norm.words(w.image.heap()) + if w.cross.is_some() { 48 } else { 0 } @@ -2642,6 +2660,30 @@ pub(super) fn heap_bits( applies } +/// Whether a storage read or write of a `float` or `half` texel (`texel`) through heap handle +/// `image` of shape `shape` converts an `A8Unorm` member's texels: a heap access, not to a texture +/// buffer (no heap class holds one), on a device that holds such a texture's alpha in +/// its `R8_UNORM` image's red (`metal::format::alpha_in_red`), which the storage array views without +/// a component mapping (`bind::heap`'s storage elements). The handle carries its class index, and +/// where it is `A8Unorm`'s (`metal::texel_format::heap_alpha_in_red_index`) a read is Metal's +/// `(0, 0, 0, r)` and a write stores the alpha in red (`StorageImageClass::AlphaInRed`'s +/// conversion), as Metal reads and writes such a member (probe `a8`'s argument buffers). +pub(super) fn heap_alpha_in_red( + cx: &mut SelectCx<'_>, + image: ImageRef, + shape: ImageShape, + texel: TexelConv, +) -> bool { + let applies = image.heap() + && matches!(texel, TexelConv::F32 | TexelConv::F16) + && shape.dim != ImageDim::Buffer + && crate::metal::format::alpha_in_red(crate::metal::PixelFormat::A8Unorm, cx.profile); + if applies { + cx.families.access.heap_class_index = true; + } + applies +} + /// Record that the stage's `half` (`packed`) or `float` writes through heap handles store /// half-float members' bits through the unsigned integer twin, and leave the device's conversion /// of a NaN to the members it does not hold (`RuntimeFact::HeapHalfTexelWrites`), which the @@ -2688,10 +2730,14 @@ pub(super) fn norm_storage( || c.vk_format .block() .is_some_and(|b| matches!(b.color, Some(N::Unorm | N::Snorm))); + // `AlphaInRed` stores the rounded alpha in red: the routine rounds the + // texel in Metal's channels, before the class moves them. normalized && matches!( c.class, - StorageImageClass::Identity | StorageImageClass::SwizzleBgra + StorageImageClass::Identity + | StorageImageClass::SwizzleBgra + | StorageImageClass::AlphaInRed ) } } @@ -3427,6 +3473,7 @@ fn select_read_as( if let (true, ImageRef::Slot(index)) = (swizzle || storage_swizzle, image) { swizzles(cx, index)?; } + let heap_alpha_red = storage && heap_alpha_in_red(cx, image, shape, texel.conv); // Where the profile's sparse textures are sparse images, a block of one that holds no mapped // tile reads the device's value (RADV's alpha 0), where Metal reads a channel the format // lacks as its constant: a color read of four 32-bit held lanes sets them after it, whether @@ -3473,6 +3520,7 @@ fn select_read_as( storage_swizzle, extended, heap_raw, + heap_alpha_red, float_texel, half_nans, constant_lanes, @@ -3648,6 +3696,8 @@ fn select_write( // Its NaNs quieted where the class is a small float's. let heap_small_floats = image.heap() && texel.conv == TexelConv::F32; cx.families.access.heap_class_index |= heap_half.is_some() || heap_small_floats; + // Its alpha in red where the class is `A8Unorm`'s and the device holds such a texture so. + let heap_alpha_red = heap_alpha_in_red(cx, image, shape, texel.conv); // A half-float member's bits through the group's unsigned integer twin, where the handle's // class names one. let encoded = extended.is_some() || cross.is_some(); @@ -3692,6 +3742,7 @@ fn select_write( class, heap_half, heap_small_floats, + heap_alpha_red, swizzle, half_nans, norm, diff --git a/crates/metal2vulkan/src/metal/format/mod.rs b/crates/metal2vulkan/src/metal/format/mod.rs index d08d20f28..f16066725 100644 --- a/crates/metal2vulkan/src/metal/format/mod.rs +++ b/crates/metal2vulkan/src/metal/format/mod.rs @@ -47,7 +47,8 @@ pub struct FormatMapping { /// The format of the Vulkan image (and of its views). pub format: vk::Format, /// The view's component mapping that presents Metal's channels (identity unless - /// [`FormatEmulation::SwizzledView`]). Texture swizzles the guest requests compose on top. + /// [`FormatEmulation::SwizzledView`] or [`FormatEmulation::AlphaInRed`]). Texture swizzles + /// the guest requests compose on top. pub components: vk::ComponentMapping, /// The aspects the Metal format has (a sampled view selects one of them). pub aspects: vk::ImageAspectFlags, @@ -77,14 +78,36 @@ pub enum FormatEmulation { /// The Vulkan format has exactly the Metal format's layout and numeric format. Direct, /// The bytes are read through a Vulkan format with the same bit layout but a different channel - /// order (or `R8_UNORM` for `A8Unorm` where `A8_UNORM` is not exposed), and - /// [`FormatMapping::components`] moves the channels back. Exact for sampling, except that + /// order, and [`FormatMapping::components`] moves the channels back. Exact for sampling, except that /// Vulkan leaves an opaque-black border read through a non-identity mapping undefined unless /// the device swizzles borders /// ([`check_border_swizzle`](crate::metal::sampler::check_border_swizzle)); admitted only for /// sampled-image usages, because texel buffers, storage images, and attachments ignore the /// component mapping. SwizzledView, + /// `A8Unorm`'s byte held in `R8_UNORM`, on a device without `A8_UNORM` for the usages (it is + /// core only from Vulkan 1.4, else `VK_KHR_maintenance5`): sampled through + /// [`FormatMapping::components`] `(Zero, Zero, Zero, R)` as [`FormatEmulation::SwizzledView`] + /// is (exact, and at the border as that is); a storage image whose shader reads the byte as + /// alpha and writes a texel's alpha into it (`StorageImageClass::AlphaInRed`); and a color + /// attachment the fragment function writes its alpha to (`LoweringInputs::rotated_colors`, + /// whose rotation puts Metal's alpha in the image's red), whose write mask's alpha bit, clear + /// color's alpha and blend (Metal's alpha factors and operation, each factor that reads an + /// alpha reading the red it lands in, `pipeline::rotated_blend::alpha_in_red_blend`) the + /// consumer and link move to red. Metal stores, reads, masks, clears, blends and resolves + /// `A8Unorm` exactly so (probe `a8`, an M3 Max under macOS 27.0.1: kernel and render writes + /// store the alpha, every read is `(0, 0, 0, a)`, only the alpha bit of a write mask writes, + /// each alpha factor reads alphas, and a 4-sample resolve is `R8Unorm`'s). An output to such + /// an attachment holds Metal's alpha in the image's alpha lane too, which alpha to coverage + /// reads, and a fetch of one reads its red as Metal's alpha, `(0, 0, 0, r)` + /// (`LoweringInputs::alpha_in_red_colors`; probe `a8`'s uses: Metal's coverage through an + /// `A8Unorm` attachment 0 is `RGBA8Unorm`'s of the same alpha, and its fetch `(0, 0, 0, a)`). + /// A texture buffer's bytes take an `R8_UNORM` view wherever `A8_UNORM` does not serve its use + /// (`texel_buffer_alpha_in_red`), and an argument buffer holds a storage texture of it as its + /// `R8_UNORM` image, whose texels a heap read or write converts where the handle carries + /// `A8Unorm`'s class (`bind::heap`; probe `a8`'s argument buffers: a member reads `(0, 0, 0, a)` + /// and a write stores its alpha). Admitted for the image usages. + AlphaInRed, /// A stencil-only format held in a combined depth/stencil format; only the stencil aspect is /// used. Exact. StencilInCombined, @@ -192,6 +215,15 @@ impl FormatEmulation { usage, U::SampledImage | U::SampledImageFilterLinear | U::SampledImageFilterMinmax ), + FormatEmulation::AlphaInRed => matches!( + usage, + U::SampledImage + | U::SampledImageFilterLinear + | U::SampledImageFilterMinmax + | U::StorageImage + | U::ColorAttachment + | U::ColorAttachmentBlend + ), FormatEmulation::RotatedView => matches!( usage, U::SampledImage @@ -1158,6 +1190,57 @@ pub fn rotated_channels(pf: PixelFormat) -> bool { } } +/// Whether a texture of `pf` holds Metal's alpha in its image's red on `profile` +/// ([`FormatEmulation::AlphaInRed`]: `A8Unorm` on a device that holds no `A8_UNORM` image, for +/// sampling, storage or attachments): its image is [`alpha_in_red_format`]'s for every use, its +/// storage choice `StorageImageClass::AlphaInRed`, and a color attachment of it takes the +/// function's output, its clear color and its write mask through [`to_rotated_image`] as +/// [`rotated_channels`]' formats do (the rotation's red is Metal's alpha), and its blend in red +/// (`pipeline::rotated_blend::alpha_in_red_blend`). +pub fn alpha_in_red(pf: PixelFormat, profile: &DeviceProfile) -> bool { + let held = |own: vk::Format| { + [ + FormatUsage::SampledImage, + FormatUsage::StorageImage, + FormatUsage::ColorAttachment, + ] + .into_iter() + .any(|usage| profile.supports_format(own, usage)) + }; + alpha_in_red_format(pf).is_some() && direct_format(pf).is_some_and(|own| !held(own)) +} + +/// The format a texel buffer view of a texture buffer of `pf` takes for `usage` (a texel buffer +/// usage) on `profile` where the format's own does not serve it and the bytes hold Metal's alpha in +/// red ([`FormatEmulation::AlphaInRed`]): `R8_UNORM` for `A8Unorm` on a device that views no +/// `A8_UNORM` texels for the usage (a Vulkan 1.2 device without `VK_KHR_maintenance5`), where it +/// views `R8_UNORM` ones. A view reads `(r, 0, 0, 1)` where Metal reads `(0, 0, 0, r)`: a storage +/// view's reads and writes convert by its choice's class (`StorageImageClass::AlphaInRed`, +/// [`storage_choice`]), and a uniform view's reads take the alpha from red through the slot's +/// swizzle (`TextureSwizzleChannels::alpha_in_red`). `None` elsewhere. +pub(crate) fn texel_buffer_alpha_in_red( + pf: PixelFormat, + usage: FormatUsage, + profile: &DeviceProfile, +) -> Option { + let own = direct_format(pf)?; + let held = alpha_in_red_format(pf)?; + (!profile.supports_format(own, usage) && profile.supports_format(held, usage)).then_some(held) +} + +/// The format of `pf`'s image where the device holds no image of its direct format and `pf` +/// holds Metal's alpha in red ([`FormatEmulation::AlphaInRed`]): `R8_UNORM` for `A8Unorm`, +/// `None` for every other format. +pub fn alpha_in_red_format(pf: PixelFormat) -> Option { + match repr(pf) { + Repr::Candidates(_, candidates) => candidates + .iter() + .find(|c| c.emulation == FormatEmulation::AlphaInRed) + .map(|c| c.format), + Repr::NotImplemented | Repr::NotAFormat => None, + } +} + /// The candidate of an RGBX format held in its RGBA twin `format` /// ([`FormatEmulation::XChannel`]): sampled through a view that reads alpha as one. fn x_channel_twin(format: vk::Format) -> Repr { @@ -1236,7 +1319,7 @@ fn make_repr(pf: PixelFormat) -> Repr { match pf { P::Invalid | P::Unspecialized => Repr::NotAFormat, // Metal presents (0, 0, 0, a), as `VK_FORMAT_A8_UNORM` does (core 1.4 or - // `VK_KHR_maintenance5`). Without it, sampling reads the byte as red. + // `VK_KHR_maintenance5`). Without it, the byte is `R8_UNORM`'s, its alpha in red. P::A8Unorm => color(vec![ direct(F::A8_UNORM), Candidate { @@ -1247,7 +1330,7 @@ fn make_repr(pf: PixelFormat) -> Repr { b: S::ZERO, a: S::R, }, - emulation: E::SwizzledView, + emulation: E::AlphaInRed, }, ]), P::R8Unorm => one(F::R8_UNORM), @@ -1582,8 +1665,9 @@ pub fn vk_format( /// The swizzle, over the channels of `own`, through which a texture of `own` reads what a view /// of `pf` made with `swizzle` reads, where `pf` holds its texels in the very bits of `own`'s and /// presents them in other channels: `own` samples as its direct Vulkan format on `profile`, and -/// one of `pf`'s candidates is [`FormatEmulation::SwizzledView`] of that format (`A8Unorm` over -/// `R8Unorm`, read through `(Zero, Zero, Zero, Red)`). Exact for sampling and reads as that +/// one of `pf`'s candidates is [`FormatEmulation::SwizzledView`] or +/// [`FormatEmulation::AlphaInRed`] of that format (`A8Unorm` over `R8Unorm`, read through +/// `(Zero, Zero, Zero, Red)`). Exact for sampling and reads as that /// emulation is: the same bits, the same filter, the channels moved by the view's mapping, which /// Vulkan applies to gathered texels and border texels as to any other ("Texel Input Operations": /// replacement, then the component swizzle). `None` elsewhere, for `pf` equal to `own`, where @@ -1616,9 +1700,12 @@ pub fn swizzle_over( return None; } let (_, candidates) = candidates(pf).ok()?; - let candidate = candidates - .iter() - .find(|c| c.emulation == FormatEmulation::SwizzledView && c.format == image.format)?; + let candidate = candidates.iter().find(|c| { + matches!( + c.emulation, + FormatEmulation::SwizzledView | FormatEmulation::AlphaInRed + ) && c.format == image.format + })?; let mapping = swizzle.compose(candidate.components); if view_mapping_gap(mapping, profile).is_some() { return None; @@ -2622,6 +2709,10 @@ pub fn storage_image_choice( /// `SrgbEncode` (`BGRA8Unorm_sRGB`, where its twin is not accessed without a format, through /// `R8G8B8A8_UNORM` with `SrgbEncodeBgra`), `RGB9E5Float` through `R32_UINT` with /// `SharedExponentBits`, and `A8Unorm` through `R8_UNORM` with `AlphaInRed` (no alias: such a +/// texture's image is `R8_UNORM` itself, [`FormatEmulation::AlphaInRed`]; a texture buffer's bytes +/// take that view wherever `A8_UNORM` does not serve the use, [`texel_buffer_alpha_in_red`]). +/// Anything else is `Unsupported{Format}` naming what each route lacks, a format's without-format +/// usage included. /// /// An RGBX format's choice ([`x_channel`]) is its RGBA twin's, which converts its texels in the /// shader (`StorageImageChoice::x_channel`); its texture buffer, whose reads a texel buffer's view @@ -2690,6 +2781,12 @@ fn held_storage_choice( Some((F::A2B10G10R10_UNORM_PACK32, StorageImageClass::SwizzleBgra)) } PixelFormat::ARGB8Unorm => Some((F::R8G8B8A8_UNORM, StorageImageClass::RotateArgb)), + // `A8Unorm`'s byte in red, where the device holds no `A8_UNORM`: an image of its own. A + // texture buffer's bytes take the view wherever `A8_UNORM` does not serve the use, whatever + // the device's images hold (a texel buffer's view names its format alone). + PixelFormat::A8Unorm if use_.texel_buffer || alpha_in_red(pf, profile) => { + Some((F::R8_UNORM, StorageImageClass::AlphaInRed)) + } PixelFormat::RGB9E5Float => Some((F::R32_UINT, StorageImageClass::SharedExponentBits)), PixelFormat::R8UnormSRGB => Some((F::R8_UNORM, StorageImageClass::SrgbEncode)), PixelFormat::RG8UnormSRGB => Some((F::R8G8_UNORM, StorageImageClass::SrgbEncode)), @@ -2735,8 +2832,11 @@ fn held_storage_choice( for (view, class) in alias.into_iter().chain(second) { if storage(view) && declarable(view) { let mut choice = StorageImageChoice::new(view, class); - // `ARGB8Unorm`'s image is the view's format: its choice rotates without an alias. - choice.alias = (view != image).then(|| AliasView::new(image)); + // `ARGB8Unorm`'s image is the view's format: its choice rotates without an alias. So is + // the image of an `A8Unorm` texture held in red, whose `R8_UNORM` views no `A8_UNORM` + // image (a class of its own). + let own = view == image || class == StorageImageClass::AlphaInRed; + choice.alias = (!own).then(|| AliasView::new(image)); return Ok(choice); } } @@ -2824,9 +2924,9 @@ pub fn storage_view_formats(pf: PixelFormat, profile: &DeviceProfile) -> Vec Some(choice.vk_format), - None => direct_format(pf), + let format = match (choice.alias, choice.class) { + (Some(_), _) | (None, StorageImageClass::AlphaInRed) => Some(choice.vk_format), + (None, _) => direct_format(pf), }; if let Some(format) = format { if !formats.contains(&format) { diff --git a/crates/metal2vulkan/src/metal/format/tests.rs b/crates/metal2vulkan/src/metal/format/tests.rs index 0e535e2c2..88c601fe5 100644 --- a/crates/metal2vulkan/src/metal/format/tests.rs +++ b/crates/metal2vulkan/src/metal/format/tests.rs @@ -187,7 +187,7 @@ fn swap_red_blue(name: &str) -> String { } /// Every swizzled twin is the direct format with red and blue exchanged in the same bit layout -/// (or `A8Unorm`'s single byte read as red), and its mapping moves the channels back. +/// (or `A8Unorm`'s single byte held in red), and its mapping moves the channels back. #[test] fn swizzled_twins_share_the_bit_layout() { use vk::ComponentSwizzle as S; @@ -198,7 +198,9 @@ fn swizzled_twins_share_the_bit_layout() { for c in candidates.iter().filter(|c| { matches!( c.emulation, - FormatEmulation::SwizzledView | FormatEmulation::RotatedView + FormatEmulation::SwizzledView + | FormatEmulation::RotatedView + | FormatEmulation::AlphaInRed ) }) { // `ARGB8Unorm`'s bytes through a rotating view. @@ -552,47 +554,70 @@ fn mandatory_formats_map_on_every_committed_profile() { } /// `A8Unorm` is `A8_UNORM` where the profile exposes and supports it (Vulkan's alpha format reads -/// (0, 0, 0, a), as Metal does); elsewhere sampling reads the byte as red through a swizzled -/// `R8_UNORM` view, and other usages name what exposes `A8_UNORM`. +/// (0, 0, 0, a), as Metal does); elsewhere its byte is `R8_UNORM`'s, its alpha in red +/// (`FormatEmulation::AlphaInRed`), for sampling through `(Zero, Zero, Zero, R)`, storage, color +/// attachments and their blend; a usage neither format has names what each lacks. #[test] -fn a8_is_direct_where_exposed_and_samples_as_red_elsewhere() { +fn a8_is_direct_where_exposed_and_holds_alpha_in_red_elsewhere() { use FormatUsage as U; let attach = SAMPLED | vk::FormatFeatureFlags::COLOR_ATTACHMENT; - let table = [ - (vk::Format::R8_UNORM, SAMPLED), - (vk::Format::A8_UNORM, attach), - ]; + let red = SAMPLED + | vk::FormatFeatureFlags::STORAGE_IMAGE + | vk::FormatFeatureFlags::COLOR_ATTACHMENT + | vk::FormatFeatureFlags::COLOR_ATTACHMENT_BLEND; + let table = [(vk::Format::R8_UNORM, red), (vk::Format::A8_UNORM, attach)]; // The 1.2 floor without `VK_KHR_maintenance5`: the listed `A8_UNORM` is not exposed, so the // profile does not hold it. let floor = device(floor_with(&table)); assert!(!floor .profile() .supports_format(vk::Format::A8_UNORM, U::SampledImage)); - let m = vk_format( - PixelFormat::A8Unorm, - &usages(&[U::SampledImage]), - floor.profile(), - ) - .unwrap(); - assert_eq!(m.format, vk::Format::R8_UNORM); - assert_eq!(m.emulation, FormatEmulation::SwizzledView); - assert_eq!(m.components.a, vk::ComponentSwizzle::R); - for u in [U::ColorAttachment, U::StorageImage] { - assert_eq!( - vk_format(PixelFormat::A8Unorm, &usages(&[u]), floor.profile()), - Err(Unsupported::needs_any_of( - Feature::Format, - vec![vec![ + for set in [ + &[U::SampledImage][..], + &[U::StorageImage], + &[U::ColorAttachment], + &[U::ColorAttachment, U::ColorAttachmentBlend, U::SampledImage], + ] { + let m = vk_format(PixelFormat::A8Unorm, &usages(set), floor.profile()).unwrap(); + assert_eq!(m.format, vk::Format::R8_UNORM, "{set:?}"); + assert_eq!(m.emulation, FormatEmulation::AlphaInRed, "{set:?}"); + assert_eq!(m.components.a, vk::ComponentSwizzle::R, "{set:?}"); + } + assert!(alpha_in_red(PixelFormat::A8Unorm, floor.profile())); + assert!(!alpha_in_red(PixelFormat::R8Unorm, floor.profile())); + assert_eq!( + alpha_in_red_format(PixelFormat::A8Unorm), + Some(vk::Format::R8_UNORM) + ); + assert_eq!(alpha_in_red_format(PixelFormat::R8Unorm), None); + // Neither format renders: the refusal names what each lacks. + let sampled_red = device(floor_with(&[(vk::Format::R8_UNORM, SAMPLED)])); + assert_eq!( + vk_format( + PixelFormat::A8Unorm, + &usages(&[U::ColorAttachment]), + sampled_red.profile() + ), + Err(Unsupported::needs_any_of( + Feature::Format, + vec![ + vec![ Capability::Extension(VkExtension::KhrMaintenance5), Capability::Format { format: vk::Format::A8_UNORM, - usage: u + usage: U::ColorAttachment } - ]] - ) - .into()) - ); - } + ], + vec![Capability::Format { + format: vk::Format::R8_UNORM, + usage: U::ColorAttachment + }], + ] + ) + .into()) + ); + // Still a device that holds `A8Unorm` in red: its attachments are what the device lacks. + assert!(alpha_in_red(PixelFormat::A8Unorm, sampled_red.profile())); // With the extension (and its 1.2 requirement), the direct format. let mut desc = floor_with(&table); desc.extensions.extend([ @@ -609,22 +634,7 @@ fn a8_is_direct_where_exposed_and_samples_as_red_elsewhere() { assert_eq!(m.emulation, FormatEmulation::Direct); assert_eq!(m.components, vk::ComponentMapping::IDENTITY); } - // Exposed but without the usage: only the format pair is missing. - assert_eq!( - vk_format( - PixelFormat::A8Unorm, - &usages(&[U::StorageImage]), - m5.profile() - ), - Err(Unsupported::needs_any_of( - Feature::Format, - vec![vec![Capability::Format { - format: vk::Format::A8_UNORM, - usage: U::StorageImage - }]] - ) - .into()) - ); + assert!(!alpha_in_red(PixelFormat::A8Unorm, m5.profile())); // Vulkan 1.4 exposes it in core. let mut desc = floor_with(&table); desc.api_version = ApiVersion { major: 1, minor: 4 }; @@ -638,6 +648,24 @@ fn a8_is_direct_where_exposed_and_samples_as_red_elsewhere() { assert_eq!(m.format, vk::Format::A8_UNORM); } +/// An `A8Unorm` storage texture on a device that stores no `A8_UNORM` is its `R8_UNORM` image +/// itself, read as alpha and written from alpha by the shader (`StorageImageClass::AlphaInRed`), +/// with no alias. +#[test] +fn a8_storage_is_its_red_image_without_a8_unorm() { + let red = SAMPLED | vk::FormatFeatureFlags::STORAGE_IMAGE; + let table = [(vk::Format::R8_UNORM, red), (vk::Format::A8_UNORM, red)]; + let floor = device(floor_with(&table)); + let c = storage_image_choice(PixelFormat::A8Unorm, floor.profile()).unwrap(); + assert_eq!(c.vk_format, vk::Format::R8_UNORM); + assert_eq!(c.class, StorageImageClass::AlphaInRed); + assert_eq!(c.alias, None); + assert_eq!( + storage_view_formats(PixelFormat::A8Unorm, floor.profile()), + vec![vk::Format::R8_UNORM] + ); +} + /// A `BGRA8Unorm_sRGB` storage texture is its `B8G8R8A8_UNORM` twin's encode view where the device /// accesses the twin without a format (SPIR-V names no BGRA image format), and else an /// `R8G8B8A8_UNORM` view that encodes and exchanges red and blue (`SrgbEncodeBgra`), which every @@ -1189,7 +1217,9 @@ fn swizzled_views_read_metal_s_opaque_black_border() { for c in candidates.iter().filter(|c| { matches!( c.emulation, - FormatEmulation::SwizzledView | FormatEmulation::RotatedView + FormatEmulation::SwizzledView + | FormatEmulation::RotatedView + | FormatEmulation::AlphaInRed ) }) { let device = crate::metal::sampler::device_opaque_black(c.format, c.components, false); @@ -1439,38 +1469,9 @@ fn storage_choices_follow_d25() { .into()) ); - // A8Unorm's storage image is `A8_UNORM` itself (the swizzled `R8_UNORM` view is sampling - // only: a storage image ignores the swizzle), so without `VK_KHR_maintenance5` it is refused - // even though R8_UNORM is storage-capable and declarable as `R8`. - let a8_lacks = |formatless: bool| { - let mut need = vec![ - Capability::Extension(VkExtension::KhrMaintenance5), - Capability::Format { - format: vk::Format::A8_UNORM, - usage: FormatUsage::StorageImage, - }, - ]; - // No SPIR-V image format declares it: the device's features, or with them the format's - // without-format usages, which a format the device does not expose has none of. - if formatless { - need.extend([ - Capability::Format { - format: vk::Format::A8_UNORM, - usage: FormatUsage::StorageImageReadWithoutFormat, - }, - Capability::Format { - format: vk::Format::A8_UNORM, - usage: FormatUsage::StorageImageWriteWithoutFormat, - }, - ]); - } else { - need.extend([ - Capability::Feature(VkFeature::ShaderStorageImageReadWithoutFormat), - Capability::Feature(VkFeature::ShaderStorageImageWriteWithoutFormat), - ]); - } - Err(Unsupported::needs_any_of(Feature::Format, vec![need]).into()) - }; + // Without `VK_KHR_maintenance5` an `A8Unorm` texture is an `R8_UNORM` image holding its alpha + // in red, which the storage choice reads and writes as alpha (`AlphaInRed`), typed as `R8`. + let held_in_red = StorageImageChoice::new(vk::Format::R8_UNORM, StorageImageClass::AlphaInRed); let typed_r8 = device(floor_with(&[(vk::Format::R8_UNORM, storage)])); assert_eq!( choice(PixelFormat::R8Unorm, &typed_r8), @@ -1479,7 +1480,7 @@ fn storage_choices_follow_d25() { StorageImageClass::Identity )) ); - assert_eq!(choice(PixelFormat::A8Unorm, &typed_r8), a8_lacks(false)); + assert_eq!(choice(PixelFormat::A8Unorm, &typed_r8), Ok(held_in_red)); // Formatless: every storage-capable format of one numeric type shares the `Unknown` identity // key, which keeps the type. @@ -1517,6 +1518,7 @@ fn storage_choices_follow_d25() { choice(PixelFormat::RGBA16Sint, &formatless), Ok(unknown(SampledType::Sint)) ); + assert_eq!(choice(PixelFormat::A8Unorm, &formatless), Ok(held_in_red)); // bgra8 sRGB's UNORM twin is not accessed without a format here (no `VkFormatProperties3`): // both conversions through rgba8. assert_eq!( diff --git a/crates/metal2vulkan/src/metal/mod.rs b/crates/metal2vulkan/src/metal/mod.rs index b759f9b16..282e44869 100644 --- a/crates/metal2vulkan/src/metal/mod.rs +++ b/crates/metal2vulkan/src/metal/mod.rs @@ -374,6 +374,26 @@ impl TextureSwizzleChannels { a: channel(3, self.alpha), } } + + /// This swizzle of the texel `(0, 0, 0, a)` an `A8Unorm` texture buffer reads, as a swizzle + /// of the texel `(a, 0, 0, 1)` its bytes' `R8_UNORM` view reads + /// (`metal::format::texel_buffer_alpha_in_red`): each channel taken from red, green or blue is + /// zero, one taken from alpha the view's red, and `Zero` and `One` stay. + pub(crate) fn alpha_in_red(self) -> TextureSwizzleChannels { + let held = |s: TextureSwizzle| match s { + TextureSwizzle::Red | TextureSwizzle::Green | TextureSwizzle::Blue => { + TextureSwizzle::Zero + } + TextureSwizzle::Alpha => TextureSwizzle::Red, + constant => constant, + }; + TextureSwizzleChannels { + red: held(self.red), + green: held(self.green), + blue: held(self.blue), + alpha: held(self.alpha), + } + } } impl Default for TextureSwizzleChannels { diff --git a/crates/metal2vulkan/src/metal/sampler.rs b/crates/metal2vulkan/src/metal/sampler.rs index 65c7a18e1..2d1fc7983 100644 --- a/crates/metal2vulkan/src/metal/sampler.rs +++ b/crates/metal2vulkan/src/metal/sampler.rs @@ -1748,7 +1748,7 @@ mod tests { b: S::ZERO, a: S::R, }, - FormatEmulation::SwizzledView, + FormatEmulation::AlphaInRed, ); let mut black = metal_default(); black.t_address_mode = SamplerAddressMode::ClampToBorderColor; diff --git a/crates/metal2vulkan/src/metal/state.rs b/crates/metal2vulkan/src/metal/state.rs index c71b2d4c3..b6162f817 100644 --- a/crates/metal2vulkan/src/metal/state.rs +++ b/crates/metal2vulkan/src/metal/state.rs @@ -119,6 +119,10 @@ pub fn blend_state( /// [`blend_state`] without the portability subset's constant-alpha check, which link applies only /// to an attachment the draw can write. +/// +/// An `A8Unorm` attachment has no color channel, so its color equation blends nothing: it takes +/// the alpha operation there too, which a driver that blends the format's one channel by the +/// color operation (lavapipe, Mesa 26.2: with the alpha factors) then applies as Metal does. pub(crate) fn blend_factors( attachment: &ColorAttachmentDescriptor, profile: &DeviceProfile, @@ -126,10 +130,14 @@ pub(crate) fn blend_factors( if !attachment.blending_enabled { return Ok(None); } + let color_op = match attachment.pixel_format { + PixelFormat::A8Unorm => attachment.alpha_blend_operation, + _ => attachment.rgb_blend_operation, + }; Ok(Some(BlendState { src_color: blend_factor(attachment.source_rgb_blend_factor, profile)?, dst_color: blend_factor(attachment.destination_rgb_blend_factor, profile)?, - color_op: blend_op(attachment.rgb_blend_operation)?, + color_op: blend_op(color_op)?, src_alpha: blend_factor(attachment.source_alpha_blend_factor, profile)?, dst_alpha: blend_factor(attachment.destination_alpha_blend_factor, profile)?, alpha_op: blend_op(attachment.alpha_blend_operation)?, @@ -587,6 +595,15 @@ mod tests { vk::BlendOp::ADD ) ); + // An `A8Unorm` attachment, which has no color channel, takes its alpha operation in + // both equations. + att.pixel_format = PixelFormat::A8Unorm; + att.alpha_blend_operation = BlendOperation::ReverseSubtract; + let b = blend_state(&att, without.profile()).unwrap().unwrap(); + assert_eq!( + (b.color_op, b.alpha_op), + (vk::BlendOp::REVERSE_SUBTRACT, vk::BlendOp::REVERSE_SUBTRACT) + ); } #[test] diff --git a/crates/metal2vulkan/src/metal/texel_format.rs b/crates/metal2vulkan/src/metal/texel_format.rs index f4babcdcf..385111800 100644 --- a/crates/metal2vulkan/src/metal/texel_format.rs +++ b/crates/metal2vulkan/src/metal/texel_format.rs @@ -891,6 +891,16 @@ pub fn heap_one_bit_indices() -> Vec { .collect() } +/// The index in [`heap_classes`] of `A8Unorm`'s class, which no other format's texture carries: +/// a storage read or write through a heap handle carrying it converts the member's texels where +/// the device holds such a texture's alpha in red (`metal::format::alpha_in_red`), which a heap's +/// storage array views without a component mapping. A swizzled `A8Unorm` texture that reads as +/// none carries it too; another swizzle's class is `OTHER`, which a heap's storage array does not +/// hold there (`bind::heap`'s storage elements). +pub fn heap_alpha_in_red_index() -> u32 { + heap_class_index(PixelFormat::A8Unorm, TextureSwizzleChannels::DEFAULT) +} + /// Whether a texture of pixel format `pf` holds 16-bit float channels of its own: its class is /// the half-float family's without a packed field ([`heap_half_indices`]' classes), so a written /// `half` stores its NaN there as the half's own bits, and elsewhere as the conversion of @@ -1485,6 +1495,33 @@ mod tests { assert!(rgba8 != 0 && r32 != 0 && rgba8 != r32); } + /// `A8Unorm`'s heap class index, which a heap storage access tests to convert a member held in + /// red, names no other format's texture, swizzled or not, nor `OTHER`. + #[test] + fn the_alpha_in_red_heap_class_is_a8_unorms_alone() { + use crate::metal::TextureSwizzle as S; + let a8 = heap_alpha_in_red_index(); + assert_ne!(heap_classes()[a8 as usize], TexelFormat::OTHER.0); + let swizzles = [ + TextureSwizzleChannels::DEFAULT, + TextureSwizzleChannels::new(S::Blue, S::Green, S::Red, S::Alpha), + TextureSwizzleChannels::new(S::Alpha, S::Alpha, S::Alpha, S::Alpha), + TextureSwizzleChannels::new(S::Red, S::Red, S::Red, S::One), + ]; + for &pf in PixelFormat::ALL { + if pf == PixelFormat::A8Unorm { + continue; + } + for swizzle in swizzles { + assert_ne!(heap_class_index(pf, swizzle), a8, "{pf:?} {swizzle:?}"); + } + } + let alpha_only = TextureSwizzleChannels::new(S::Zero, S::Zero, S::Zero, S::Alpha); + assert_eq!(heap_class_index(PixelFormat::A8Unorm, alpha_only), a8); + let moved = TextureSwizzleChannels::new(S::Alpha, S::Zero, S::Zero, S::One); + assert_ne!(heap_class_index(PixelFormat::A8Unorm, moved), a8); + } + /// The half-float heap classes a float write tests by index are the unswizzled half-float /// formats' and no other format's: `RGBX16Float`'s too, `RGBA16Float`'s texels with three /// channels, whose writes take the half class as its twin's. diff --git a/crates/metal2vulkan/src/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index faf15c644..f6858aab2 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -408,6 +408,7 @@ mod serde_round_trips { shader_stencil: true, window_depth_varying: true, rotated_colors: BTreeSet::from([4]), + alpha_in_red_colors: BTreeSet::from([4]), rotated_factors: BTreeMap::from([( 4, [ diff --git a/crates/metal2vulkan/src/pipeline/color_writes.rs b/crates/metal2vulkan/src/pipeline/color_writes.rs index 50eddad9c..12b2c2e50 100644 --- a/crates/metal2vulkan/src/pipeline/color_writes.rs +++ b/crates/metal2vulkan/src/pipeline/color_writes.rs @@ -362,7 +362,8 @@ fn metal_stored(c: &ColorAttachmentDescriptor) -> Option<[Option; /// ([`wanted_extended_range`]), and every color it stores nowhere (`StageIo::unattached_colors`) /// has no attachment and is not color 0 under alpha to coverage, and the second outputs it writes /// for rotated attachments are the pipeline's ([`wanted_rotated_factors`]), and so are the forms of -/// their blends ([`wanted_rotated_blends`]), and the pipeline takes the `half` outputs it computes +/// their blends ([`wanted_rotated_blends`]), and the attachments holding Metal's alpha in red it +/// writes or reads are the pipeline's ([`wanted_alpha_in_red`]), and the pipeline takes the `half` outputs it computes /// at `float` precision as it compiled them ([`half_output_lanes_hold`]), and its texture writes /// that Metal's mode 2 stores otherwise compiled under the pipeline's `textureWriteRoundingMode` /// (`StageIo::texture_write_rounding`), else `NeedsInput(ColorWrites)`. @@ -383,7 +384,8 @@ pub(crate) fn check( && wanted_extended_range(fragment, colors, rounding) == io.extended_range_colors && wanted_word_colors(fragment, colors, alpha_to_coverage, p) == io.word_colors && wanted_srgb_fetches(fragment, colors) == io.srgb_fetches - && wanted_rotated(fragment, colors) == io.rotated_colors + && wanted_rotated(fragment, colors, p) == io.rotated_colors + && wanted_alpha_in_red(fragment, colors, p) == io.alpha_in_red_colors && wanted_rotated_factors(fragment, colors, p) == io.rotated_factors && wanted_rotated_blends(fragment, colors, p) == io.rotated_blends && half_output_lanes_hold(fragment, colors) @@ -613,13 +615,23 @@ pub(crate) fn wanted_word_colors( } /// The color attachments of a render pipeline whose color attachments are `colors` held with -/// their channels rotated, by color index (`LoweringInputs::rotated_colors`): every attachment -/// of a format `metal::format::rotated_channels` names (`ARGB8Unorm`). -pub(crate) fn rotated_colors(colors: &[Option]) -> BTreeSet { +/// their channels rotated on `p`, by color index (`LoweringInputs::rotated_colors`): every +/// attachment of a format `metal::format::rotated_channels` names (`ARGB8Unorm`), and every one +/// whose image holds Metal's alpha in red (`metal::format::alpha_in_red`: `A8Unorm` without +/// `A8_UNORM`), which the rotation's red is. +pub(crate) fn rotated_colors( + colors: &[Option], + p: &DeviceProfile, +) -> BTreeSet { colors .iter() .enumerate() - .filter(|(_, c)| c.is_some_and(|c| metal::format::rotated_channels(c.pixel_format))) + .filter(|(_, c)| { + c.is_some_and(|c| { + metal::format::rotated_channels(c.pixel_format) + || metal::format::alpha_in_red(c.pixel_format, p) + }) + }) .map(|(i, _)| i as u32) .collect() } @@ -630,6 +642,7 @@ pub(crate) fn rotated_colors(colors: &[Option]) -> BT pub(crate) fn wanted_rotated( fragment: &FunctionArtifact, colors: &[Option], + p: &DeviceProfile, ) -> BTreeSet { let written: BTreeSet = fragment .interface @@ -641,11 +654,64 @@ pub(crate) fn wanted_rotated( _ => None, }) .collect(); - let mut out = rotated_colors(colors); + let mut out = rotated_colors(colors, p); out.retain(|a| written.contains(a)); out } +/// The color attachments of a render pipeline whose color attachments are `colors` whose image +/// holds Metal's alpha in red on `p` (`metal::format::alpha_in_red`: `A8Unorm` without +/// `A8_UNORM`), by color index (`LoweringInputs::alpha_in_red_colors`). +pub(crate) fn alpha_in_red_colors( + colors: &[Option], + p: &DeviceProfile, +) -> BTreeSet { + colors + .iter() + .enumerate() + .filter(|(_, c)| c.is_some_and(|c| metal::format::alpha_in_red(c.pixel_format, p))) + .map(|(i, _)| i as u32) + .collect() +} + +/// The attachments holding Metal's alpha in red that the fragment stage `fragment` writes or reads +/// in a render pipeline whose color attachments are `colors` on `p`: [`alpha_in_red_colors`]'s, +/// for the attachments it writes through output variables of either dual-source index, reads +/// through an input attachment, or reads in the interlocked storage form +/// (`RuntimeFact::InterlockedFramebufferFetch`), the set it must have compiled under +/// (`StageIo::alpha_in_red_colors`). +pub(crate) fn wanted_alpha_in_red( + fragment: &FunctionArtifact, + colors: &[Option], + p: &DeviceProfile, +) -> BTreeSet { + let written = fragment + .interface + .io + .outputs + .iter() + .filter_map(|v| match v.role { + IoRole::Color { attachment, .. } => Some(attachment), + _ => None, + }); + let inputs = fragment + .interface + .descriptors + .iter() + .filter_map(|d| match d.slot.kind { + crate::pipeline::sym::ResourceKind::InputAttachment(color) => Some(color), + _ => None, + }); + let interlocked = fragment.facts.iter().filter_map(|f| match *f { + RuntimeFact::InterlockedFramebufferFetch { color, .. } => Some(color), + _ => None, + }); + let used: BTreeSet = written.chain(inputs).chain(interlocked).collect(); + let mut out = alpha_in_red_colors(colors, p); + out.retain(|a| used.contains(a)); + out +} + /// The channels of the color attachments `colors` that take a fragment function's `half` output /// at `float` precision where Metal computes its last operation so, by color index /// (`LoweringInputs::half_output_lanes`): each attachment of a 32-bit float format whose every diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 294d86505..08c7a66d2 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -1790,6 +1790,9 @@ pub(crate) fn fragment_inputs( ); out.word_colors = crate::pipeline::color_writes::word_colors(d.color_attachments, d.alpha_to_coverage, p); + out.rotated_colors = crate::pipeline::color_writes::rotated_colors(d.color_attachments, p); + out.alpha_in_red_colors = + crate::pipeline::color_writes::alpha_in_red_colors(d.color_attachments, p); out.rotated_factors = crate::pipeline::color_writes::rotated_factors(d.color_attachments, p); out.rotated_blends = crate::pipeline::color_writes::rotated_blends(d.color_attachments, p); out.sample_mask = d.sample_mask; diff --git a/crates/metal2vulkan/src/pipeline/compile/key.rs b/crates/metal2vulkan/src/pipeline/compile/key.rs index ee69c538c..aa195b085 100644 --- a/crates/metal2vulkan/src/pipeline/compile/key.rs +++ b/crates/metal2vulkan/src/pipeline/compile/key.rs @@ -240,6 +240,11 @@ pub fn function_key( .bytes(format!("{:?}", inputs.rotated_colors).as_bytes()); } // Appended only when set, as `storage_view_slots`. + if !inputs.alpha_in_red_colors.is_empty() { + h.bytes(b"alpha-in-red-colors") + .bytes(format!("{:?}", inputs.alpha_in_red_colors).as_bytes()); + } + // Appended only when set, as `storage_view_slots`. if !inputs.rotated_factors.is_empty() { h.bytes(b"rotated-factors") .bytes(format!("{:?}", inputs.rotated_factors).as_bytes()); diff --git a/crates/metal2vulkan/src/pipeline/compile/tests.rs b/crates/metal2vulkan/src/pipeline/compile/tests.rs index f3320c5ef..a1480b699 100644 --- a/crates/metal2vulkan/src/pipeline/compile/tests.rs +++ b/crates/metal2vulkan/src/pipeline/compile/tests.rs @@ -677,6 +677,7 @@ fn the_inputs_encoding_is_the_earlier_derived_debug() { .replace(", shader_stencil: false", "") .replace(", window_depth_varying: false", "") .replace(", rotated_colors: {}", "") + .replace(", alpha_in_red_colors: {}", "") .replace(", rotated_factors: {}", "") .replace(", threadgroup_size_matches_tile_size: false", "") .replace(", address_maps: {}", "") diff --git a/crates/metal2vulkan/src/pipeline/link/graphics.rs b/crates/metal2vulkan/src/pipeline/link/graphics.rs index 700f94664..367bc830e 100644 --- a/crates/metal2vulkan/src/pipeline/link/graphics.rs +++ b/crates/metal2vulkan/src/pipeline/link/graphics.rs @@ -136,7 +136,14 @@ //! coverage stays the rasterizer's, measured at 1 and 4 samples, while Vulkan requires an alpha //! output at location 0 (`VUID-VkGraphicsPipelineCreateInfo-alphaToCoverageEnable-08891`), so //! link turns it off. Over an integer attachment 0 it is Metal's pipeline error -//! (`ColorAttachment`). +//! (`ColorAttachment`). Over an `A8Unorm` attachment 0 whose image holds Metal's alpha in red +//! (`R8_UNORM`, no `A8_UNORM`), the output holds Metal's alpha in its alpha lane too +//! (`StageIo::alpha_in_red_colors`), so Vulkan's coverage, which reads the output's alpha +//! whatever the format keeps (the specification's multisample coverage section: "All alpha +//! values in this section refer only to the alpha component of the fragment shader output that +//! has a `Location` and `Index` decoration of zero"), reads Metal's alpha; +//! over an `ARGB8Unorm` one, whose image's alpha is Metal's blue, it is +//! `NotImplemented(Format)`. //! - **Vertex amplification**: `maxVertexAmplificationCount` above 1 makes a pipeline whose draws //! may be multiview, which needs `multiview`; its draws of more amplifications than the device's //! `maxMultiviewViewCount` are draws of one amplification each. A count of 0 is an invalid @@ -154,7 +161,9 @@ use crate::error::{ Attachment, Capability, DescriptorError, Error, Feature, RuntimeInput, Unsupported, }; use crate::metal; -use crate::metal::format::{color_output_components, sampled_type, vk_format, ExtendedRange}; +use crate::metal::format::{ + color_output_components, sampled_type, vk_format, ExtendedRange, FormatEmulation, +}; use crate::metal::state::{ blend_factors, check_constant_alpha, color_write_mask, constant_alpha_withheld, }; @@ -165,7 +174,7 @@ use crate::pipeline::graphics::{ }; use crate::pipeline::interface::StageInterface; use crate::pipeline::link::RenderLinkInputs; -use crate::pipeline::rotated_blend::{rotated_blend, RotatedBlend}; +use crate::pipeline::rotated_blend::{alpha_in_red_blend, rotated_blend, RotatedBlend}; use crate::pipeline::stage_io::{ CoverageLoop, Interpolation, IoNumeric, IoRole, Sampling, StageBuiltin, StageIo, }; @@ -389,8 +398,11 @@ pub fn graphics_state( let input_blend = input_blends.get(&(index as u32)).copied(); // An attachment held with its channels rotated takes the function's rotated // output, the descriptor's mask rotated, and the blend `rotated_blend` - // finds Metal's in Vulkan's factors. - let rotated = metal::format::rotated_channels(a.pixel_format); + // finds Metal's in Vulkan's factors; one holding Metal's alpha in red + // (`A8Unorm` in `R8_UNORM`) the rotated output too, whose red is Metal's + // alpha, the mask's alpha bit in red, and Metal's alpha blend in red. + let alpha_red = metal::format::alpha_in_red(a.pixel_format, p); + let rotated = metal::format::rotated_channels(a.pixel_format) || alpha_red; let blended = a.blending_enabled && !replaced && input_blend.is_none(); let mut usages = BTreeSet::from([FormatUsage::ColorAttachment]); if blended { @@ -409,9 +421,10 @@ pub fn graphics_state( { return Err(Unsupported::not_implemented(Feature::Format).into()); } - let descriptor_mask = match rotated { - true => rotated_mask(descriptor_mask), - false => descriptor_mask, + let descriptor_mask = match (alpha_red, rotated) { + (true, _) => rotated_mask(descriptor_mask) & vk::ColorComponentFlags::R, + (false, true) => rotated_mask(descriptor_mask), + (false, false) => descriptor_mask, }; // An extended-range attachment holds its raw texels, whose components the // function writes whole. @@ -434,6 +447,7 @@ pub fn graphics_state( let blend = match (replaced || input_blend.is_some(), rotated) { (true, _) => None, (false, false) => blend_factors(a, p)?, + (false, true) if alpha_red => alpha_in_red_blend(a, p)?, // The second output the rotation needs is the function's only beside // a first output to the attachment; without one the draw writes nothing // there whatever the blend (its mask is empty). @@ -447,7 +461,13 @@ pub fn graphics_state( Some(RotatedBlend::Synthesized(..)) | None => None, }, }; - let format = vk_format(a.pixel_format, &usages, p)?.format; + let mapping = vk_format(a.pixel_format, &usages, p)?; + // The format holds Metal's alpha in red for these usages exactly where the + // function wrote it there (`alpha_in_red`, of the attachment usage alone). + if (mapping.emulation == FormatEmulation::AlphaInRed) != alpha_red { + return Err(Unsupported::not_implemented(Feature::Format).into()); + } + let format = mapping.format; Ok(ColorAttachmentState { format, write_mask, @@ -508,7 +528,9 @@ pub fn graphics_state( index: color, }))?; // An input attachment of an image holding Metal's channels rotated would read them - // rotated: not modelled. + // so: not modelled. (One holding Metal's alpha in red is read as Metal's alpha by a + // stage compiled for it, `StageIo::alpha_in_red_colors`, which + // `color_writes::check` holds to the pipeline's.) // Nor is a two-plane YCbCr attachment's, whose texels Metal holds as halves and the // attachment as the function's floats. if metal::format::rotated_channels(attachment.pixel_format) @@ -934,7 +956,11 @@ fn reads_alpha_to_coverage( && o.ty.components == 4 }); // An attachment 0 held with its channels rotated takes Metal's alpha in its red, where - // Vulkan's coverage reads its alpha (Metal's blue). + // Vulkan's coverage reads its alpha (Metal's blue). One holding Metal's alpha in red takes + // that alpha in its alpha lane too (`StageIo::alpha_in_red_colors`, which + // `color_writes::check` holds to the pipeline's), so the coverage reads Metal's alpha, as + // Metal's does through an `A8Unorm` attachment 0 (probe `a8`'s uses: the masks of every alpha + // in 1/32 steps at four samples are `RGBA8Unorm`'s). if reads && r.color_attachments[0].is_some_and(|a| metal::format::rotated_channels(a.pixel_format)) { diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index 300652809..88e80dce4 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -525,13 +525,28 @@ pub struct LoweringInputs { /// each such attachment's image holds Metal's alpha, red, green and blue in its red, green, /// blue and alpha, so the function writes each `float` or `half` output to it, of either /// dual-source index, rotated (`metal::format::to_rotated_image`), after Metal's conversion - /// of its channels (`color_writes`). An output of fewer than four lanes there is + /// of its channels (`color_writes`). An attachment whose image holds Metal's alpha in red + /// (`metal::format::alpha_in_red`, `A8Unorm` in `R8_UNORM`) is listed too: the rotation's red + /// is Metal's alpha (and `alpha_in_red_colors` names it). An output of fewer than four lanes + /// there is /// `NotImplemented(Format)`. `Device::compile_render_pipeline` sets it for a `Function` /// fragment stage from the pipeline's color attachments, and a fragment compiled on its own for /// such a pipeline compiles under the same set: link refuses one compiled under another as /// `NeedsInput(ColorWrites)`. Empty for any other function. #[cfg_attr(feature = "serde", serde(default))] pub rotated_colors: BTreeSet, + /// The color attachments of `rotated_colors` whose image holds Metal's alpha in red + /// (`metal::format::alpha_in_red`: `A8Unorm` in `R8_UNORM`), by color index. An output to one + /// holds Metal's alpha in the image's alpha lane as well as its red (the image keeps only the + /// red), so alpha to coverage through attachment 0 reads Metal's alpha as Metal's does; a + /// color input (`[[color(n)]]`) of one reads the image's red as Metal's alpha, `(0, 0, 0, r)`, + /// as Metal reads an `A8Unorm` attachment (probe `a8`'s uses on an M3 Max under macOS + /// 27.0.1), through the input attachment or the interlocked storage form alike. + /// `Device::compile_render_pipeline` sets it for a `Function` fragment stage from the + /// pipeline's color attachments, and link refuses a fragment compiled under another set as + /// `NeedsInput(ColorWrites)`. Empty for any other function. + #[cfg_attr(feature = "serde", serde(default))] + pub alpha_in_red_colors: BTreeSet, /// The second output (`[[color(n), index(1)]]`) the fragment function writes for an /// attachment of `rotated_colors` whose blend reads a value no channel of the image holds where /// Vulkan's factors read it (Metal's source alpha in a color factor), by color index: per @@ -1349,6 +1364,11 @@ pub enum StorageImageClass { /// An `ARGB8Unorm` image (alpha in byte 0, then red, green, and blue) viewed as /// `R8G8B8A8_UNORM`: the shader rotates the channels. RotateArgb, + /// An `A8Unorm` texture held in `R8_UNORM` (`metal::format::FormatEmulation::AlphaInRed`): + /// a read is the byte as alpha, `(0, 0, 0, r)`, and a write stores the texel's alpha, as + /// Metal's do (probe `a8`, an M3 Max under macOS 27.0.1: kernel writes of `float` and `half` + /// texels and `read_write` access). + AlphaInRed, /// A half-float image (`R16Float`, `RG16Float`, `RGBA16Float`) written by a device not /// measured to round a `float` texel as Metal does: the shader rounds each written `float` /// channel toward zero to the `half` Metal stores (a finite value past 65504 to 65504, an diff --git a/crates/metal2vulkan/src/pipeline/rotated_blend.rs b/crates/metal2vulkan/src/pipeline/rotated_blend.rs index c4af0891e..4f95442ca 100644 --- a/crates/metal2vulkan/src/pipeline/rotated_blend.rs +++ b/crates/metal2vulkan/src/pipeline/rotated_blend.rs @@ -550,5 +550,59 @@ pub(crate) fn rotated_blend( Ok(Some(RotatedBlend::Synthesized(state, lanes))) } +/// Vulkan's blend of attachment `a` on an `R8_UNORM` image holding Metal's alpha in red +/// (`metal::format::alpha_in_red`, `A8Unorm`), whose fragment output the function writes rotated +/// (the red of each output, of either dual-source index, Metal's alpha): `None` without blending, +/// and the descriptor's own errors. Metal blends `A8Unorm`'s alpha by its alpha operation and +/// factors alone, each factor reading alphas: `SourceColor` and `SourceAlpha` the source's, +/// `DestinationColor` and `DestinationAlpha` the destination's, `SourceAlphaSaturated` one, +/// `BlendColor` and `BlendAlpha` the blend color's, `Source1Color` and `Source1Alpha` the second +/// output's (probe `a8`, an M3 Max under macOS 27.0.1: every factor as source and as +/// destination, under every operation). Vulkan's color operation and factors govern the image's +/// red, where each of those alphas is that of the red it reads (the source's red, the +/// destination's, the second output's), but the blend color's, which `CONSTANT_ALPHA` reads +/// unrotated, and the saturated alpha's one. The image has no alpha, so its alpha factors are the +/// same as its color factors, read by nothing. +pub(crate) fn alpha_in_red_blend( + a: &ColorAttachmentDescriptor, + p: &DeviceProfile, +) -> Result, Error> { + // The descriptor's own errors first: a placeholder, and a `Source1` factor without + // dual-source blending. + if blend_factors(a, p)?.is_none() { + return Ok(None); + } + use vk::BlendFactor as B; + use BlendFactor as F; + let red = |f: BlendFactor| match f { + F::Zero => Some(B::ZERO), + F::One | F::SourceAlphaSaturated => Some(B::ONE), + F::SourceColor | F::SourceAlpha => Some(B::SRC_COLOR), + F::OneMinusSourceColor | F::OneMinusSourceAlpha => Some(B::ONE_MINUS_SRC_COLOR), + F::DestinationColor | F::DestinationAlpha => Some(B::DST_COLOR), + F::OneMinusDestinationColor | F::OneMinusDestinationAlpha => Some(B::ONE_MINUS_DST_COLOR), + F::BlendColor | F::BlendAlpha => Some(B::CONSTANT_ALPHA), + F::OneMinusBlendColor | F::OneMinusBlendAlpha => Some(B::ONE_MINUS_CONSTANT_ALPHA), + F::Source1Color | F::Source1Alpha => Some(B::SRC1_COLOR), + F::OneMinusSource1Color | F::OneMinusSource1Alpha => Some(B::ONE_MINUS_SRC1_COLOR), + F::Unspecialized => None, + }; + let (Some(src), Some(dst)) = ( + red(a.source_alpha_blend_factor), + red(a.destination_alpha_blend_factor), + ) else { + return Err(Unsupported::not_implemented(Feature::Format).into()); + }; + let op = blend_op(a.alpha_blend_operation)?; + Ok(Some(BlendState { + src_color: src, + dst_color: dst, + color_op: op, + src_alpha: src, + dst_alpha: dst, + alpha_op: op, + })) +} + #[cfg(test)] mod tests; diff --git a/crates/metal2vulkan/src/pipeline/rotated_blend/tests.rs b/crates/metal2vulkan/src/pipeline/rotated_blend/tests.rs index 0e0b8ba5e..a2316edc0 100644 --- a/crates/metal2vulkan/src/pipeline/rotated_blend/tests.rs +++ b/crates/metal2vulkan/src/pipeline/rotated_blend/tests.rs @@ -491,3 +491,47 @@ fn unmeasured_blends_are_announced() { assert_eq!(rotated_form(&refused, p), None); } } + +/// Every pair of Metal's alpha factors under each operation, beside color factors that would read +/// other values: Vulkan's blend [`alpha_in_red_blend`] gives an `R8_UNORM` image holding Metal's +/// alpha in red, whose function writes its outputs rotated, stores in red Metal's blend of +/// `A8Unorm`'s alpha (probe `a8`, an M3 Max under macOS 27.0.1: each alpha factor reads alphas, +/// the color factors nothing). The image's destination reads red as its own and alpha as one. +#[test] +fn an_alpha_in_red_blend_stores_metals_alpha() { + use BlendFactor as F; + use BlendOperation as O; + let p = moltenvk(); + let factors: Vec = F::ALL + .iter() + .copied() + .filter(|&f| f != F::Unspecialized) + .collect(); + let mut checked = 0; + for op in [O::Add, O::Subtract, O::ReverseSubtract, O::Min, O::Max] { + for &sa in &factors { + for &da in &factors { + let mut a = attachment( + (F::OneMinusDestinationColor, F::SourceAlphaSaturated, O::Add), + (sa, da, op), + ); + a.pixel_format = PixelFormat::A8Unorm; + let state = alpha_in_red_blend(&a, &p) + .unwrap_or_else(|e| panic!("{a:?}: {e:?}")) + .expect("blends"); + for v in texels(u64::from(sa.as_raw()) << 8 | u64::from(da.as_raw())).take(16) { + let (s, s1, d, c) = v; + let image = [d[3], 0.0, 0.0, 1.0]; + let got = vulkan_blend(&state, (rotated(s), rotated(s1), image, c)); + assert_eq!(got[0], metal_blend(&a, v)[3], "{a:?}: {state:?}"); + } + checked += 1; + } + } + } + assert_eq!(checked, 5 * factors.len() * factors.len()); + let mut off = attachment((F::One, F::Zero, O::Add), (F::One, F::Zero, O::Add)); + off.pixel_format = PixelFormat::A8Unorm; + off.blending_enabled = false; + assert_eq!(alpha_in_red_blend(&off, &p), Ok(None)); +} diff --git a/crates/metal2vulkan/src/pipeline/stage_io.rs b/crates/metal2vulkan/src/pipeline/stage_io.rs index ff5b6a39b..0b6a0584f 100644 --- a/crates/metal2vulkan/src/pipeline/stage_io.rs +++ b/crates/metal2vulkan/src/pipeline/stage_io.rs @@ -240,6 +240,15 @@ pub struct StageIo { /// refuses a stage compiled for another set than the pipeline's (`NeedsInput(ColorWrites)`). #[cfg_attr(feature = "serde", serde(default))] pub rotated_colors: std::collections::BTreeSet, + /// The attachments whose image holds Metal's alpha in red + /// (`LoweringInputs::alpha_in_red_colors`) that the fragment function writes through an output + /// variable of either dual-source index, or reads (`[[color(n)]]`) through an input attachment + /// or the interlocked storage form, by color index: each such output holds Metal's alpha in + /// the image's alpha lane too, which alpha to coverage reads, and each read takes the image's + /// red as Metal's alpha. Link refuses a stage compiled for another set than the pipeline's + /// (`NeedsInput(ColorWrites)`). + #[cfg_attr(feature = "serde", serde(default))] + pub alpha_in_red_colors: std::collections::BTreeSet, /// The second outputs the fragment function writes for attachments held with their channels /// rotated (`LoweringInputs::rotated_factors`), by color index: those of the attachments it /// writes through a first output, each with what it holds in each channel of the image. Link diff --git a/crates/metal2vulkan/src/pipeline/testing.rs b/crates/metal2vulkan/src/pipeline/testing.rs index 4bc0363ad..97a8b38bb 100644 --- a/crates/metal2vulkan/src/pipeline/testing.rs +++ b/crates/metal2vulkan/src/pipeline/testing.rs @@ -207,6 +207,9 @@ pub fn fragment_inputs( ); inputs.word_colors = crate::pipeline::color_writes::word_colors(&r.color_attachments, r.alpha_to_coverage, p); + inputs.rotated_colors = crate::pipeline::color_writes::rotated_colors(&r.color_attachments, p); + inputs.alpha_in_red_colors = + crate::pipeline::color_writes::alpha_in_red_colors(&r.color_attachments, p); inputs.half_output_lanes = crate::pipeline::color_writes::half_output_lanes(&r.color_attachments); inputs.rotated_factors = diff --git a/crates/metal2vulkan/tests/air_input/a8r_buffers.txt b/crates/metal2vulkan/tests/air_input/a8r_buffers.txt new file mode 100644 index 000000000..61d687cb8 --- /dev/null +++ b/crates/metal2vulkan/tests/air_input/a8r_buffers.txt @@ -0,0 +1,220 @@ +target triple = "air64_v28-apple-macosx26.0.0" +source_filename = "-" +; datalayout DataLayout { endian: Little, pointers: {0: PointerSpec { size_bits: 64, abi_bits: 64, pref_bits: 64, index_bits: 64 }}, ints: {1: AlignSpec { abi_bits: 8, pref_bits: 8 }, 8: AlignSpec { abi_bits: 8, pref_bits: 8 }, 16: AlignSpec { abi_bits: 16, pref_bits: 16 }, 32: AlignSpec { abi_bits: 32, pref_bits: 32 }, 64: AlignSpec { abi_bits: 64, pref_bits: 64 }}, floats: {16: AlignSpec { abi_bits: 16, pref_bits: 16 }, 32: AlignSpec { abi_bits: 32, pref_bits: 32 }, 64: AlignSpec { abi_bits: 64, pref_bits: 64 }, 128: AlignSpec { abi_bits: 128, pref_bits: 128 }}, vectors: {16: AlignSpec { abi_bits: 16, pref_bits: 16 }, 24: AlignSpec { abi_bits: 32, pref_bits: 32 }, 32: AlignSpec { abi_bits: 32, pref_bits: 32 }, 48: AlignSpec { abi_bits: 64, pref_bits: 64 }, 64: AlignSpec { abi_bits: 64, pref_bits: 64 }, 96: AlignSpec { abi_bits: 128, pref_bits: 128 }, 128: AlignSpec { abi_bits: 128, pref_bits: 128 }, 192: AlignSpec { abi_bits: 256, pref_bits: 256 }, 256: AlignSpec { abi_bits: 256, pref_bits: 256 }, 512: AlignSpec { abi_bits: 512, pref_bits: 512 }, 1024: AlignSpec { abi_bits: 1024, pref_bits: 1024 }}, aggregate: AlignSpec { abi_bits: 0, pref_bits: 64 }, native_ints: [8, 16, 32], stack_align_bits: None, alloca_space: 0, program_space: 0, globals_space: 0, mangling: None, fn_ptr_align: None, non_integral: [] } +%t4 = type void (ptr addrspace(1), ptr addrspace(1), i32) +%t9 = type <4 x float> (<4 x half>) +%t11 = type void (ptr addrspace(1), ptr addrspace(2), i32) +%t12 = type void (ptr addrspace(1), ptr addrspace(2), ptr addrspace(1), i32) +%t14 = type void (ptr addrspace(2), ptr addrspace(2), ptr addrspace(1), <2 x i32>) +%t15 = type ptr addrspace(2) () +%t17 = type { <4 x float>, i8 } +%t18 = type %t17 (ptr addrspace(1), ptr addrspace(2), i32, i32) +%t19 = type { <4 x half>, i8 } +%t20 = type %t19 (ptr addrspace(1), ptr addrspace(2), i32, i32) +%t21 = type void (ptr addrspace(1), i32, <4 x float>, i32) +%t22 = type %t17 (ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) +%t23 = type void (ptr addrspace(1), <2 x i32>, <4 x float>, i32, i32) +%t25 = type [2 x i32] +%t27 = type { ptr addrspace(1) } ; "struct.metal::texture2d" +%t28 = type { ptr addrspace(1) } ; "struct.metal::texture2d.45" +%t29 = type { %t27, %t28 } ; "struct.A8rHeld" +c15 = %t25 [27, 0] + +define %t4 @f0 "a8r_buffer_read" "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" %a0( Ref nocapture ) %a1( Mod nocapture "air-buffer-no-alias"="" ) { +bb0: + %i0 = tail call ptr addrspace(2) @f6 [air Sampler(GetReadSampler)]() + %i1 = tail call %t17 @f7 [air Texture(Texture { op: Read, image: ImageShape { dim: Buffer, array: false, ms: false, depth: false }, texel: Some(Texel { ty: NumTy { elem: F32, lanes: 4 }, sign: None }), coord16: false, form: Current, access: Some(Read) })](%a0, %i0, %a2, i32 1) arg0( Ref nocapture ) + %i2 = extractvalue <4 x float> %i1, 0 + %i3 = zext %a2 to i64 + %i4 = getelementptr inbounds <4 x float>, %a1, %i3 + store %i2, %i4, align 16 + ret void +} + +define %t4 @f1 "a8r_buffer_read_half" "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="64" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" %a0( Ref nocapture ) %a1( Mod nocapture "air-buffer-no-alias"="" ) { +bb0: + %i0 = tail call ptr addrspace(2) @f6 [air Sampler(GetReadSampler)]() + %i1 = tail call %t19 @f8 [air Texture(Texture { op: Read, image: ImageShape { dim: Buffer, array: false, ms: false, depth: false }, texel: Some(Texel { ty: NumTy { elem: F16, lanes: 4 }, sign: None }), coord16: false, form: Current, access: Some(Read) })](%a0, %i0, %a2, i32 1) arg0( Ref nocapture ) + %i2 = extractvalue <4 x half> %i1, 0 + %i3 = tail call reassoc nnan ninf nsz arcp contract afn <4 x float> @f2 [air Convert(Convert { dst: NumTy { elem: F32, lanes: 4 }, dst_kind: Float, src: NumTy { elem: F16, lanes: 4 }, src_kind: Float, src_fp8: None })](%i2) + %i4 = zext %a2 to i64 + %i5 = getelementptr inbounds <4 x float>, %a1, %i4 + store %i3, %i5, align 16 + ret void +} + +declare %t9 @f2 "air.convert.f.v4f32.f.v4f16" memory(NoModRef, NoModRef, NoModRef) + +define %t11 @f3 "a8r_buffer_write" memory(ModRef, NoModRef, NoModRef) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" %a0( nocapture ) %a1( Ref nocapture "air-buffer-no-alias"="" ) { +bb0: + %i0 = load <4 x float>, %a1, align 16 + tail call void @f9 [air Texture(Texture { op: Write, image: ImageShape { dim: Buffer, array: false, ms: false, depth: false }, texel: Some(Texel { ty: NumTy { elem: F32, lanes: 4 }, sign: None }), coord16: false, form: Current, access: Some(Write) })](%a0, %a2, %i0, i32 2) arg0( nocapture ) + ret void +} + +define %t12 @f4 "a8r_buffer_read_write" "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" %a1( Ref nocapture "air-buffer-no-alias"="" ) %a2( Mod nocapture "air-buffer-no-alias"="" ) { +bb0: + %i0 = tail call ptr addrspace(2) @f6 [air Sampler(GetReadSampler)]() + %i1 = tail call %t17 @f7 [air Texture(Texture { op: Read, image: ImageShape { dim: Buffer, array: false, ms: false, depth: false }, texel: Some(Texel { ty: NumTy { elem: F32, lanes: 4 }, sign: None }), coord16: false, form: Current, access: Some(ReadWrite) })](%a0, %i0, %a3, i32 3) arg0( Ref nocapture ) + %i2 = extractvalue <4 x float> %i1, 0 + %i3 = zext %a3 to i64 + %i4 = getelementptr inbounds <4 x float>, %a2, %i3 + store %i2, %i4, align 16 + %i6 = load <4 x float>, %a1, align 16 + tail call void @f9 [air Texture(Texture { op: Write, image: ImageShape { dim: Buffer, array: false, ms: false, depth: false }, texel: Some(Texel { ty: NumTy { elem: F32, lanes: 4 }, sign: None }), coord16: false, form: Current, access: Some(ReadWrite) })](%a0, %a3, %i6, i32 3) arg0( nocapture ) + ret void +} + +define %t14 @f5 "a8r_held" "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" %a0( align 8 dereferenceable(16) Ref nocapture "air-buffer-no-alias"="" ) %a1( Ref nocapture "air-buffer-no-alias"="" ) %a2( Mod nocapture "air-buffer-no-alias"="" ) { +bb0: + %i0 = getelementptr inbounds %t29, %a0, i64 0, i32 0, i32 0 + %i1 = load ptr addrspace(1), %i0, align 8 + %i2 = tail call ptr addrspace(2) @f6 [air Sampler(GetReadSampler)]() + %i3 = tail call %t17 @f10 [air Texture(Texture { op: Read, image: ImageShape { dim: D2, array: false, ms: false, depth: false }, texel: Some(Texel { ty: NumTy { elem: F32, lanes: 4 }, sign: None }), coord16: false, form: Current, access: Some(ReadWrite) })](%i1, %i2, %a3, <2 x i32> zeroinitializer, i32 0, i32 3) arg0( Ref nocapture ) + %i4 = extractvalue <4 x float> %i3, 0 + %i5 = extractelement %a3, i64 1 + %i6 = shl i32 %i5, i32 3 + %i7 = extractelement %a3, i64 0 + %i8 = add i32 %i6, %i7 + %i9 = zext %i8 to i64 + %i10 = getelementptr inbounds <4 x float>, %a2, %i9 + store %i4, %i10, align 16 + %i12 = load <4 x float>, %a1, align 16 + tail call void @f11 [air Texture(Texture { op: Write, image: ImageShape { dim: D2, array: false, ms: false, depth: false }, texel: Some(Texel { ty: NumTy { elem: F32, lanes: 4 }, sign: None }), coord16: false, form: Current, access: Some(ReadWrite) })](%i1, %a3, %i12, i32 0, i32 3) arg0( nocapture ) + %i14 = getelementptr inbounds <4 x float>, %a1, i64 1 + %i15 = load <4 x float>, %i14, align 16 + %i16 = getelementptr inbounds %t29, %a0, i64 0, i32 1, i32 0 + %i17 = load ptr addrspace(1), %i16, align 8 + tail call void @f11 [air Texture(Texture { op: Write, image: ImageShape { dim: D2, array: false, ms: false, depth: false }, texel: Some(Texel { ty: NumTy { elem: F32, lanes: 4 }, sign: None }), coord16: false, form: Current, access: Some(Write) })](%i17, %a3, %i15, i32 0, i32 2) arg0( nocapture ) + ret void +} + +declare %t15 @f6 "air.get_read_sampler" memory(NoModRef, Ref, NoModRef) + +declare %t18 @f7 "air.read_texture_buffer_1d.v4f32" memory(Ref, NoModRef, NoModRef) %a0( Ref nocapture ) + +declare %t20 @f8 "air.read_texture_buffer_1d.v4f16" memory(Ref, NoModRef, NoModRef) %a0( Ref nocapture ) + +declare %t21 @f9 "air.write_texture_buffer_1d.v4f32" memory(ModRef, NoModRef, NoModRef) %a0( nocapture ) + +declare %t22 @f10 "air.read_texture_2d.v4f32" memory(Ref, NoModRef, NoModRef) %a0( Ref nocapture ) + +declare %t23 @f11 "air.write_texture_2d.v4f32" memory(ModRef, NoModRef, NoModRef) %a0( nocapture ) +!md0 = !"SDK Version" +!md1 = !"wchar_size" +!md2 = !"frame-pointer" +!md3 = !"air.max_device_buffers" +!md4 = !"air.max_constant_buffers" +!md5 = !"air.max_threadgroup_buffers" +!md6 = !"air.max_textures" +!md7 = !"air.max_read_write_textures" +!md8 = !"air.max_samplers" +!md9 = !"air.texture" +!md10 = !"air.location_index" +!md11 = !"air.read" +!md12 = !"air.arg_type_name" +!md13 = !"texture_buffer" +!md14 = !"air.arg_name" +!md15 = !"t" +!md16 = !"air.buffer" +!md17 = !"air.read_write" +!md18 = !"air.address_space" +!md19 = !"air.arg_type_size" +!md20 = !"air.arg_type_align_size" +!md21 = !"float4" +!md22 = !"out" +!md23 = !"air.thread_position_in_grid" +!md24 = !"uint" +!md25 = !"g" +!md26 = !"texture_buffer" +!md27 = !"air.write" +!md28 = !"texture_buffer" +!md29 = !"color" +!md30 = !"texture_buffer" +!md31 = !"air.indirect_buffer" +!md32 = !"air.buffer_size" +!md33 = !"air.struct_type_info" +!md34 = !"texture2d" +!md35 = !"rw" +!md36 = !"air.indirect_argument" +!md37 = !"texture2d" +!md38 = !"w" +!md39 = !"A8rHeld" +!md40 = !"held" +!md41 = !"uint2" +!md42 = !"air.compile.denorms_disable" +!md43 = !"air.compile.fast_math_enable" +!md44 = !"air.compile.framebuffer_fetch_enable" +!md45 = !"Apple metal version 32023.921 (metalfe-32023.921.6)" +!md46 = !"Metal" +!md47 = !"omnipotent char" +!md48 = !"Simple C++ TBAA" +!md49 = !"air-alias-scope-arg(1)" +!md50 = !"air-alias-scope-textures" +!md51 = !"air-alias-scope-arg(2)" +!md52 = i32 2 +!md53 = %t25 c15 +!md54 = i32 1 +!md55 = i32 4 +!md56 = i32 7 +!md57 = i32 31 +!md58 = i32 128 +!md59 = i32 8 +!md60 = i32 16 +!md61 = ptr addrspace(0) @f0 +!md62 = i32 0 +!md63 = ptr addrspace(0) @f1 +!md64 = ptr addrspace(0) @f3 +!md65 = ptr addrspace(0) @f4 +!md66 = i32 3 +!md67 = ptr addrspace(0) @f5 +!md68 = i64 0 +!md69 = !{!md52, !md0, !md53} +!md70 = !{!md54, !md1, !md55} +!md71 = !{!md56, !md2, !md52} +!md72 = !{!md56, !md3, !md57} +!md73 = !{!md56, !md4, !md57} +!md74 = !{!md56, !md5, !md57} +!md75 = !{!md56, !md6, !md58} +!md76 = !{!md56, !md7, !md59} +!md77 = !{!md56, !md8, !md60} +!md78 = !{} +!md79 = !{!md62, !md9, !md10, !md62, !md54, !md11, !md12, !md13, !md14, !md15} +!md80 = !{!md54, !md16, !md10, !md54, !md54, !md17, !md18, !md54, !md19, !md60, !md20, !md60, !md12, !md21, !md14, !md22} +!md81 = !{!md52, !md23, !md12, !md24, !md14, !md25} +!md82 = !{!md79, !md80, !md81} +!md83 = !{!md61, !md78, !md82} +!md84 = !{!md62, !md9, !md10, !md62, !md54, !md11, !md12, !md26, !md14, !md15} +!md85 = !{!md84, !md80, !md81} +!md86 = !{!md63, !md78, !md85} +!md87 = !{!md62, !md9, !md10, !md62, !md54, !md27, !md12, !md28, !md14, !md15} +!md88 = !{!md54, !md16, !md10, !md62, !md54, !md11, !md18, !md52, !md19, !md60, !md20, !md60, !md12, !md21, !md14, !md29} +!md89 = !{!md87, !md88, !md81} +!md90 = !{!md64, !md78, !md89} +!md91 = !{!md62, !md9, !md10, !md62, !md54, !md17, !md12, !md30, !md14, !md15} +!md92 = !{!md52, !md16, !md10, !md54, !md54, !md17, !md18, !md54, !md19, !md60, !md20, !md60, !md12, !md21, !md14, !md22} +!md93 = !{!md66, !md23, !md12, !md24, !md14, !md25} +!md94 = !{!md91, !md88, !md92, !md93} +!md95 = !{!md65, !md78, !md94} +!md96 = !{!md62, !md9, !md10, !md62, !md54, !md17, !md12, !md34, !md14, !md35} +!md97 = !{!md54, !md9, !md10, !md54, !md54, !md27, !md12, !md37, !md14, !md38} +!md98 = !{!md62, !md59, !md62, !md34, !md35, !md36, !md96, !md59, !md59, !md62, !md37, !md38, !md36, !md97} +!md99 = !{!md62, !md31, !md32, !md60, !md10, !md52, !md54, !md11, !md18, !md52, !md33, !md98, !md19, !md60, !md20, !md59, !md12, !md39, !md14, !md40} +!md100 = !{!md66, !md23, !md12, !md41, !md14, !md25} +!md101 = !{!md99, !md88, !md92, !md100} +!md102 = !{!md67, !md78, !md101} +!md103 = !{!md42} +!md104 = !{!md43} +!md105 = !{!md44} +!md106 = !{!md45} +!md107 = !{!md52, !md59, !md62} +!md108 = !{!md46, !md55, !md62, !md62} +!md109 = !{!md48} +!md110 = !{!md47, !md109, !md68} +!md111 = !{!md110, !md110, !md68} +!"llvm.module.flags" = !{!md69, !md70, !md71, !md72, !md73, !md74, !md75, !md76, !md77} +!"air.kernel" = !{!md83, !md86, !md90, !md95, !md102} +!"air.compile_options" = !{!md103, !md104, !md105} +!"llvm.ident" = !{!md106} +!"air.version" = !{!md107} +!"air.language_version" = !{!md108} diff --git a/crates/metal2vulkan/tests/air_input/a8r_targets.txt b/crates/metal2vulkan/tests/air_input/a8r_targets.txt new file mode 100644 index 000000000..da7fdbd9e --- /dev/null +++ b/crates/metal2vulkan/tests/air_input/a8r_targets.txt @@ -0,0 +1,323 @@ +target triple = "air64_v28-apple-macosx26.0.0" +source_filename = "-" +; datalayout DataLayout { endian: Little, pointers: {0: PointerSpec { size_bits: 64, abi_bits: 64, pref_bits: 64, index_bits: 64 }}, ints: {1: AlignSpec { abi_bits: 8, pref_bits: 8 }, 8: AlignSpec { abi_bits: 8, pref_bits: 8 }, 16: AlignSpec { abi_bits: 16, pref_bits: 16 }, 32: AlignSpec { abi_bits: 32, pref_bits: 32 }, 64: AlignSpec { abi_bits: 64, pref_bits: 64 }}, floats: {16: AlignSpec { abi_bits: 16, pref_bits: 16 }, 32: AlignSpec { abi_bits: 32, pref_bits: 32 }, 64: AlignSpec { abi_bits: 64, pref_bits: 64 }, 128: AlignSpec { abi_bits: 128, pref_bits: 128 }}, vectors: {16: AlignSpec { abi_bits: 16, pref_bits: 16 }, 24: AlignSpec { abi_bits: 32, pref_bits: 32 }, 32: AlignSpec { abi_bits: 32, pref_bits: 32 }, 48: AlignSpec { abi_bits: 64, pref_bits: 64 }, 64: AlignSpec { abi_bits: 64, pref_bits: 64 }, 96: AlignSpec { abi_bits: 128, pref_bits: 128 }, 128: AlignSpec { abi_bits: 128, pref_bits: 128 }, 192: AlignSpec { abi_bits: 256, pref_bits: 256 }, 256: AlignSpec { abi_bits: 256, pref_bits: 256 }, 512: AlignSpec { abi_bits: 512, pref_bits: 512 }, 1024: AlignSpec { abi_bits: 1024, pref_bits: 1024 }}, aggregate: AlignSpec { abi_bits: 0, pref_bits: 64 }, native_ints: [8, 16, 32], stack_align_bits: None, alloca_space: 0, program_space: 0, globals_space: 0, mangling: None, fn_ptr_align: None, non_integral: [] } +%t3 = type <{ <4 x float> }> +%t5 = type %t3 (i32) +%t6 = type float (i32) +%t8 = type <4 x float> (<4 x float>, ptr addrspace(2)) +%t9 = type <{ <4 x float>, <4 x float> }> +%t10 = type %t9 (<4 x float>, ptr addrspace(2)) +%t12 = type <4 x float> (<4 x float>, <4 x float>, ptr addrspace(2), ptr addrspace(1)) +%t15 = type <2 x i32> (<2 x float>) +%t17 = type void (ptr addrspace(1), ptr addrspace(2), <2 x i32>) +%t20 = type <4 x half> (<4 x float>) +%t21 = type void (ptr addrspace(1), ptr addrspace(1), <2 x i32>) +%t22 = type void (ptr addrspace(1), ptr addrspace(2), ptr addrspace(1), <2 x i32>) +%t23 = type <2 x float> (<2 x i32>) +%t24 = type void (ptr addrspace(1), <2 x i32>, <4 x float>, i32, i32) +%t25 = type void (ptr addrspace(1), <2 x i32>, <4 x half>, i32, i32) +%t26 = type ptr addrspace(2) () +%t28 = type { <4 x float>, i8 } +%t29 = type %t28 (ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) +%t31 = type %t28 (ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32) +%t33 = type [2 x i32] +c22 = %t33 [27, 0] +c37 = <2 x float> [0x40000000, 0x40000000] +c38 = <2 x float> [0xBF800000, 0xBF800000] +c41 = <4 x i32> [0, 1, poison, poison] +c45 = <4 x float> [poison, poison, 0x0, 0x3F800000] +c46 = <4 x i32> [0, 1, 6, 7] +c50 = <2 x i32> [0, 1] +c54 = <2 x float> [0x3F000000, 0x3F000000] +c55 = <2 x float> [0x3E000000, 0x3E000000] + +define %t5 @f0 "a8r_vertex" memory(NoModRef, NoModRef, NoModRef) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" { +bb0: + %i0 = shl i32 %a0, i32 1 + %i1 = and i32 %i0, i32 2 + %i2 = tail call reassoc nnan ninf nsz arcp contract afn float @f1 [air Convert(Convert { dst: NumTy { elem: F32, lanes: 1 }, dst_kind: Float, src: NumTy { elem: I32, lanes: 1 }, src_kind: Unsigned, src_fp8: None })](%i1) + %i3 = insertelement <2 x float> undef, %i2, i64 0 + %i4 = and i32 %a0, i32 2 + %i5 = tail call reassoc nnan ninf nsz arcp contract afn float @f1 [air Convert(Convert { dst: NumTy { elem: F32, lanes: 1 }, dst_kind: Float, src: NumTy { elem: I32, lanes: 1 }, src_kind: Unsigned, src_fp8: None })](%i4) + %i6 = insertelement %i3, %i5, i64 1 + %i7 = fmul reassoc nnan ninf nsz arcp contract afn <2 x float> %i6, <2 x float> c37 + %i8 = fadd reassoc nnan ninf nsz arcp contract afn <2 x float> %i7, <2 x float> c38 + %i9 = shufflevector <4 x float> %i8, <2 x float> poison, <0, 1, poison, poison> + %i10 = shufflevector <4 x float> %i9, <4 x float> c45, <0, 1, 6, 7> + %i11 = insertvalue %t3 undef %i10, 0 + ret %i11 +} + +declare %t6 @f1 "air.convert.f.f32.u.i32" memory(NoModRef, NoModRef, NoModRef) + +define %t5 @f2 "a8r_half_vertex" memory(NoModRef, NoModRef, NoModRef) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" { +bb0: + %i0 = icmp eq %a0, i32 1 + %i1 = select reassoc nnan ninf nsz arcp contract afn float %i0, float 0x3F800000, float 0xBF800000 + %i2 = icmp eq %a0, i32 2 + %i3 = select reassoc nnan ninf nsz arcp contract afn float %i2, float 0x3F800000, float 0xBF800000 + %i4 = insertelement <4 x float> c45, %i1, i64 0 + %i5 = insertelement %i4, %i3, i64 1 + %i6 = insertvalue %t3 undef %i5, 0 + ret %i6 +} + +define %t8 @f3 "a8r_fill" memory(NoModRef, NoModRef, NoModRef) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" %a1( Ref nocapture "air-buffer-no-alias"="" ) { +bb0: + %i0 = load <4 x float>, %a1, align 16 + ret %i0 +} + +define %t10 @f4 "a8r_dual" memory(NoModRef, NoModRef, NoModRef) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" %a1( Ref nocapture "air-buffer-no-alias"="" ) { +bb0: + %i0 = load <4 x float>, %a1, align 16 + %i1 = getelementptr inbounds <4 x float>, %a1, i64 1 + %i2 = load <4 x float>, %i1, align 16 + %i3 = insertvalue %t9 undef %i0, 0 + %i4 = insertvalue %i3 %i2, 1 + ret %i4 +} + +define %t12 @f5 "a8r_fetch" memory(Mod, NoModRef, NoModRef) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" %a2( Ref nocapture "air-buffer-no-alias"="" ) %a3( Mod nocapture "air-buffer-no-alias"="" ) { +bb0: + %i0 = shufflevector <2 x float> %a0, <4 x float> poison, <0, 1> + %i1 = tail call <2 x i32> @f6 [air Convert(Convert { dst: NumTy { elem: I32, lanes: 2 }, dst_kind: Unsigned, src: NumTy { elem: F32, lanes: 2 }, src_kind: Float, src_fp8: None })](%i0) + %i2 = extractelement %i1, i64 1 + %i3 = shl i32 %i2, i32 3 + %i4 = extractelement %i1, i64 0 + %i5 = add i32 %i3, %i4 + %i6 = zext %i5 to i64 + %i7 = getelementptr inbounds <4 x float>, %a3, %i6 + store %a1, %i7, align 16 + %i9 = load <4 x float>, %a2, align 16 + ret %i9 +} + +declare %t15 @f6 "air.convert.u.v2i32.f.v2f32" memory(NoModRef, NoModRef, NoModRef) + +define %t17 @f7 "a8r_write" memory(ModRef, NoModRef, NoModRef) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" %a0( nocapture ) %a1( Ref nocapture "air-buffer-no-alias"="" ) { +bb0: + %i0 = load <4 x float>, %a1, align 16 + tail call void @f14 [air Texture(Texture { op: Write, image: ImageShape { dim: D2, array: false, ms: false, depth: false }, texel: Some(Texel { ty: NumTy { elem: F32, lanes: 4 }, sign: None }), coord16: false, form: Current, access: Some(Write) })](%a0, %a2, %i0, i32 0, i32 2) arg0( nocapture ) + ret void +} + +define %t17 @f8 "a8r_write_half" memory(ModRef, NoModRef, NoModRef) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="64" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" %a0( nocapture ) %a1( Ref nocapture "air-buffer-no-alias"="" ) { +bb0: + %i0 = load <4 x float>, %a1, align 16 + %i1 = tail call reassoc nnan ninf nsz arcp contract afn <4 x half> @f9 [air Convert(Convert { dst: NumTy { elem: F16, lanes: 4 }, dst_kind: Float, src: NumTy { elem: F32, lanes: 4 }, src_kind: Float, src_fp8: None })](%i0) + tail call void @f15 [air Texture(Texture { op: Write, image: ImageShape { dim: D2, array: false, ms: false, depth: false }, texel: Some(Texel { ty: NumTy { elem: F16, lanes: 4 }, sign: None }), coord16: false, form: Current, access: Some(Write) })](%a0, %a2, %i1, i32 0, i32 2) arg0( nocapture ) + ret void +} + +declare %t20 @f9 "air.convert.f.v4f16.f.v4f32" memory(NoModRef, NoModRef, NoModRef) + +define %t21 @f10 "a8r_read" "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" %a0( Ref nocapture ) %a1( Mod nocapture "air-buffer-no-alias"="" ) { +bb0: + %i0 = tail call ptr addrspace(2) @f16 [air Sampler(GetReadSampler)]() + %i1 = tail call %t28 @f17 [air Texture(Texture { op: Read, image: ImageShape { dim: D2, array: false, ms: false, depth: false }, texel: Some(Texel { ty: NumTy { elem: F32, lanes: 4 }, sign: None }), coord16: false, form: Current, access: Some(Read) })](%a0, %i0, %a2, <2 x i32> zeroinitializer, i32 0, i32 1) arg0( Ref nocapture ) + %i2 = extractvalue <4 x float> %i1, 0 + %i3 = extractelement %a2, i64 1 + %i4 = shl i32 %i3, i32 3 + %i5 = extractelement %a2, i64 0 + %i6 = add i32 %i4, %i5 + %i7 = zext %i6 to i64 + %i8 = getelementptr inbounds <4 x float>, %a1, %i7 + store %i2, %i8, align 16 + ret void +} + +define %t22 @f11 "a8r_sample" convergent memory(ModRef, NoModRef, NoModRef) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" %a0( Ref nocapture ) %a1( Ref nocapture ) %a2( Mod nocapture "air-buffer-no-alias"="" ) { +bb0: + %i0 = tail call reassoc nnan ninf nsz arcp contract afn <2 x float> @f12 [air Convert(Convert { dst: NumTy { elem: F32, lanes: 2 }, dst_kind: Float, src: NumTy { elem: I32, lanes: 2 }, src_kind: Unsigned, src_fp8: None })](%a3) + %i1 = fadd reassoc nnan ninf nsz arcp contract afn <2 x float> %i0, <2 x float> c54 + %i2 = fmul reassoc nnan ninf nsz arcp contract afn <2 x float> %i1, <2 x float> c55 + %i3 = tail call %t28 @f18 [air Texture(Texture { op: Sample { compare: false, lod: Bias, offset: true }, image: ImageShape { dim: D2, array: false, ms: false, depth: false }, texel: Some(Texel { ty: NumTy { elem: F32, lanes: 4 }, sign: None }), coord16: false, form: Current, access: Some(Sample) })](%a0, %a1, %i2, i1 1, <2 x i32> zeroinitializer, i1 0, float 0x0, float 0x0, i32 0) convergent arg0( Ref nocapture ) arg1( Ref nocapture ) + %i4 = extractvalue <4 x float> %i3, 0 + %i5 = extractelement %a3, i64 1 + %i6 = shl i32 %i5, i32 3 + %i7 = extractelement %a3, i64 0 + %i8 = add i32 %i6, %i7 + %i9 = zext %i8 to i64 + %i10 = getelementptr inbounds <4 x float>, %a2, %i9 + store %i4, %i10, align 16 + ret void +} + +declare %t23 @f12 "air.convert.f.v2f32.u.v2i32" memory(NoModRef, NoModRef, NoModRef) + +define %t22 @f13 "a8r_read_write" "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" %a1( Ref nocapture "air-buffer-no-alias"="" ) %a2( Mod nocapture "air-buffer-no-alias"="" ) { +bb0: + %i0 = tail call ptr addrspace(2) @f16 [air Sampler(GetReadSampler)]() + %i1 = tail call %t28 @f17 [air Texture(Texture { op: Read, image: ImageShape { dim: D2, array: false, ms: false, depth: false }, texel: Some(Texel { ty: NumTy { elem: F32, lanes: 4 }, sign: None }), coord16: false, form: Current, access: Some(ReadWrite) })](%a0, %i0, %a3, <2 x i32> zeroinitializer, i32 0, i32 3) arg0( Ref nocapture ) + %i2 = extractvalue <4 x float> %i1, 0 + %i3 = extractelement %a3, i64 1 + %i4 = shl i32 %i3, i32 3 + %i5 = extractelement %a3, i64 0 + %i6 = add i32 %i4, %i5 + %i7 = zext %i6 to i64 + %i8 = getelementptr inbounds <4 x float>, %a2, %i7 + store %i2, %i8, align 16 + %i10 = load <4 x float>, %a1, align 16 + tail call void @f14 [air Texture(Texture { op: Write, image: ImageShape { dim: D2, array: false, ms: false, depth: false }, texel: Some(Texel { ty: NumTy { elem: F32, lanes: 4 }, sign: None }), coord16: false, form: Current, access: Some(ReadWrite) })](%a0, %a3, %i10, i32 0, i32 3) arg0( nocapture ) + ret void +} + +declare %t24 @f14 "air.write_texture_2d.v4f32" memory(ModRef, NoModRef, NoModRef) %a0( nocapture ) + +declare %t25 @f15 "air.write_texture_2d.v4f16" memory(ModRef, NoModRef, NoModRef) %a0( nocapture ) + +declare %t26 @f16 "air.get_read_sampler" memory(NoModRef, Ref, NoModRef) + +declare %t29 @f17 "air.read_texture_2d.v4f32" memory(Ref, NoModRef, NoModRef) %a0( Ref nocapture ) + +declare %t31 @f18 "air.sample_texture_2d.v4f32" convergent memory(Ref, NoModRef, NoModRef) %a0( Ref nocapture ) %a1( Ref nocapture ) +!md0 = !"SDK Version" +!md1 = !"wchar_size" +!md2 = !"frame-pointer" +!md3 = !"air.max_device_buffers" +!md4 = !"air.max_constant_buffers" +!md5 = !"air.max_threadgroup_buffers" +!md6 = !"air.max_textures" +!md7 = !"air.max_read_write_textures" +!md8 = !"air.max_samplers" +!md9 = !"air.position" +!md10 = !"air.arg_type_name" +!md11 = !"float4" +!md12 = !"air.arg_name" +!md13 = !"position" +!md14 = !"air.vertex_id" +!md15 = !"uint" +!md16 = !"id" +!md17 = !"air.render_target" +!md18 = !"air.center" +!md19 = !"air.no_perspective" +!md20 = !"air.arg_unused" +!md21 = !"air.buffer" +!md22 = !"air.location_index" +!md23 = !"air.read" +!md24 = !"air.address_space" +!md25 = !"air.arg_type_size" +!md26 = !"air.arg_type_align_size" +!md27 = !"color" +!md28 = !"first" +!md29 = !"second" +!md30 = !"held" +!md31 = !"air.read_write" +!md32 = !"out" +!md33 = !"air.texture" +!md34 = !"air.write" +!md35 = !"texture2d" +!md36 = !"t" +!md37 = !"air.thread_position_in_grid" +!md38 = !"uint2" +!md39 = !"g" +!md40 = !"texture2d" +!md41 = !"texture2d" +!md42 = !"air.sample" +!md43 = !"texture2d" +!md44 = !"air.sampler" +!md45 = !"sampler" +!md46 = !"s" +!md47 = !"texture2d" +!md48 = !"air.compile.denorms_disable" +!md49 = !"air.compile.fast_math_enable" +!md50 = !"air.compile.framebuffer_fetch_enable" +!md51 = !"Apple metal version 32023.921 (metalfe-32023.921.6)" +!md52 = !"Metal" +!md53 = !"omnipotent char" +!md54 = !"Simple C++ TBAA" +!md55 = !"air-alias-scope-arg(1)" +!md56 = !"air-alias-scope-arg(2)" +!md57 = !"air-alias-scope-textures" +!md58 = i32 2 +!md59 = %t33 c22 +!md60 = i32 1 +!md61 = i32 4 +!md62 = i32 7 +!md63 = i32 31 +!md64 = i32 128 +!md65 = i32 8 +!md66 = i32 16 +!md67 = ptr addrspace(0) @f0 +!md68 = i32 0 +!md69 = ptr addrspace(0) @f2 +!md70 = ptr addrspace(0) @f3 +!md71 = ptr addrspace(0) @f4 +!md72 = ptr addrspace(0) @f5 +!md73 = i32 3 +!md74 = ptr addrspace(0) @f7 +!md75 = ptr addrspace(0) @f8 +!md76 = ptr addrspace(0) @f10 +!md77 = ptr addrspace(0) @f11 +!md78 = ptr addrspace(0) @f13 +!md79 = i64 0 +!md80 = !{!md58, !md0, !md59} +!md81 = !{!md60, !md1, !md61} +!md82 = !{!md62, !md2, !md58} +!md83 = !{!md62, !md3, !md63} +!md84 = !{!md62, !md4, !md63} +!md85 = !{!md62, !md5, !md63} +!md86 = !{!md62, !md6, !md64} +!md87 = !{!md62, !md7, !md65} +!md88 = !{!md62, !md8, !md66} +!md89 = !{!md9, !md10, !md11, !md12, !md13} +!md90 = !{!md89} +!md91 = !{!md68, !md14, !md10, !md15, !md12, !md16} +!md92 = !{!md91} +!md93 = !{!md67, !md90, !md92} +!md94 = !{!md69, !md90, !md92} +!md95 = !{!md17, !md68, !md68, !md10, !md11} +!md96 = !{!md95} +!md97 = !{!md68, !md9, !md18, !md19, !md10, !md11, !md12, !md13, !md20} +!md98 = !{!md60, !md21, !md22, !md68, !md60, !md23, !md24, !md58, !md25, !md66, !md26, !md66, !md10, !md11, !md12, !md27} +!md99 = !{!md97, !md98} +!md100 = !{!md70, !md96, !md99} +!md101 = !{!md17, !md68, !md68, !md10, !md11, !md12, !md28} +!md102 = !{!md17, !md68, !md60, !md10, !md11, !md12, !md29} +!md103 = !{!md101, !md102} +!md104 = !{!md71, !md103, !md99} +!md105 = !{!md68, !md9, !md18, !md19, !md10, !md11, !md12, !md13} +!md106 = !{!md60, !md17, !md68, !md10, !md11, !md12, !md30} +!md107 = !{!md58, !md21, !md22, !md68, !md60, !md23, !md24, !md58, !md25, !md66, !md26, !md66, !md10, !md11, !md12, !md27} +!md108 = !{!md73, !md21, !md22, !md60, !md60, !md31, !md24, !md60, !md25, !md66, !md26, !md66, !md10, !md11, !md12, !md32} +!md109 = !{!md105, !md106, !md107, !md108} +!md110 = !{!md72, !md96, !md109} +!md111 = !{} +!md112 = !{!md68, !md33, !md22, !md68, !md60, !md34, !md10, !md35, !md12, !md36} +!md113 = !{!md58, !md37, !md10, !md38, !md12, !md39} +!md114 = !{!md112, !md98, !md113} +!md115 = !{!md74, !md111, !md114} +!md116 = !{!md68, !md33, !md22, !md68, !md60, !md34, !md10, !md40, !md12, !md36} +!md117 = !{!md116, !md98, !md113} +!md118 = !{!md75, !md111, !md117} +!md119 = !{!md68, !md33, !md22, !md68, !md60, !md23, !md10, !md41, !md12, !md36} +!md120 = !{!md60, !md21, !md22, !md60, !md60, !md31, !md24, !md60, !md25, !md66, !md26, !md66, !md10, !md11, !md12, !md32} +!md121 = !{!md119, !md120, !md113} +!md122 = !{!md76, !md111, !md121} +!md123 = !{!md68, !md33, !md22, !md68, !md60, !md42, !md10, !md43, !md12, !md36} +!md124 = !{!md60, !md44, !md22, !md68, !md60, !md10, !md45, !md12, !md46} +!md125 = !{!md58, !md21, !md22, !md60, !md60, !md31, !md24, !md60, !md25, !md66, !md26, !md66, !md10, !md11, !md12, !md32} +!md126 = !{!md73, !md37, !md10, !md38, !md12, !md39} +!md127 = !{!md123, !md124, !md125, !md126} +!md128 = !{!md77, !md111, !md127} +!md129 = !{!md68, !md33, !md22, !md68, !md60, !md31, !md10, !md47, !md12, !md36} +!md130 = !{!md129, !md98, !md125, !md126} +!md131 = !{!md78, !md111, !md130} +!md132 = !{!md48} +!md133 = !{!md49} +!md134 = !{!md50} +!md135 = !{!md51} +!md136 = !{!md58, !md65, !md68} +!md137 = !{!md52, !md61, !md68, !md68} +!md138 = !{!md54} +!md139 = !{!md53, !md138, !md79} +!md140 = !{!md139, !md139, !md79} +!"llvm.module.flags" = !{!md80, !md81, !md82, !md83, !md84, !md85, !md86, !md87, !md88} +!"air.vertex" = !{!md93, !md94} +!"air.fragment" = !{!md100, !md104, !md110} +!"air.kernel" = !{!md115, !md118, !md122, !md128, !md131} +!"air.compile_options" = !{!md132, !md133, !md134} +!"llvm.ident" = !{!md135} +!"air.version" = !{!md136} +!"air.language_version" = !{!md137} diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index 324c48c12..2655acdb7 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -865,6 +865,8 @@ surface! { fn ycbcr_format; fn rotated_channels; fn to_rotated_image; + fn alpha_in_red; + fn alpha_in_red_format; } "metal::sampler" => metal2vulkan::metal::sampler { struct SamplerUse N;