Files
metal2vulkan/validation/src/texture.rs
T
Anees Iqbal 8d982e649e Fix MS/sampler/FC-gating lowering and re-bank execution ledgers
Consolidates the translation fixes surfaced by post-runner triage of the private
corpus, together with the validation-harness work needed to actually run and compare
those cases, and re-banks execution evidence for all three backends.

63 files, +31,520/-6,780. Translator: 51 files under src/, +6,670/-314. Validation
crate: 7 files under validation/src/, +24,813/-6,410. The four
validation/corpus/metal2vulkan-ledger*.jsonl files are Git LFS pointers, so the
tracked diff is 4 lines while the referenced objects are fully re-banked.

================================================================================
Translation fixes
================================================================================

Texture and sampler lowering
  src/passes/air_calls/images/{mod.rs,write_read.rs,sample_depth.rs},
  src/passes/air_calls/dispatch_texture.rs, src/passes/resources/texture_array.rs
- AIR `texture2d_ms` / multisample depth reads now build a multisampled
  `OpTypeImage` (MS=1) and pass the sample id as a `Sample` image operand instead of
  treating it as a mip `Lod`. Multisample size queries use `OpImageQuerySize`
  without a LOD operand.
- Texel-buffer reads (`Dim Buffer`) omit the `Lod` operand entirely; `Dim Buffer`
  has no mip levels, so the operand was invalid.
- Depth sampling and compare-depth paths that select between AIR `constexpr sampler`
  state globals now resolve to a real SPIR-V sampler id, so `OpSampledImage` always
  receives a valid sampler operand.
- Texture-array descriptors carry (dim, arrayed, component type, MS) so array
  element image types match the declared AIR texture type.

Fragment stage interface
  src/meta/{mod.rs,globals.rs,tests.rs}, src/passes/stage_input/{mod.rs,air_layout.rs},
  src/reflect/mod.rs, src/passes/resources/discovery.rs
- New `FragRole::SampleId` and `FragRole::FrontFacing`. `[[sample_id]]` lowers to
  `BuiltIn SampleId` with the required `SampleRateShading` capability;
  `[[front_facing]]` lowers to `BuiltIn FrontFacing`.
- Function-constant-gated `[[color(n)]]` outputs now follow the AIR default-zero
  predicate model (`function_constant_gate_global` /
  `output_metadata_enabled_by_default`), so two mutually exclusive render-target
  formats no longer advertise themselves at the same Vulkan location.

