Translator: the swizzled_storage variant goes; the runtime never asks for it

LoweringInputs::swizzled_storage and VariantKey::swizzled_storage have
no setter outside the translator's own tests. Since the identity domains
refuse any slot whose SlotPlan::swizzle is set
(IdentityCause::TextureState), a slot of the variant could only lead to
a refusal or to nothing. Nothing else reads the swizzle any more: the
emit side went in 6a08124f54.

Deleted with it:
- the cache key's "swizzled-storage" block;
- lower::texture::swizzled_storage and ::swizzles;
- SlotPlan::swizzle (identity_lowered now tests offset_base alone);
- the NotImplemented(TextureSwizzle) refusals of the variant's ulong,
  short-lane and imageblock-slice accesses (Feature::TextureSwizzle
  stays: bind/heap.rs refuses with it);
- the bicubic and packed-normalized sampling arms that read the
  variant, and the read path's storage_swizzle alpha term;
- the public RuntimeFact::TextureSwizzle, which only swizzles()
  produced, with its codec entry, mechanism, identity_unsourced arm and
  name. The mechanism test's variant index 35 now holds PrivateList and
  the covered range is 0..55.
Tests: tests/engine_swizzled_storage.rs goes (its reference rules
checked only its own helpers once the emit side was gone), and
engine_extended_range/bicubic.rs loses its swizzled cases. Docs fixed:
LoweringInputs, VariantKey, the sampler select and extended module
docs, IdentityCause::TextureState's examples, and the runtime README's
identity refusal list (TextureSwizzle no longer named).

No compile with empty inputs changes: every deleted arm was gated on
the set. The RuntimeFact encoding loses a variant; the
ARTIFACT_FORMAT_VERSION bump to 616 in 9cc7dd223a on this branch covers
it.

Searches:
- this tree at f6fc9cf282: git grep -n swizzled_storage in
  crates/metal2vulkan{,-runtime,-air,-validation,-harness,-devtools}
  and docs, fixture names (rrp_swizzled_storage) and the conformance
  case module aside -> 32 hits, all in crates/metal2vulkan; 0 after
  (crates/metal2vulkan-runtime: 0 before).
- reims-vgpu c16328ee3d (and cc1f47b30b): git grep -n swizzled_storage
  -> 0 hits; git grep -n RuntimeFact -> 0 hits.

The signatures table is blessed: exactly 3 records removed
(VariantKey.swizzled_storage, LoweringInputs.swizzled_storage,
RuntimeFact::TextureSwizzle). refusal_surface.py --check passes, so
docs/REFUSALS.md does not change.
This commit is contained in:
Anees Iqbal committed 2026-12-04 18:12:43 -08:00
1 parent ab351430d3
commit a49e4a61c4
21 files changed
+29 -453

No files matched your search