Pointer and access-chain legality under Logical addressing
  src/passes/access/{dynamic_reinterpret.rs,mod.rs}, src/spirv_variable_ptr.rs,
  src/native/emitter/body/{gep_provenance.rs,core_inst.rs,mod.rs,vector_store.rs,
  reinterpret_pointer.rs}, src/native/emitter/pointers/*
- Dynamic sub-word views (`half`/`ushort`/`uchar`) of a raw `{ RuntimeArray<uint> }`
  buffer block lower to `dyn / lanes_per_word` for the backing word plus a lane
  extract/insert, rather than an illegal single dynamic index into the Block struct.
- Dynamic 64-bit views (`ulong`/`long`/`double`) of the same raw model address
  `word = dyn * 2` and `word + 1`, assembling/splitting the scalar little-endian.
- A dynamic index into a homogeneous `OpTypeStruct` (an `[N x T]` array that LLVM
  bitcasts exposed as N identical members) becomes a select over constant-member
  loads, since SPIR-V struct indices must be constants.
- Zero-stride `OpPtrAccessChain` on StorageBuffer demotes to a plain
  `OpAccessChain`; Private palette-array pointer phis likewise use ordinary access
  chains instead of pointer-stride forms.
- Struct-global GEPs (inline and promoted) preserve their zero member index, and
  flat-scalar global views translate through view indices.
- Large dynamic vector extract/insert lowers through composite selects.
- Pointer `OpIEqual`/`OpINotEqual` against loop cursor/end pointers reserves forward
  GEP phi root provenance; unmodeled device GEP phis take a placeholder rather than
  emitting an invalid pointer phi.
- Function-scope aggregate scalar-reinterpret stores target member 0.

Function constants
  src/fc_specialize.rs, src/passes/air_calls/integer_simd.rs
- `air.is_function_constant_defined` now emits a named
  `__metal2vulkan.MTL_FC_DEFINED_<N>` marker that specialization rewrites to
  `OpConstantTrue`/`OpConstantFalse`: all predicates true under zero specialization,
  only the listed indices true under value specialization.
- Value specialization materializes vector-integer FC initializers (lanes split out
  of the little-endian value) and rewrites thread-local byte-subslot stores.

Module cleanup, CFG repair, and retry
  src/native/rewrites.rs, src/native/relooper.rs, src/retry.rs, src/lib.rs,
  src/native/error_class.rs, src/passes/module_cleanup.rs,
  src/native/emitter/ops/atomics.rs, src/native/emitter/functions.rs,
  src/native/emitter/body/calls.rs, src/native/ir/ordinary_inline/mod.rs
- `drop_workgroup_struct_padding_byte_zero_stores_module` removes byte-addressed
  Workgroup padding clears produced from `llvm.memset.p3`; an `OpPtrAccessChain
  %uchar*` from a `%struct*` base is not expressible in Logical addressing, and the
  stores are value-preserving to drop (harness zero-fills, no typed load can observe
  the padding). Real member stores are kept.
- `drop_dangling_debug_targets_module` removes `OpName`/annotation records whose
  target id an earlier rewrite deleted (constant-branch pruning of FC helper
  globals). Both run in `finish_module` before validation, so the retry cascade only
  sees semantic failures.
- The relooper rematerializes pure opaque image/descriptor loads at their use: an
  opaque handle loaded in a non-entry block dominates in the original CFG but not
  once both blocks become sibling switch cases, and handles cannot spill to memory.
- `inline_sroa_raw_relooped` uses the capped relooper, runs
  `repair_relooped_access_chains`, and can escalate through PSB/WG remodel; a new
  `inline_sroa_raw_cfg_restructure` tier joins the cascade for the TopK
  multi-destination shape.
- `reject_visible_function_references` is now
  `reject_unsupported_metal_linked_functions` and also fails fast on
  `air.patch_control_point_function` / `.MTL_CONTROL_POINT_FN`, since tessellation
  patch inputs are not lowered.
- The pointer-typing error classifier recognizes spirv-val's "does not match the
  type that results from indexing into the Composite".
- StorageBuffer atomics carrying Workgroup scope rewrite to Device/Relaxed, and AIR
  barrier memory scope/semantics derive from the barrier's device flag so a
  threadgroup barrier orders StorageBuffer memory.
- Internal calls skip extra AIR ABI operands by formal parameter type.

Tests
  ~38 new unit/integration tests across src/native/tests/{textures,buffers,interface,
  control_flow,intrinsics,threadgroup,types,misc}.rs, src/passes/access/mod.rs,
  src/fc_specialize.rs, src/native/rewrites.rs, src/native/relooper.rs,
  src/spirv_variable_ptr.rs, src/meta/tests.rs.

================================================================================
Validation harness
================================================================================

validation/src/loop_budget.rs (+7,669/-638)
- The pre-submission loop-budget classifier now accepts `LoopInputFacts`: function
  constant values, exact and upper-bound integer/float argument values, constant-GEP
  struct field values, integer vector lane values and bounds, bound texture extents,
  and the imageblock extent. Facts propagate through direct calls, and
  classification starts from the entry function instead of the whole module. Far
  more loops are provably bounded, which is what moves Metal quarantine 2,480 -> 18.

validation/src/oracle_macos.rs (+1,779/-21)
- Derives those facts from AIR metadata plus the concrete bound inputs
  (`exact_scalar_arg_values`, `exact_launch_vector_arg_values`,
  `exact_texture_extent_values`, `exact_struct_arg_values`, ...) and substitutes
  imageblock extent/implicit-load AIR calls with constants before `metal-as`.

validation/src/corpus_run.rs (+14,982/-5,643)
- Seed profile `deterministic_v6_finite_float_render_targets` ->
  `deterministic_v7_thread_indexed_inputs`: thread-indexed input buffers are resized
  to the dispatch grid, output-stride seeds are applied, atomic-counter and
  read-only buffer arguments are recognized, and bounded-control seeding covers
  float vector lanes and result-dimension struct fields.
- Default per-case timeout 60s -> 300s.
- Function-constant value selection for oracle inputs, integer divisors, and
  barrier-loop progress, plus collision detection for conditionally bound resources.
- New incompatible-golden detectors: multisample textures, FC texture-array refs, FC
  private pointer tables, FC simdgroup, and `compare=none` simdgroup-matrix /
  raytracing smoke kernels.
- `--compile-missing` mode: cases with no comparable Metal golden are translated and
  recorded as `smoke` rows carrying the skip reason in `error`, instead of being
  left as empty `missing` cells.

validation/src/runner_linux.rs (+326/-71)
- Derives the full set of fragment color attachments from `air.render_target`
  metadata and the output locations the SPIR-V actually writes, and creates the
  extra attachment views, instead of assuming location 0 only.
- Enables and preflights the `sampleRateShading` feature / `SampleRateShading`
  capability.
- Compute/vertex pipeline creation returns `Result` rather than panicking.

validation/src/corpus_triage.rs
- `tolerance` counts as success only for the Vulkan candidate backend; MoltenVK must
  match the Metal golden byte-exactly.

validation/src/texture.rs
- `depthcube<...>` / `depthcube_array<...>` map to cube / cube-array texture kinds,
  which previously fell through to `Plain`.

================================================================================
Ledger re-bank (rows keyed by air_sha256, last write wins)
================================================================================

"Passing" below means ok + tolerance, i.e. the row reproduced the Metal golden
exactly or within the documented per-format tolerance. Note that this commit also
tightens `execution_status_is_success`: tolerance now counts only for the Vulkan
candidate backend (Metal and MoltenVK require exact `ok`), so the MoltenVK
tolerance rows are reported here for completeness but no longer bank as passes.

Metal goldens (metal2vulkan-ledger-metal.jsonl)  43,514 -> 43,622 rows
  passing      39,986 -> 42,124  (96.6%)   no tolerance rows on either side
  ok           39,986 -> 42,124      quarantine    2,480 ->     18
  fallback      1,048 ->  1,476      timeout           0 ->      4
  comparable goldens (compare=full) 20,336 -> 23,430
  Transitions: quarantine->ok 2,058, quarantine->fallback 404, 108 new rows,
  ok->fallback 23, ok->timeout 4, fallback->ok 3.

MoltenVK (metal2vulkan-ledger-moltenvk.jsonl)    37,136 rows
  passing      28,743 -> 30,089  (81.0%)   = ok 30,089 + tolerance 0
  ok           28,660 -> 30,089      failure       3,828 ->      0
  tolerance        83 ->      0      fallback      1,333 ->      0
  quarantine      491 ->    136      timeout         473 ->      0
  missing       2,268 ->  6,911
  Transitions: failure->ok 538, fallback->ok 410, missing->ok 286,
  quarantine->ok 184, tolerance->ok 11; failure->missing 3,290,
  fallback->missing 923, timeout->missing 473, quarantine->missing 172,
  tolerance->missing 72.

Vulkan / Linux (metal2vulkan-ledger-vulkan.jsonl) 39,090 rows
  passing       5,970 ->  9,823  (25.1%)   = ok 9,243 + tolerance 580
  ok            3,341 ->  9,243      smoke            17 -> 28,846
  tolerance     2,629 ->    580      missing      31,277 ->      0
  quarantine    1,826 ->    421
  Transitions: missing->ok 7,094, tolerance->ok 218, quarantine->ok 148;
  missing->smoke 23,484, tolerance->smoke 2,219, quarantine->smoke 1,568,
  ok->smoke 1,558.

Net state: 42,124 of 43,622 Metal golden rows pass, and 30,089 of 37,136 MoltenVK
rows pass -- all of them exact, byte-identical to the Metal golden they were
compared against, with no tolerance rows left in that ledger. That is ~30k
Metal/MoltenVK pairs in sync out of a ~43.6k-case corpus. On Linux Vulkan 9,823
rows pass (9,243 exact + 580 within tolerance), up from 5,970; the 28,846 `smoke`
rows are compile-only evidence with a recorded reason why no semantic compare was
possible, replacing the 31,277 blank `missing` cells.

Caveats worth stating plainly: a large share of the MoltenVK `failure`/`fallback`/
`timeout` reduction is reclassification, not repair -- 4,930 rows became `missing`
because re-banking the Metal side under seed profile v7 invalidated their golden,
against 1,346 net rows genuinely turning passing (28,743 -> 30,089). Likewise 1,558
Vulkan rows regressed from `ok` to compile-only `smoke` because their golden is no
longer comparable, and 2,219 more moved from `tolerance` to `smoke`.

The translate ledger (metal2vulkan-ledger.jsonl) is carried forward essentially
unchanged: 43,657 rows, 39,090 ok / 4,557 fallback / 10 timeout, with a single row's
SPIR-V digest re-minted.
2026-07-29 14:35:45 +03:00

313 lines
11 KiB
Rust

use crate::{
seeded_texture_bytes_for_extent, seeded_unit_rgba32_float_texture_bytes, DataFormat, Extent3d,
TextureInput, TextureRole,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum TextureKind {
Dim1d,
Dim1dArray,
Dim3d,
Plain,
Dim2dArray,
Cube,
CubeArray,
}
pub(crate) fn texture_seed_bytes(
input: &TextureInput,
kind: TextureKind,
extent: Extent3d,
) -> Vec<u8> {
if matches!(kind, TextureKind::Cube | TextureKind::CubeArray)
&& input.format == DataFormat::Rgba32Float
&& input.role == TextureRole::Sampled
{
return seeded_unit_rgba32_float_texture_bytes(extent);
}
seeded_texture_bytes_for_extent(input, extent)
}
pub(crate) fn texture_seed_extent(extent: Extent3d, kind: TextureKind) -> Extent3d {
match kind {
TextureKind::Dim1d => Extent3d::new(extent.width, 1, 1),
TextureKind::Dim1dArray => Extent3d::new(extent.width, 1, extent.depth.max(1)),
TextureKind::Cube => Extent3d::new(extent.width, extent.height, 6),
TextureKind::CubeArray => {
Extent3d::new(extent.width, extent.height, 6 * extent.depth.max(1))
}
TextureKind::Plain | TextureKind::Dim2dArray | TextureKind::Dim3d => extent,
}
}
pub(crate) fn texture_output_extent(extent: Extent3d, kind: TextureKind) -> Extent3d {
match kind {
TextureKind::Dim1d => Extent3d::new(extent.width, 1, 1),
TextureKind::Dim1dArray => Extent3d::new(extent.width, 1, extent.depth.max(1)),
TextureKind::Cube => Extent3d::new(extent.width, extent.height, 1),
TextureKind::CubeArray => Extent3d::new(extent.width, extent.height, extent.depth.max(1)),
TextureKind::Plain | TextureKind::Dim2dArray | TextureKind::Dim3d => extent,
}
}
#[cfg(any(target_os = "macos", test))]
pub(crate) fn texture_layer_count(extent: Extent3d, kind: TextureKind) -> usize {
match kind {
TextureKind::Dim1dArray | TextureKind::Dim2dArray => extent.depth.max(1) as usize,
TextureKind::Cube => 6,
TextureKind::CubeArray => extent.depth.max(1) as usize,
TextureKind::Dim1d | TextureKind::Dim3d | TextureKind::Plain => 1,
}
}
pub(crate) fn fragment_writes_depth(sanitized_ll: &str) -> bool {
sanitized_ll
.lines()
.any(|line| line.contains(r#""air.depth""#))
}
pub(crate) fn texture_kind(sanitized_ll: Option<&str>, texture_location: u32) -> TextureKind {
let Some(sanitized_ll) = sanitized_ll else {
return TextureKind::Plain;
};
if let Some(meta) = metal2vulkan::meta::parse_air_kernel_meta(sanitized_ll) {
let mut params = meta
.roles
.iter()
.filter_map(|(param_idx, role)| {
matches!(role, metal2vulkan::meta::KernRole::Texture(location) if *location == texture_location)
.then_some(*param_idx)
})
.collect::<Vec<_>>();
params.sort_unstable();
if let Some(param_idx) = params.into_iter().next() {
return texture_kind_from_type_name(meta.texture_type_name(param_idx));
}
}
if let Some(meta) = metal2vulkan::meta::parse_air_fragment_meta(sanitized_ll) {
let mut params = meta
.roles
.iter()
.filter_map(|(param_idx, role)| {
matches!(role, metal2vulkan::meta::FragRole::Texture(location) if *location == texture_location)
.then_some(*param_idx)
})
.collect::<Vec<_>>();
params.sort_unstable();
if let Some(param_idx) = params.into_iter().next() {
return texture_kind_from_type_name(meta.texture_type_name(param_idx));
}
}
if let Some(meta) = metal2vulkan::meta::parse_air_vertex_meta(sanitized_ll) {
let mut params = meta
.roles
.iter()
.filter_map(|(param_idx, role)| {
matches!(role, metal2vulkan::meta::VertRole::Texture(location) if *location == texture_location)
.then_some(*param_idx)
})
.collect::<Vec<_>>();
params.sort_unstable();
if let Some(param_idx) = params.into_iter().next() {
return texture_kind_from_type_name(meta.texture_type_name(param_idx));
}
}
TextureKind::Plain
}
pub(crate) fn texture_kind_from_type_name(name: Option<&str>) -> TextureKind {
match name {
Some(name) if name.starts_with("texture1d<") => TextureKind::Dim1d,
Some(name) if name.starts_with("texture1d_array<") => TextureKind::Dim1dArray,
Some(name) if name.starts_with("texture3d<") => TextureKind::Dim3d,
Some(name) if name.starts_with("texture2d_array") || name.starts_with("depth2d_array") => {
TextureKind::Dim2dArray
}
Some(name)
if name.starts_with("texturecube_array<") || name.starts_with("depthcube_array<") =>
{
TextureKind::CubeArray
}
Some(name) if name.starts_with("texturecube<") || name.starts_with("depthcube<") => {
TextureKind::Cube
}
_ => TextureKind::Plain,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Seed;
#[test]
fn static_type_names_map_to_shared_texture_kinds() {
assert_eq!(
texture_kind_from_type_name(Some("texture1d<float, sample>")),
TextureKind::Dim1d
);
assert_eq!(
texture_kind_from_type_name(Some("texture1d_array<float, sample>")),
TextureKind::Dim1dArray
);
assert_eq!(
texture_kind_from_type_name(Some("texture3d<float, write>")),
TextureKind::Dim3d
);
assert_eq!(
texture_kind_from_type_name(Some("texture2d_array<float, read>")),
TextureKind::Dim2dArray
);
assert_eq!(
texture_kind_from_type_name(Some("depth2d_array<float, sample>")),
TextureKind::Dim2dArray
);
assert_eq!(
texture_kind_from_type_name(Some("texturecube<float, sample>")),
TextureKind::Cube
);
assert_eq!(
texture_kind_from_type_name(Some("depthcube<float, sample>")),
TextureKind::Cube
);
assert_eq!(
texture_kind_from_type_name(Some("texturecube_array<float, sample>")),
TextureKind::CubeArray
);
assert_eq!(
texture_kind_from_type_name(Some("depthcube_array<float, sample>")),
TextureKind::CubeArray
);
assert_eq!(
texture_kind_from_type_name(Some("texture2d<float, sample>")),
TextureKind::Plain
);
assert_eq!(texture_kind_from_type_name(None), TextureKind::Plain);
}
#[test]
fn air_metadata_selects_texture_kind_by_stage_and_location() {
let kernel = r#"
!air.kernel = !{!0}
!0 = !{ptr @k, !1, !2}
!1 = !{}
!2 = !{!3}
!3 = !{i32 0, !"air.texture", !"air.location_index", i32 5, i32 1, !"air.read", !"air.arg_type_name", !"texture3d<float, read>"}
"#;
let duplicated_kernel_location = r#"
!air.kernel = !{!0}
!0 = !{ptr @k, !1, !2}
!1 = !{}
!2 = !{!3, !4}
!3 = !{i32 0, !"air.function_constant", !5, !"air.texture", !"air.location_index", i32 5, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d<float, sample>"}
!4 = !{i32 1, !"air.function_constant", !6, !"air.texture", !"air.location_index", i32 5, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d_array<float, sample>"}
!5 = !{}
!6 = !{}
"#;
let fragment = r#"
!air.fragment = !{!0}
!0 = !{ptr @f, !1, !3}
!1 = !{!2}
!2 = !{!"air.render_target", i32 0, i32 0}
!3 = !{!4}
!4 = !{i32 0, !"air.texture", !"air.location_index", i32 6, i32 1, !"air.sample", !"air.arg_type_name", !"texturecube<float, sample>"}
"#;
let vertex = r#"
!air.vertex = !{!0}
!0 = !{ptr @v, !1, !2}
!1 = !{}
!2 = !{!3}
!3 = !{i32 0, !"air.texture", !"air.location_index", i32 7, i32 1, !"air.read", !"air.arg_type_name", !"texture1d<float, read>"}
"#;
assert_eq!(texture_kind(Some(kernel), 5), TextureKind::Dim3d);
assert_eq!(
texture_kind(Some(duplicated_kernel_location), 5),
TextureKind::Plain
);
assert_eq!(texture_kind(Some(fragment), 6), TextureKind::Cube);
assert_eq!(texture_kind(Some(vertex), 7), TextureKind::Dim1d);
assert_eq!(texture_kind(Some(kernel), 99), TextureKind::Plain);
assert_eq!(texture_kind(None, 5), TextureKind::Plain);
}
#[test]
fn sampled_float_cube_uses_shared_unit_seed_override() {
let extent = Extent3d::new(2, 2, 6);
let input = TextureInput {
index: 0,
format: DataFormat::Rgba32Float,
extent,
role: TextureRole::Sampled,
seed: Seed::ZeroForTest {
reason: "shared texture helper test",
},
};
assert_eq!(
texture_seed_bytes(&input, TextureKind::Cube, extent),
seeded_unit_rgba32_float_texture_bytes(extent)
);
assert_eq!(
texture_seed_bytes(&input, TextureKind::Plain, extent),
seeded_texture_bytes_for_extent(&input, extent)
);
}
#[test]
fn shared_shape_policy_handles_1d_cube_and_arrays() {
let extent = Extent3d::new(8, 8, 3);
assert_eq!(
texture_seed_extent(extent, TextureKind::Dim1d),
Extent3d::new(8, 1, 1)
);
assert_eq!(
texture_seed_extent(extent, TextureKind::Dim1dArray),
Extent3d::new(8, 1, 3)
);
assert_eq!(
texture_output_extent(extent, TextureKind::Dim1d),
Extent3d::new(8, 1, 1)
);
assert_eq!(
texture_output_extent(extent, TextureKind::Dim1dArray),
Extent3d::new(8, 1, 3)
);
assert_eq!(
texture_seed_extent(extent, TextureKind::Cube),
Extent3d::new(8, 8, 6)
);
assert_eq!(
texture_output_extent(extent, TextureKind::Cube),
Extent3d::new(8, 8, 1)
);
assert_eq!(
texture_seed_extent(extent, TextureKind::CubeArray),
Extent3d::new(8, 8, 18)
);
assert_eq!(
texture_output_extent(extent, TextureKind::CubeArray),
Extent3d::new(8, 8, 3)
);
assert_eq!(texture_layer_count(extent, TextureKind::Dim2dArray), 3);
assert_eq!(texture_layer_count(extent, TextureKind::Dim1dArray), 3);
assert_eq!(texture_layer_count(extent, TextureKind::Cube), 6);
assert_eq!(
texture_layer_count(
texture_seed_extent(extent, TextureKind::CubeArray),
TextureKind::CubeArray
),
18
);
assert_eq!(texture_layer_count(extent, TextureKind::Dim3d), 1);
}
#[test]
fn depth_output_metadata_is_detected() {
assert!(fragment_writes_depth(r#"!1 = !{!"air.depth", i32 0}"#));
assert!(!fragment_writes_depth(
r#"!1 = !{!"air.render_target", i32 0}"#
));
}
}