+2 -2
View File
@@ -4614,8 +4614,8 @@ cache is answered compile-required on both.
`under_the_identity_domains_a_runtime_samplers_query_reads_its_pushed_word`;
- other state of a bound texture or sampler beyond its resource ID ("state of a bound texture
or sampler beyond its resource ID (F)", `F` the `RuntimeFact`): a cube's view shape,
`ImageViewShape`; a storage texture's numeric type that nothing in the function states,
`StorageTextureNumericType`; and a texture's swizzle, `TextureSwizzle`: no test yet;
`ImageViewShape`, and a storage texture's numeric type that nothing in the function states,
`StorageTextureNumericType`: no test yet;
- program-scope constant data past 64 KiB read through memory ("constant data of N bytes read
through memory"): `tests::engine_identity`'s
`a_constant_blob_past_the_modules_bound_is_refused_naming_its_size` asserts the text;
-1
View File
@@ -1212,7 +1212,6 @@ codec_enum! {
FlatGrid,
CallThreadgroups,
TileThreadgroupMemory { index },
TextureSwizzle { slot },
TileImageblock { data_size, alignment },
AmplificationDraws { layered, viewports },
FoldedGroups,
-17
View File
@@ -241,16 +241,6 @@ pub struct VariantKey {
/// not draw runs. Its graphics state states it (`GraphicsState::line_band`).
#[cfg_attr(feature = "serde", serde(default))]
pub line_band: Option<crate::pipeline::BandPrimitive>,
/// Storage-image texture slots bound to a texture with a swizzle (`MTLTexture.swizzle` other
/// than the default) whose texels the function reads or writes
/// (`LoweringInputs::swizzled_storage`), where a Vulkan storage view takes no swizzle; and
/// each sampled slot of `extended_range` bound to such a texture, whose view holds raw codes,
/// and, on a device without Metal's own sampler, each sampled slot bound to a swizzled packed
/// normalized texture. A function that reads, writes or samples texels of such a slot is
/// refused under the identity domains, which source no swizzle (`IdentityCause::TextureState`);
/// `metal2vulkan-runtime` asks for none.
#[cfg_attr(feature = "serde", serde(default))]
pub swizzled_storage: BTreeSet<SlotRef>,
/// Every function that reads visible-function tables by their resource ids reads their
/// words through their device addresses (`LoweringInputs::addressed_function_tables`): the
/// variant a shape whose listed tables may pass `maxStorageBufferRange` asks for
@@ -316,7 +306,6 @@ impl VariantKey {
&& !self.depth_clamp_range
&& !self.rotated_weights
&& self.line_band.is_none()
&& self.swizzled_storage.is_empty()
&& !self.addressed_function_tables
&& self.primitive_id_indices.is_none()
&& !self.quad_primitive_ids
@@ -382,12 +371,6 @@ impl VariantKey {
.filter(|(s, _)| s.stage == stage)
.map(|(s, x)| (*s, *x))
.collect();
out.swizzled_storage = self
.swizzled_storage
.iter()
.filter(|s| s.stage == stage)
.copied()
.collect();
if stage == crate::pipeline::sym::Stage::Fragment {
out.zeroed_colors = self.zeroed_colors.clone();
out.dropped_colors = self.dropped_colors.clone();
@@ -83,9 +83,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism {
// The binder checks the object function's arena with the encoder's lengths, which it
// specializes, against the object stage's workgroup memory limit.
RuntimeFact::ObjectThreadgroupArena { .. } => Mechanism::PlanTimeCheck,
// The binder specializes the bound texture buffer's swizzle, which the function applies
// to its reads.
RuntimeFact::TextureSwizzle { .. } => Mechanism::Specialization,
// The consumer keeps the pass's imageblock storage and binds it to the dispatch.
RuntimeFact::TileImageblock { .. } => Mechanism::RenderPassContract,
// A separate compile of the pipeline, which an amplification multiview does not express
@@ -57,7 +57,6 @@ fn every_fact() -> Vec<RuntimeFact> {
RuntimeFact::FlatGrid,
RuntimeFact::CallThreadgroups,
RuntimeFact::TileThreadgroupMemory { index: 1 },
RuntimeFact::TextureSwizzle { slot },
RuntimeFact::TileImageblock {
data_size: 8,
alignment: 4,
@@ -134,7 +133,6 @@ fn variant(f: &RuntimeFact) -> usize {
RuntimeFact::CallStackDepth { .. } => 32,
RuntimeFact::FlatGrid => 33,
RuntimeFact::TileThreadgroupMemory { .. } => 34,
RuntimeFact::TextureSwizzle { .. } => 35,
RuntimeFact::TileImageblock { .. } => 36,
RuntimeFact::AmplificationDraws { .. } => 37,
RuntimeFact::FoldedGroups => 39,
@@ -149,7 +147,7 @@ fn variant(f: &RuntimeFact) -> usize {
RuntimeFact::MergedDraws => 48,
RuntimeFact::QuadPrimitiveIds => 40,
RuntimeFact::RotatedWeights => 53,
RuntimeFact::PrivateList => 55,
RuntimeFact::PrivateList => 35,
RuntimeFact::PartialObjectThreadgroups => 27,
RuntimeFact::OpenClMode => 25,
RuntimeFact::CallThreadgroups => 26,
@@ -166,7 +164,7 @@ fn variant(f: &RuntimeFact) -> usize {
fn mechanism_is_total_over_every_fact_and_profile() {
let facts = every_fact();
let covered: std::collections::BTreeSet<usize> = facts.iter().map(variant).collect();
assert_eq!(covered, (0..56).collect(), "every_fact misses a variant");
assert_eq!(covered, (0..55).collect(), "every_fact misses a variant");
for (stem, _) in super::committed_profiles() {
let dev = device(&stem);
let p = dev.profile();
@@ -182,8 +180,7 @@ fn mechanism_is_total_over_every_fact_and_profile() {
| RuntimeFact::AmplificationCount
| RuntimeFact::ImageblockSize { .. }
| RuntimeFact::TileFunction
| RuntimeFact::TileThreadgroupMemory { .. }
| RuntimeFact::TextureSwizzle { .. } => Mechanism::Specialization,
| RuntimeFact::TileThreadgroupMemory { .. } => Mechanism::Specialization,
RuntimeFact::LocalSizeConstraint { .. }
| RuntimeFact::LocalSizeLimits
| RuntimeFact::DeviceAddresses { .. }
+2 -2
View File
@@ -1082,8 +1082,8 @@ pub enum IdentityCause {
/// no input names under the identity domains.
StorageTextureFormat,
/// A texture argument of a type the identity arrays hold no element of, or state of a bound
/// texture or sampler beyond its resource ID that the function reads (a swizzle, an
/// extended-range or sRGB-twin form, a bound format's class).
/// texture or sampler beyond its resource ID that the function reads (an extended-range or
/// sRGB-twin form, a bound format's class, a view's parent's base-level size).
TextureState,
}
@@ -142,9 +142,7 @@
//! border texel through the format's channels. A swizzled texture's answers are the unswizzled
//! texture's, swizzled: the swizzle applies to the decoded texel, a border texel included, and a
//! gather of a component gathers the component the swizzle names (a `Zero` or `One` 0 or 1 at every
//! tap). The slot's view holds raw codes, so it takes no swizzle: a function that samples a slot of
//! `LoweringInputs::swizzled_storage` is refused, its swizzle state of the bound texture beyond its
//! resource ID (`IdentityCause::TextureState`). A `BGR10_XR` or `BGRA10_XR` form's (or `_sRGB` twin's) `half` gather rounds each
//! tap). A `BGR10_XR` or `BGRA10_XR` form's (or `_sRGB` twin's) `half` gather rounds each
//! tap as its nearest sample does, with ties away from zero, and every gather reads the base level
//! whatever the sampler's mip filter and clamp (the XR mip probe below: every lane of 8,192 gathers
//! of each such form's 2D and 2D array textures of five levels, through a runtime sampler with a
@@ -1035,13 +1035,12 @@ fn select_slot(
/// implicit level and explicit gradients by Vulkan's level of detail, recorded
/// (`PrecisionNote::DeviceSampleLevel`). A bfloat form's sample is nearest under either filter, as
/// Metal's, and its gather of a component is built, the taps of the linear footprint; so is another
/// form's gather, but a two-plane form's and a padded form's `half` one, at the base level; and a
/// swizzled texture of the slot's variant (`LoweringInputs::swizzled_storage`) swizzles the decoded
/// texels. A `BGR10_XR`, `BGRA10_XR` or two-plane form's (or `_sRGB` twin's) 2D sample through a
/// form's gather, but a two-plane form's and a padded form's `half` one, at the base level. A
/// `BGR10_XR`, `BGRA10_XR` or two-plane form's (or `_sRGB` twin's) 2D sample through a
/// constexpr bicubic sampler is Metal's bicubic filter of the decoded texels
/// (`extended`), under the bicubic filter's checks (`NotImplemented(SamplerBicubicFilter)`:
/// `bicubic::check`), and refused there for a bfloat or padded form, a gather, a 2D array, and a
/// swizzled texture (not measured). Every other sampling of the slot is `NotImplemented(Format)`:
/// `bicubic::check`), and refused there for a bfloat or padded form, a gather and a 2D array (not
/// measured). Every other sampling of the slot is `NotImplemented(Format)`:
/// a two-plane form's gather, or a padded form's `half` one, an LOD query, a comparison, a 1D or
/// cube texture, another form's 3D texture, an anisotropic or mixed filter, a constexpr sampler's
/// linear mip filter of a two-plane form or of `RGB10A2Unorm_sRGB`, its level bias of its own or
@@ -1174,18 +1173,10 @@ fn select_extended(
SamplerArg::Static(r, _) => super::bicubic::state(r)?,
SamplerArg::Heap(_) => None,
};
let swizzle = crate::lower::texture::swizzled_storage(cx, ImageRef::Slot(index))?;
let cubic = match cubic {
None => None,
// Measured on the six `BGR10_XR`, `BGRA10_XR` and two-plane forms' 2D samples alone.
Some(_)
if form.bfloat()
|| form.padded()
|| gather.is_some()
|| swizzle
|| shape.array
|| volume =>
{
Some(_) if form.bfloat() || form.padded() || gather.is_some() || shape.array || volume => {
return Err(bicubic_refused());
}
Some(s) => {
@@ -1275,13 +1266,6 @@ fn select_extended(
SamplerArg::Heap(_) => return Err(refused()),
},
};
// A swizzled texture of the slot's variant: plain Metal swizzles the decoded texel, a border
// texel included, and a gather of a component gathers the component its swizzle names. The
// swizzle is state of the bound texture beyond its resource ID, which the identity domains
// refuse (`SlotPlan::identity_lowered`).
if swizzle {
crate::lower::texture::swizzles(cx, index)?;
}
// An offset on an axis that may repeat or mirror is placed by Metal's rule, which reads a
// view's parent's base-level size, state of the bound texture the identity domains refuse
// (`SlotPlan::offset_base`).
@@ -1796,8 +1780,6 @@ fn select_one(
.extend(routines.iter().copied());
cx.precision.insert(PrecisionNote::BicubicFilterArithmetic);
}
// An LOD query reads no texel.
let texel_op = !matches!(op, SampleOp::Lod { .. } | SampleOp::QueryLevel { .. });
// Every sample, gather and level query goes to the device's own sampler
// (`VkProperty::DeviceSampling`), whose answers the module records (a level query's level
// clamped by the device into the sampler's clamp, the descriptor's).
@@ -1901,21 +1883,6 @@ fn select_one(
}
_ => {}
}
// A packed normalized sampled slot of the variant (`LoweringInputs::swizzled_storage`), whose
// view takes no swizzle: plain Metal swizzles the texel its class converts, and a gather of a
// component gathers the component the swizzle names. The swizzle is state of the bound texture
// beyond its resource ID, which the identity domains refuse (`SlotPlan::identity_lowered`).
match image {
ImageRef::Slot(index)
if texel_op && !shape.depth && crate::lower::texture::swizzled_storage(cx, image)? =>
{
if form.is_none_or(|f| f.lanes != 4 || matches!(f.conv, TexelConv::U64Words)) {
return Err(Unsupported::not_implemented(Feature::TextureSwizzle).into());
}
crate::lower::texture::swizzles(cx, index)?;
}
_ => {}
}
// A cube's explicit gradients handed to the device in a form other than Metal's own: the
// footprint's note.
if let SampleOp::Sample {
+1 -3
View File
@@ -1682,9 +1682,7 @@ fn finish(
fn identity_unsourced(f: &RuntimeFact) -> bool {
matches!(
f,
RuntimeFact::ImageViewShape { .. }
| RuntimeFact::StorageTextureNumericType { .. }
| RuntimeFact::TextureSwizzle { .. }
RuntimeFact::ImageViewShape { .. } | RuntimeFact::StorageTextureNumericType { .. }
)
}
+3 -53
View File
@@ -1667,31 +1667,6 @@ pub(crate) fn extended_range(
Ok(cx.inputs.extended_range.get(&slot).copied())
}
/// Whether texture slot `image` is one of `LoweringInputs::swizzled_storage`, a storage slot
/// bound to a swizzled texture, or an extended-range or packed normalized sampled slot bound to
/// one: a function that reads, writes or samples it reads the bound swizzle ([`swizzles`]). A heap
/// element never is.
pub(crate) fn swizzled_storage(cx: &SelectCx<'_>, image: ImageRef) -> Result<bool, Error> {
let ImageRef::Slot(index) = image else {
return Ok(false);
};
let slot = slot_of(cx, index)?.slot;
Ok(cx.inputs.swizzled_storage.contains(&slot))
}
/// Record that texture slot `index`'s function reads its bound texture's swizzle
/// (`RuntimeFact::TextureSwizzle`): state of the bound texture beyond its resource ID, which the
/// identity domains refuse (`SlotPlan::identity_lowered`).
pub(crate) fn swizzles(cx: &mut SelectCx<'_>, index: u32) -> Result<(), Error> {
let slot = slot_of(cx, index)?.slot;
if let Some(s) = cx.families.texture.slots.get_mut(&index) {
s.swizzle = true;
}
cx.facts
.insert(crate::pipeline::facts::RuntimeFact::TextureSwizzle { slot });
Ok(())
}
/// Record an operation of shape `shape` and texel class `texel` on `image`'s declaration.
fn observe(
cx: &mut SelectCx<'_>,
@@ -1980,24 +1955,12 @@ fn select_read(
}
// Metal's out-of-bounds alpha is the bound format's (1 where it has none): a read the shader
// checks, or tests against its level views, whose alpha the function observes takes it from the
// slot's resource ID's word, or from a heap element's handle. A texture buffer's read takes no
// swizzle: the runtime makes no swizzled texture buffer (its `Gap::TextureBufferSwizzle`).
// Plain Metal applies a storage slot's bound swizzle to the converted texel, out of bounds
// too, an extended-range sampled slot's to the decoded texel, and a packed normalized sampled
// slot's to the texel its class converts: a slot of the variant reads that swizzle, which the
// identity domains refuse (`swizzles`). A `ulong` texel's swizzle, and a read of fewer lanes,
// are not measured.
let storage_swizzle = shape.dim != ImageDim::Buffer && swizzled_storage(cx, image)?;
if storage_swizzle && (texel.lanes != 4 || matches!(texel.conv, TexelConv::U64Words)) {
return Err(Unsupported::not_implemented(Feature::TextureSwizzle).into());
}
// A `ulong` read's lanes past the first are Metal's constants `(0, 0, 1)` in and out of
// bounds, never the image's. A swizzled read may return the alpha in any lane, so it observes
// the alpha wherever the function reads a lane.
// slot's resource ID's word, or from a heap element's handle. A `ulong` read's lanes past the
// first are Metal's constants `(0, 0, 1)` in and out of bounds, never the image's.
let observed = (check == ReadCheck::Shader || level_views)
&& texel.lanes == 4
&& !matches!(texel.conv, TexelConv::U64Words)
&& (storage_swizzle || alpha_read(cx, at));
&& alpha_read(cx, at);
let alpha = match image {
ImageRef::Slot(index) if observed => {
if let Some(s) = cx.families.texture.slots.get_mut(&index) {
@@ -2047,9 +2010,6 @@ fn select_read(
if texel.conv == TexelConv::F32 && !decoded && extended.is_none() {
float_texel_notes(cx, image, shape, true);
}
if let (true, ImageRef::Slot(index)) = (storage_swizzle, image) {
swizzles(cx, index)?;
}
mark(cx, image, |u| u.read = true);
Ok(Read {
image,
@@ -2252,16 +2212,6 @@ fn select_write(
if matches!(texel.conv, TexelConv::F32 | TexelConv::F16) && extended.is_none() {
norm_storage_facts(cx, image)?;
}
// Plain Metal stores each channel of a storage slot bound to a swizzled texture from the lane
// the swizzle takes it to: a slot of the variant reads that swizzle, which the identity domains
// refuse (`swizzles`). A `ulong` texel's is not measured.
let swizzle = shape.dim != ImageDim::Buffer && swizzled_storage(cx, image)?;
if swizzle && (texel.lanes != 4 || matches!(texel.conv, TexelConv::U64Words)) {
return Err(Unsupported::not_implemented(Feature::TextureSwizzle).into());
}
if let (true, ImageRef::Slot(index)) = (swizzle, image) {
swizzles(cx, index)?;
}
let saturate = match extended {
Some(_) => IntRange::Full,
None => int_range(cx, image, texel)?,
@@ -271,13 +271,6 @@ pub(super) fn select(
if !image_access(cx, image)?.0 {
return Err(imageblocks());
}
// A slice written to a storage slot bound to a swizzled texture is not measured.
if super::swizzled_storage(cx, image)? {
return Err(crate::error::Unsupported::not_implemented(
crate::error::Feature::TextureSwizzle,
)
.into());
}
slot::stage_stores(cx)?;
let at = coord(cx, ops, t.image)?;
// Every cell's offset is `region + k · cell_bytes + field`, the region 16-byte aligned.
+3 -10
View File
@@ -158,11 +158,6 @@ pub struct SlotPlan {
/// The device is left both an out-of-bounds store and an out-of-bounds load of the slot, so
/// its variable is decorated `Volatile`; set by [`finish`].
pub volatile: bool,
/// The slot is one of `LoweringInputs::swizzled_storage` that the function reads, writes or
/// samples, so it reads the bound texture's swizzle (`RuntimeFact::TextureSwizzle`, `swizzles`):
/// state of the bound texture beyond its resource ID, which the identity domains refuse
/// ([`identity_lowered`](Self::identity_lowered)).
pub swizzle: bool,
/// An access of the slot places a texel offset by Metal's rule on an axis that may repeat or
/// mirror (`sampler::position::offset_dropped`), which reads a view's parent's base-level size:
/// state of the bound texture beyond its resource ID, which the identity domains refuse
@@ -184,7 +179,6 @@ impl SlotPlan {
uses: Uses::default(),
oob_alpha: false,
volatile: false,
swizzle: false,
offset_base: false,
decl: None,
}
@@ -1233,11 +1227,10 @@ impl SlotPlan {
/// Whether the identity domains lower the slot: its declaration has an identity array class
/// ([`identity_class`]), or it has none (a slot that is only tested for presence), and it reads
/// no state of the bound texture but its resource ID's (its presence, its format's missing
/// alpha and its border texels). A conversion by the bound format, a swizzle and offset
/// bases each read a constant or a binding the slot does not have there yet.
/// alpha and its border texels). A conversion by the bound format and an offset base each read
/// a constant or a binding the slot does not have there yet.
pub(crate) fn identity_lowered(&self) -> bool {
let state = self.swizzle || self.offset_base;
!state
!self.offset_base
&& self
.decl
.as_ref()
@@ -21,8 +21,7 @@ fn slot(stage: Stage, class: SlotClass, index: u32) -> SlotRef {
fn keys_and_inputs_start_empty() {
assert!(VariantKey::new().is_empty());
let mut v = VariantKey::new();
v.swizzled_storage
.insert(slot(Stage::Kernel, SlotClass::Texture, 3));
v.rotated_weights = true;
assert!(!v.is_empty());
assert_eq!(LoweringInputs::new(), LoweringInputs::default());
let key = PipelineKey::new([0xab; 32]);
@@ -114,7 +113,6 @@ mod serde_round_trips {
depth_clamp_range: true,
rotated_weights: true,
line_band: Some(crate::pipeline::BandPrimitive::Triangles),
swizzled_storage: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 6)]),
addressed_function_tables: true,
primitive_id_indices: Some(metal::IndexType::UInt16),
quad_primitive_ids: true,
@@ -251,7 +249,6 @@ mod serde_round_trips {
kept_imageblock_bytes: Some(12),
depth_clamp_range: true,
rotated_weights: true,
swizzled_storage: BTreeSet::from([slot(Stage::Fragment, SlotClass::Texture, 3)]),
addressed_function_tables: true,
unattached_colors: BTreeSet::from([5, 7]),
sample_mask: Some([0b1010, 0b0010, 0b1000, 0]),
@@ -260,11 +260,6 @@ pub fn function_key(
h.bytes(b"rotated-blends")
.bytes(format!("{:?}", inputs.rotated_blends).as_bytes());
}
// Appended only when set, as `signed_color_attachments`.
if !inputs.swizzled_storage.is_empty() {
h.bytes(b"swizzled-storage")
.bytes(format!("{:?}", inputs.swizzled_storage).as_bytes());
}
// Appended only when set.
if inputs.viewport_index_varying {
h.bytes(b"viewport-index-varying");
@@ -665,7 +665,6 @@ fn the_inputs_encoding_is_the_earlier_derived_debug() {
.replace(", kept_imageblock_bytes: None", "")
.replace(", depth_clamp_range: false", "")
.replace(", rotated_weights: false", "")
.replace(", swizzled_storage: {}", "")
.replace(", addressed_function_tables: false", "")
.replace(", unattached_colors: {}", "")
.replace(", sample_mask: None", "")
@@ -164,14 +164,6 @@ pub enum RuntimeFact {
/// buffer, at its tile, which `SpecKey::ImageblockWidth` and `SpecKey::ImageblockHeight` (the
/// pass's tile size) place.
TileThreadgroupMemory { index: u32 },
/// The function reads the bound texture's swizzle at texture slot `slot`: a slot of
/// `LoweringInputs::swizzled_storage` it reads, writes or samples texels of. Plain Metal
/// applies a storage texture's swizzle to each read, out of bounds too, and undoes it on each
/// write, and swizzles an extended-range sampled texture's decoded texels and a packed
/// normalized one's converted texels (Apple M4). The identity domains source no swizzle (state
/// of the bound texture beyond its resource ID), so such a function is refused
/// (`IdentityCause::TextureState`).
TextureSwizzle { slot: SlotRef },
/// The tile function declares an explicit imageblock that stands alone (no implicit one
/// beside it, and not aliased onto one), of `data_size` bytes (`air.imageblock_data_size`)
/// whose layout aligns to `alignment` (`air.arg_type_align_size`). Its cells are the render
@@ -391,7 +383,6 @@ impl RuntimeFact {
RuntimeFact::FlatGrid => "FlatGrid",
RuntimeFact::CallThreadgroups => "CallThreadgroups",
RuntimeFact::TileThreadgroupMemory { .. } => "TileThreadgroupMemory",
RuntimeFact::TextureSwizzle { .. } => "TextureSwizzle",
RuntimeFact::TileImageblock { .. } => "TileImageblock",
RuntimeFact::AmplificationDraws { .. } => "AmplificationDraws",
RuntimeFact::FoldedGroups => "FoldedGroups",
@@ -501,20 +501,6 @@ pub struct LoweringInputs {
/// compiles as without it.
#[cfg_attr(feature = "serde", serde(default))]
pub rotated_weights: bool,
/// Storage-image texture slots bound to a swizzled texture (`VariantKey::swizzled_storage`),
/// and sampled slots of `extended_range`, or of a packed normalized format, bound to one. Plain
/// Metal applies a storage texture's swizzle to each texel read, out of bounds too, after
/// converting it, and undoes it on each texel written: channel `c` stores the value of the
/// first lane whose source is `c`, else lane `c`'s own (an M4, where atomics ignore the
/// swizzle); it swizzles a sampled one's decoded or converted texels, a border texel included,
/// and a gather of a component gathers the component the swizzle names. A function that reads,
/// writes or samples texels of such a slot states `RuntimeFact::TextureSwizzle` and is refused
/// under the identity domains, which source no swizzle (`IdentityCause::TextureState`); a
/// `ulong` texel, an imageblock slice written to such a slot, or a read of fewer than four
/// lanes there is `NotImplemented(TextureSwizzle)` (unmeasured). A slot the function does not
/// read or write texels of compiles as without it.
#[cfg_attr(feature = "serde", serde(default))]
pub swizzled_storage: BTreeSet<SlotRef>,
/// The function reads every visible-function table it reads by resource id through the
/// table's device address (`VariantKey::addressed_function_tables`): the directory's entry
/// of the id holds the address of the table's words in place of an element, and a read of
@@ -11,18 +11,17 @@
//! multiply and add of the decoded taps under the weights computed from the fraction, where Metal
//! sums fixed-point weights exactly onto the lane's grid, and a `half` result is the device's
//! narrowing. Each compile is validated. What no case measured
//! is refused, `NotImplemented(SamplerBicubicFilter)`: a padded or bfloat form's bicubic sample, a
//! swizzled texture's, and a gather through a bicubic sampler.
//! is refused, `NotImplemented(SamplerBicubicFilter)`: a padded or bfloat form's bicubic sample and
//! a gather through a bicubic sampler.
use super::samples::{sample_kernel, words, Through};
use super::*;
use crate::error::Unsupported;
use crate::pipeline::testing::engine_dir;
/// A padded or bfloat form's bicubic sample, a swizzled texture's, and a gather through a bicubic
/// sampler are refused, `NotImplemented(SamplerBicubicFilter)`, but a two-plane form's gather, which
/// is refused under any sampler, `NotImplemented(Format)`; each compiles without the slot's
/// variant.
/// A padded or bfloat form's bicubic sample and a gather through a bicubic sampler are refused,
/// `NotImplemented(SamplerBicubicFilter)`, but a two-plane form's gather, which is refused under
/// any sampler, `NotImplemented(Format)`; each compiles without the slot's variant.
#[test]
fn unmeasured_bicubic_samples_are_refused() {
let fixture = match llvm_assemble(&engine_dir().join("xr_bicubic.ll")) {
@@ -52,20 +51,13 @@ fn unmeasured_bicubic_samples_are_refused() {
];
let mut cases = Vec::new();
for form in unmeasured {
cases.push((format!("{form:?}"), &fixture, "xrb_edge", form, false));
cases.push((format!("{form:?}"), &fixture, "xrb_edge", form));
}
for form in FORMS {
cases.push((
format!("{form:?} swizzled"),
&fixture,
"xrb_edge",
form,
true,
));
cases.push((format!("{form:?} gather"), &gather, "k", form, false));
cases.push((format!("{form:?} gather"), &gather, "k", form));
}
for (stem, p) in profiles() {
for (what, bc, entry, form, swizzled) in &cases {
for (what, bc, entry, form) in &cases {
let feature = match (*entry, form) {
("k", ExtendedRange::Planes { .. }) => Feature::Format,
_ => Feature::SamplerBicubicFilter,
@@ -73,9 +65,6 @@ fn unmeasured_bicubic_samples_are_refused() {
let want = Unsupported::not_implemented(feature);
let mut inputs = LowerInputs::new();
inputs.extended_range.insert(SOURCE, *form);
if *swizzled {
inputs.swizzled_storage.insert(SOURCE);
}
match typed_module_with(bc, entry, &p, &inputs) {
Err(crate::error::Error::Unsupported(u)) => assert_eq!(
(&u.feature, &u.needs),
@@ -1,252 +0,0 @@
//! Swizzled textures at storage slots: plain Metal applies the bound texture's swizzle to the texels
//! a function reads through a storage binding of a swizzled view and undoes it on those it writes
//! (an M4 under macOS 27.0.1; misuse, which Metal's validation stops: the view's usage is stripped
//! of `ShaderWrite`). Under a slot's `swizzled_storage` variant a function that reads or writes
//! texels there reads that swizzle, which the identity domains refuse
//! (`IdentityCause::TextureState`).
//!
//! - The reference rules reproduce the probes' answers ([`the_rules_are_the_probes_answers`]): a
//! read of each swizzle in [`swizzles`] is the texel swizzled, and a write stores channel `c`
//! from the first lane whose source is `c`, else lane `c`.
//! - An atomic ignores the swizzle.
//! - A `ulong` read under the variant is refused (`NotImplemented(TextureSwizzle)`).
//!
//! `llvm-as` assembles the kernels; without it the tests skip visibly.
use crate::device::profile::DeviceProfile;
use crate::device::requirements::VkFeature;
use crate::device::{Device, DeviceDescription};
use crate::error::{Error, Feature};
use crate::lower::select::LowerInputs;
use crate::metal::{TextureSwizzle as S, TextureSwizzleChannels as C};
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::lower_inputs::{StorageImageChoice, StorageImageClass};
use crate::pipeline::sym::Stage;
use crate::pipeline::sym::{SlotClass, SlotRef};
use crate::pipeline::testing::{engine_dir, llvm_assemble, typed_module_with, AssembleError};
use crate::vk;
const SLOT: SlotRef = SlotRef {
stage: Stage::Kernel,
class: SlotClass::Texture,
index: 0,
};
/// The swizzles: permutations, `Zero` and `One` sources, repeated sources and the identity, the
/// probes' among them.
fn swizzles() -> Vec<C> {
let c = |s: &str| {
let v: Vec<S> = s
.chars()
.map(|ch| match ch {
'R' => S::Red,
'G' => S::Green,
'B' => S::Blue,
'A' => S::Alpha,
'0' => S::Zero,
_ => S::One,
})
.collect();
C::new(v[0], v[1], v[2], v[3])
};
[
"RGBA", "GBAR", "BGRA", "ABGR", "GRBA", "RRRR", "R01A", "0000", "1111", "RGB1", "RGBR",
"0GBA", "GR01", "0R01", "1RG0", "ARGB",
]
.into_iter()
.map(c)
.collect()
}
// ---- The reference ----------------------------------------------------------------------------
/// The swizzle's four sources, red's first.
fn sources(s: C) -> [S; 4] {
[s.red, s.green, s.blue, s.alpha]
}
/// Metal's read of texel `t` (its channels) through swizzle `s`: each lane the source its
/// channel names, `one` for `One`.
fn read_rule(s: C, t: [u32; 4], one: u32) -> [u32; 4] {
sources(s).map(|source| match source {
S::Zero => 0,
S::One => one,
S::Red => t[0],
S::Green => t[1],
S::Blue => t[2],
_ => t[3],
})
}
/// The channels Metal stores for a write of `v` through swizzle `s`: channel `c` takes the lane
/// of the first source that is `c`, else lane `c`.
fn write_rule(s: C, v: [u32; 4]) -> [u32; 4] {
let channel = [S::Red, S::Green, S::Blue, S::Alpha];
let from = sources(s);
std::array::from_fn(|c| match from.iter().position(|&f| f == channel[c]) {
Some(i) => v[i],
None => v[c],
})
}
/// The probes' answers (for reads and writes of `RGBA8Unorm`, `RG8Unorm`, `R32Float` and `R32Uint`
/// views, for reads outside the texture), which the rules reproduce: a write of `(10, 20, 30, 40)`
/// and a read of the texel `(10, 20, 30, 40)` in bytes; `RG8Unorm`'s two channels; `R32Uint`'s
/// texel `(1000, 0, 0, 1)` and its zero texel `(0, 0, 0, 1)`.
#[test]
fn the_rules_are_the_probes_answers() {
let by = |name: &str| {
swizzles()
.into_iter()
.zip([
"RGBA", "GBAR", "BGRA", "ABGR", "GRBA", "RRRR", "R01A", "0000", "1111", "RGB1",
"RGBR", "0GBA", "GR01", "0R01", "1RG0", "ARGB",
])
.find_map(|(s, n)| (n == name).then_some(s))
.expect("swizzle")
};
let t = [10, 20, 30, 40];
for (name, read, written) in [
("GBAR", [20, 30, 40, 10], [40, 10, 20, 30]),
("BGRA", [30, 20, 10, 40], [30, 20, 10, 40]),
("ABGR", [40, 30, 20, 10], [40, 30, 20, 10]),
("GRBA", [20, 10, 30, 40], [20, 10, 30, 40]),
("RRRR", [10, 10, 10, 10], [10, 20, 30, 40]),
("R01A", [10, 0, 255, 40], [10, 20, 30, 40]),
("0000", [0, 0, 0, 0], [10, 20, 30, 40]),
("1111", [255, 255, 255, 255], [10, 20, 30, 40]),
("RGB1", [10, 20, 30, 255], [10, 20, 30, 40]),
("RGBR", [10, 20, 30, 10], [10, 20, 30, 40]),
("0GBA", [0, 20, 30, 40], [10, 20, 30, 40]),
] {
assert_eq!(read_rule(by(name), t, 255), read, "{name} read");
assert_eq!(write_rule(by(name), t), written, "{name} write");
}
// `RG8Unorm`: the texel `(10, 20, 0, 255)`; a write stores red and green.
let rg = [10, 20, 0, 255];
for (name, read, written) in [
("GR01", [20, 10, 0, 255], [20, 10]),
("RRRR", [10, 10, 10, 10], [10, 20]),
("0R01", [0, 10, 0, 255], [20, 20]),
] {
assert_eq!(read_rule(by(name), rg, 255), read, "RG8 {name} read");
assert_eq!(write_rule(by(name), t)[..2], written, "RG8 {name} write");
}
// `R32Uint`: probe 1's reads and writes of `(11, 22, 33, 44)`, probe 9's zero texel.
let r = [1000, 0, 0, 1];
assert_eq!(read_rule(by("GRBA"), r, 1), [0, 1000, 0, 1]);
assert_eq!(read_rule(by("ARGB"), r, 1), [1, 1000, 0, 0]);
assert_eq!(read_rule(by("1RG0"), r, 1), [1, 1000, 0, 0]);
assert_eq!(read_rule(by("1RG0"), [0, 0, 0, 1], 1), [1, 0, 0, 0]);
assert_eq!(read_rule(by("ARGB"), [0, 0, 0, 1], 1), [1, 0, 0, 0]);
for (name, red) in [("RRRR", 11), ("GRBA", 22), ("ARGB", 22)] {
assert_eq!(
write_rule(by(name), [11, 22, 33, 44])[0],
red,
"R32Uint {name}"
);
}
}
// ---- The kernels ------------------------------------------------------------------------------
// ---- The interpreter --------------------------------------------------------------------------
/// Every committed profile, and `moltenvk-m3` and `lavapipe` without robustness, whose shader
/// checks its reads and guards its writes.
fn profiles() -> Vec<(String, DeviceProfile)> {
let mut out = crate::spirv::testing::committed_profiles().expect("profiles");
let all = [VkFeature::RobustImageAccess, VkFeature::RobustImageAccess2];
for stem in ["moltenvk-m3", "lavapipe"] {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../metal2vulkan-validation/profiles")
.join(format!("{stem}.json"));
let text = std::fs::read_to_string(path).expect("profile");
let mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description");
for f in &all {
desc.features.remove(f);
}
let p = Device::from_queries(desc)
.expect("device")
.profile()
.clone();
out.push((format!("{stem} unrobust"), p));
}
out
}
/// An atomic ignores the swizzle (`atomic_fetch_add` through a swizzled
/// `R32Uint` view adds to red and returns the texel unswizzled): `rrp_sw_atomic_u` under the
/// variant states no `TextureSwizzle` and compiles to the same words as without it (the
/// interpreter does not model image atomics).
#[test]
fn an_atomic_ignores_the_bound_swizzle() {
let bc = match llvm_assemble(&engine_dir().join("rrp_swizzled_storage.ll")) {
Ok(b) => b,
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
return;
}
Err(AssembleError::Rejected(why)) => panic!("rrp_swizzled_storage: {why}"),
};
let atomic = StorageImageChoice::new(vk::Format::R32_UINT, StorageImageClass::Identity);
let mut ran = 0;
for (stem, p) in profiles() {
let mut plain = LowerInputs::new();
plain.storage_images.insert(SLOT, atomic);
let mut swizzled = plain.clone();
swizzled.swizzled_storage.insert(SLOT);
let entry = "rrp_sw_atomic_u";
let (Ok(a), Ok(b)) = (
crate::pipeline::testing::compile_with(&bc, entry, &p, &plain),
crate::pipeline::testing::compile_with(&bc, entry, &p, &swizzled),
) else {
// A profile without the format's atomics refuses both alike.
continue;
};
let (plan, _) =
typed_module_with(&bc, entry, &p, &swizzled).unwrap_or_else(|e| panic!("{stem}: {e}"));
assert!(
!plan
.facts
.contains(&RuntimeFact::TextureSwizzle { slot: SLOT }),
"{stem}"
);
assert_eq!(a.module.words, b.module.words, "{stem}");
ran += 1;
}
assert!(ran > 0);
}
/// A `ulong` read of a slot under the variant is refused `NotImplemented(TextureSwizzle)`:
/// Metal's swizzled `ulong` texel is not measured.
#[test]
fn a_ulong_read_under_the_variant_is_refused() {
let bc = match llvm_assemble(&engine_dir().join("unk_ulong_rw.ll")) {
Ok(b) => b,
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
return;
}
Err(AssembleError::Rejected(why)) => panic!("unk_ulong_rw: {why}"),
};
let two_d = SlotRef { index: 2, ..SLOT };
let mut refused = 0;
for (stem, p) in profiles() {
if typed_module_with(&bc, "unk_ulong_rw", &p, &LowerInputs::new()).is_err() {
continue;
}
let mut i = LowerInputs::new();
i.swizzled_storage.insert(two_d);
match typed_module_with(&bc, "unk_ulong_rw", &p, &i) {
Err(Error::Unsupported(u)) => {
assert_eq!(u.feature, Feature::TextureSwizzle, "{stem}");
refused += 1;
}
other => panic!("{stem}: {:?}", other.map(|_| ())),
}
}
assert!(refused > 0);
}
// ---- The binder -------------------------------------------------------------------------------
-1
View File
@@ -169,7 +169,6 @@ mod engine_stage_root_attributes;
mod engine_stencil;
mod engine_stitched;
mod engine_store_quad;
mod engine_swizzled_storage;
mod engine_table_copies;
mod engine_tables;
mod engine_target_indices;
@@ -2099,7 +2099,6 @@ field metal2vulkan::cache::VariantKey.region_viewports pub region_viewports: boo
field metal2vulkan::cache::VariantKey.replay_bindings pub replay_bindings: bool
field metal2vulkan::cache::VariantKey.rotated_weights pub rotated_weights: bool
field metal2vulkan::cache::VariantKey.storage_images pub storage_images: BTreeMap<SlotRef, StorageImageChoice>
field metal2vulkan::cache::VariantKey.swizzled_storage pub swizzled_storage: BTreeSet<SlotRef>
field metal2vulkan::cache::VariantKey.zeroed_colors pub zeroed_colors: BTreeMap<u32, crate::metal::PixelFormat>
field metal2vulkan::device::AllocationLimits.max_buffer_size pub max_buffer_size: u64
field metal2vulkan::device::AllocationLimits.max_memory_allocation_size pub max_memory_allocation_size: u64
@@ -2617,7 +2616,6 @@ field metal2vulkan::pipeline::LoweringInputs.signed_color_attachments pub signed
field metal2vulkan::pipeline::LoweringInputs.srgb_storage pub srgb_storage: BTreeSet<SlotRef>
field metal2vulkan::pipeline::LoweringInputs.stage_input pub stage_input: Option<StageInputDescriptor>
field metal2vulkan::pipeline::LoweringInputs.storage_images pub storage_images: BTreeMap<SlotRef, StorageImageChoice>
field metal2vulkan::pipeline::LoweringInputs.swizzled_storage pub swizzled_storage: BTreeSet<SlotRef>
field metal2vulkan::pipeline::LoweringInputs.texture_write_rounding pub texture_write_rounding: metal::TextureWriteRoundingMode
field metal2vulkan::pipeline::LoweringInputs.threadgroup_size_matches_tile_size pub threadgroup_size_matches_tile_size: bool
field metal2vulkan::pipeline::LoweringInputs.tile_attachments pub tile_attachments: Option<BTreeMap<u32, metal::PixelFormat>>
@@ -10249,7 +10247,6 @@ variant metal2vulkan::pipeline::RuntimeFact::StageInRegion StageInRegion
variant metal2vulkan::pipeline::RuntimeFact::StageInStride StageInStride { layout: u32 }
variant metal2vulkan::pipeline::RuntimeFact::StencilBitDraws StencilBitDraws
variant metal2vulkan::pipeline::RuntimeFact::StorageTextureNumericType StorageTextureNumericType { slot: SlotRef }
variant metal2vulkan::pipeline::RuntimeFact::TextureSwizzle TextureSwizzle { slot: SlotRef }
variant metal2vulkan::pipeline::RuntimeFact::ThreadgroupMemoryLength ThreadgroupMemoryLength { index: u32 }
variant metal2vulkan::pipeline::RuntimeFact::ThreadsPerThreadgroup ThreadsPerThreadgroup
variant metal2vulkan::pipeline::RuntimeFact::TileAttachmentFormat TileAttachmentFormat { color: u32, format: crate::metal::PixelFormat }
Can't render this file because it is too large.