Files
metal2vulkan/docs/ARCHITECTURE.md
T
Anees Iqbal 78ed264c90 Drop the normalized vertex attribute's exact division (vertex_normalized)
One work packet, landed as 9 commits (9c0bdbe0d2..41066d87d0 on archive/development-linear-2026-10-28), in order:

* Drop the normalized vertex attribute's exact division (vertex_normalized)

The owner's ruling of 2026-10-27: the GPU's native arithmetic is the contract, no exact
emulation. A normalized vertex attribute is now always the device's fixed-function UNORM or
SNORM conversion; the policy-forced pull that divided its codes in the shader goes with
DevicePolicy::vertex_normalized, VertexNormalizedPolicy, its profile field, its ledger row and
its tests. A format pulled for any other reason (a format the device cannot fetch, alignment,
limits, containment, the capture form) still decodes in the shader as before.

Verified: cargo clippy --workspace --all-targets --all-features -D warnings clean; nextest of
engine_vertex_variants, device::tests::profile, fast_paths, catalogue, degradation and
api_surface: 71 passed. api_signatures is re-blessed at the end of the lane.

* Keep the compact decoded twin only (decoded_texels)

The owner's ruling of 2026-10-27: no exact emulation. A carried ASTC LDR texture's decoded
twin now always holds 8-bit codes, and an EAC 11-bit texture's 16-bit normalized codes (its
values in floats only where the device does not take those codes' format, a capability
fallback). DevicePolicy::decoded_texels and DecodedTexelsPolicy go, with their ledger row,
their mentions in the degrade catalogue and the runtime's docs, the policy-keyed fingerprint
test, and the validation lanes' exact twins. decoded-texel-precision is announced as before.
bind::AstcTexels::Float stays: the conformance suite's cross-check decodes Metal's values with
it. RUNTIME_VERSION 1654.

Verified: clippy --workspace --all-targets --all-features -D warnings clean, plain and with
--cfg m2v_gpu; nextest of fast_paths, device profile, degradation and catalogue, image_plan's
decode bands, the conformance ASTC and ETC cases, api_surface: 112 passed.

* Take the device's texel conversion only (texel_conversion)

The owner's ruling of 2026-10-27: no exact emulation. A read, sample or gather with a float
or half result off Apple's GPUs is now always the device's conversion of the texel's codes,
recorded as DeviceTexelConversion or HalfTexelConversion. DevicePolicy::texel_conversion and
TexelConversionPolicy go, with Metal's conversion by the bound format's class:
lower::texture::float_texel (its routine, census entry and tests), the float_texel plan flags of
reads and samples, the slots' float_format and the heap's float class, and the field of
RuntimeFact::ExactFormsOverCompilerLimit that named it (encoded, so ARTIFACT_FORMAT_VERSION
456; SEMANTICS_VERSION 1873). The ledger row goes; DeviceTexelConversion is now documented in
docs/API.md section 9 alone (fast_paths classes it Elsewhere), and the conformance cases cite
the note's bound in place of the row. The half routine on Apple's GPUs is untouched.

Verified: clippy --workspace --all-targets --all-features -D warnings clean, plain and with
--cfg m2v_gpu; nextest of fast_paths, device profile, catalogue, degradation, the fit, mechanism,
codec, the snapshot variant, engine_handles, the extended-range heap tests, the texel-conversion
test (rewritten for the device's form alone), the conformance ETC, BC and border cases and the
runtime's fitted-variant notice: passed (one exact-conversion test deleted).

* Take the device's filter of a two-plane YCbCr texture only (ycbcr_filter)

The owner's ruling: promise the GPU's native arithmetic, no exact emulation.
YCbCrFilterPolicy and its Exact form go: no slot takes a YCbCr variant
(RuntimeFact::YCbCrTexture, VariantKey and LoweringInputs::ycbcr_textures,
ProfileFields::ycbcr_variant, Linear::exact_only and the binder's
ycbcr_variant are gone). A natively sampling device filters such a texture's
texels (device-sampling); on MoltenVK Metal's own sampler filters them,
noted where the bound format is two-plane YCbCr (ycbcr-filter-not-exact).
The planes read in place on a device whose memory is the host's are kept:
that is a capability path, Metal's filter exactly.

The FAST-PATHS row goes; HalfTexelConversion, which only that row named, is
classed Elsewhere (API.md's catalogue states it). The YCbCr tests keep the
default's selection and drop the variant's; the uniform-branch test runs at
the default policy; the validation lane's Exact draw test goes.

Verified: cargo clippy --workspace --all-targets --all-features -D warnings,
plain and with --cfg m2v_gpu, clean. nextest over fast_paths, device::tests,
bind::plan, compile::fit, compile::tests, engine_linear_half, catalogue,
degradation, api_surface, codec, cache: 372 passed, 5 failed. The five are
engine_linear_half tests of the emulated sampler on lavapipe and MoltenVK
under EXACT_SAMPLING (the_emulation_reaches_what_metal_measured,
the_linear_sums_run_one_by_a_branch_and_stay_calls,
swizzled_packed_texels_are_the_unswizzled_swizzled,
a_pipelines_texture_notes_follow_its_bound_format_and_sampler,
a_depth_comparison_through_a_filter_is_a_filtered_float_sample); they go with
the emulated sampler in the next step. api_signatures is re-blessed at the
end of the lane.

* Take the device's sampler only (sampling, unorm8_linear_filter)

The owner's ruling of 2026-10-27: promise the GPU's native arithmetic, no
exact emulation. Metal's sampler emulated by fetches (SamplingPolicy::Exact,
a pipeline per bound sampler state) and the device's 8-bit unorm filter at
Metal's footprint step (Unorm8LinearFilterPolicy) are gone with their
switches: every sample, gather and comparison goes to the device's sampler,
Metal's own on MoltenVK (VkProperty::MetalSampler) and the device's
elsewhere (VkProperty::DeviceSampling, PrecisionNote::DeviceSampling).

Deleted: lower/sampler/compared.rs, native.rs, linear/compare.rs,
linear/cube.rs, the nearest and level snaps, the cube face position and
fold (face::snapped, FaceWrap), the span and cube bicubic routines, the heap
depth class (FLAG_DEPTH_*, HANDLE_DEPTH_*, Lookup::Flagged's depth), the
normalized gather snap and the runtime sampler's anisotropic bias route.
Notes nothing records any more are deleted with their catalogue and codec
entries and the runtime's Degradation kinds: DeviceGatherFootprint,
CubeFaceReciprocal, DeviceDepthComparison, DeviceTexelDenormals,
DeviceUnorm8LinearFilter. The fit drops the sampling field of
ExactFormsOverCompilerLimit and makes every module-growing form native in
one reduction.

Kept as capability: bicubic, extended range, heap raw reads, YCbCr planes
read in place (its tests move to engine_ycbcr_in_place), constexpr pixel
samplers' snaps and fetches, the runtime pixel word's gather and footprint
cell, Metal's cube face at a tie, the anisotropic emulation without
samplerAnisotropy and for an unmeasured cube-gradient route, the
VkSampler level clamp on Metal's grid.

Validation and conformance follow: the lanes judge the device's filter
within two codes where it samples natively, the anisotropic lane runs with
samplerAnisotropy withheld, and the conformance cases drop their
device-texel-denormals declarations. docs/API.md, FAST-PATHS.md,
ARCHITECTURE.md, CONTRIBUTING.md and VALIDATION.md updated.

Verified so far: cargo check of the workspace, all targets and features,
plain and --cfg m2v_gpu; 1000 of 3664 translator lib tests passed before
the run was stopped for the rebase.

* Join the device-sampler deletions with development's half and write removals

The rebase onto development left two joins only a build shows:

- `packed_scales` and `PackedField::small` lost their last readers (the
  float texel conversion this branch deleted and the normalized write
  development deleted): both go.
- `engine_srgb_raw` takes `DevicePolicy::default()` where development's
  side named `EXACT_SAMPLING`, so it imports `DevicePolicy` again.

Also formats the conflict resolutions (`cargo fmt --all`).

Verified: `cargo check --workspace --all-targets --all-features` passes.

* Drop the sampler word's snap and level-rule fields with their last readers

With every sample the device's own, no function reads a runtime sampler's
nearest snap (`SamplerWord::NEAREST_BASE`, `NEAREST_SNAP`, `NEAREST_LEVEL`,
`LEVELED_SNAP`) or its level rule (`LEVEL_RULE`); only tests named them.
The constants go, with the word test of the base-level mask; the
`VkSampler` clamp on Metal's level grid (`clamps_on_grid`) stays, and its
docs no longer say the shader reads the rule.

The runtime-sampler tests of `engine_sampler` asked, off MoltenVK, for the
emulation's linear state, leveled snap and level rule: they now state the
device's sample on every committed profile (the pixel fields alone, gated;
`MetalSampler` on MoltenVK, `DeviceSampling` elsewhere; no level field).

Also matches `SnapKind::WordGather` as the unit variant it is (clippy).

Verified: clippy (all targets, all features, -D warnings) passes.

* Test the anisotropic, bias and position paths as the device's sampler runs them

The tests of these paths compiled under the exact sampling policy, which
is gone; under the default each now states what the translation does:

- Metal's anisotropic filter is emulated only without `samplerAnisotropy`
  (and on MoltenVK's unmeasured cube-gradient route), so the emulation's
  shape tests compile on committed profiles with the feature withheld,
  and their MoltenVK arms on the profile as described. An isotropic cube
  keeps the device's gradient sample except on the unmeasured route.
- A bias through a sampler without its own is the `Bias` operand on every
  profile (one test over MoltenVK, RADV, lavapipe and the floor); the
  compile-time and anisotropic axis-gradient tests take a constexpr
  sampler with its own bias, the only one that reaches them. The runtime
  slot's word-chosen axis gradients have no reader left: its test goes,
  with the helpers only it used.
- The position kernel writes three words a lane: its record stride is 12
  bytes, not 16, and the by-word gather test's lane floor matches its
  single pass.

Verified: `cargo check -p metal2vulkan --tests --all-features` clean; the
tests run after the rebase onto development.

* Rewrite the sampling tests and notes for the device's sampler

The sampling, texel-conversion and YCbCr-filter emulations are gone, so
the tests that pinned them now pin the device's answer, and the note
docs that described them describe what the module records today.

Tests: the sampler-unk, anisotropic cube, depth-range, bicubic,
dynamic-offset, heap half-texel, shared-switch, sRGB raw view,
swizzled packed and texture-interpreter families. Deleted the tests of
the emulated linear filter over raw sRGB codes (constexpr and runtime),
the runtime sampler's one-texel raw sample and its switch, the shader's
linear depth comparison, the bicubic small-level comparison against the
linear emulation and the depth read's class conversion; the shared
switch keeps the bicubic emulation alone. A NaN texel's half read only
needs to read a NaN under the default policy.

Docs: HalfSampleFilter, FloatSampleFilter, SrgbTexelDecode,
AnisotropicFilter, DeviceAnisotropicFilter, ViewBaseTexelOffset and
HalfTexelConversion in artifact.rs, RuntimeFact::TexelFormat, the heap
class flag, texel_format_spec and a few comments that still named the
emulated linear filter, snapped gathers or the shader's comparisons.

Verified: plain clippy over the workspace with all targets and
features; the touched families under nextest (see the next commits for
the full runs).
2026-10-28 17:24:20 +02:00

12 KiB

Architecture

How the translator turns AIR into Vulkan pipelines: the stages, the rules that hold across them, and where each piece lives. The consumer's view of the same flow is API.md.

The pipeline

metallib | AIR bitcode
  ── parse ───────► Library: the container's functions                  air::container, library
  ── decode ──────► a typed AIR module and its ABI                      air::{bitstream, bitcode, ir, intrinsics, abi}
  ── specialize ──► one inlined entry: function constants baked,        air::canon
                    constants propagated, linked functions resolved,
                    pointee types erased
  ── analyze ─────► MemoryPlan: provenance, one representation          memory
                    per value, slot windows
  ── select ──────► Plan: a strategy per instruction and interface      lower::select, lower::strategy
                    element, push-constant placement, requirements,
                    the output-size estimate (checked here)
  ── structurize ─► a structured tree over the AIR CFG                  structurize
  ── emit ────────► a typed SPIR-V module through the builder           structurize::emit, lower::*, spirv::builder
  ── tidy ────────► single-store promotion, dead values removed,        structurize::promote, spirv::{dead, roll}
                    repeated regions of large entries rolled into loops
  ── verify ──────► the full verifier; requirements within the profile  spirv::verify, spirv::requirements
  ── serialize ───► SPIR-V 1.5 words with typed relocations             spirv::serialize
  = CompiledFunction, keyed by FunctionCompileKey (the caller may cache it)
  ── link ────────► bindings, Locations, spec ids, the pipeline         pipeline::link
                    layout, pipeline-wide limits, the generated         pipeline::link::geometry
                    geometry stages (barycentric weights read as
                    varyings, a selected slice or viewport stored
                    from the first vertex)
  ── relocate ────► the final words of each stage                       pipeline::relocate
  = ComputePipeline | RenderPipeline | tile and mesh pipelines

BindState ── shape ──► BindingPlan (per pipeline and shape) ── instantiate ──► dispatch or draw commands   bind

pipeline::compile::compile_stage runs one function from decode to serialize and keeps only the relocatable module and plain metadata; the decoded AIR, the plan and the typed module are dropped before it returns. It runs under catch_unwind, so a panic in the core becomes Error::Internal, never an unwind into the caller.

Three rules hold across the arrows:

  • Each stage maps valid typed input to valid typed output. No stage produces a form a later stage repairs, and nothing parses SPIR-V words to decide what to emit.
  • Nothing after select changes which instructions a function contains, except the tidy passes, which preserve meaning. Link and relocate write only literal numbers (descriptor set and binding, Location, SpecId) into slots the serializer reserved, so one compiled function is reused by every pipeline it links into.
  • One representation per feature and device, chosen before emission. select decides every strategy from the AIR and the device profile. There are no retries, no candidate modules and no validator in the loop. A family that cannot lower an input refuses it.

The library runs no external tool: it reads bitcode with its own reader and verifies with its own verifier. The command line adds llvm-as for .ll input and spirv-val as an independent check.

Where each piece lives

The AIR front end is its own crate, metal2vulkan-air (crates/metal2vulkan-air/src/). The translator names it air, with its graph and budget modules at the translator's root. The rest is crates/metal2vulkan/src/.

Module Role
air (metal2vulkan-air) The container (metallib, bitcode wrapper, raw module), the bitstream and bitcode readers, the typed IR, the air.* and llvm.* intrinsic families, the metadata ABI (AirAbi), and canonicalization (canon: inlining, function constants, SCCP, devirtualization, linking, pruning, pointee erasure, and the speculation of the short branch arms Metal's backend runs in every lane). Canonicalization also writes the formats the binder and runtime read: the visible-function table's words and the rasterization-rate map's parameter data
graph The shared RPO, dominator tree, loop forest and SCC
budget Budget, CancelToken, and the per-attempt Meter: deadline, cancellation, work units, the byte ledger and every structural cap
memory/ Pointer provenance, the MemoryPlan, leaf access emitters, arenas, root and handle lookups, word composition, atomics
lower/ select (routing every instruction, intrinsic and parameter into the Plan), strategy, push (push-constant placement), estimate (output size), specialized (bound-texture values read as push data), and one module per family: arith, access, texture, sampler, simd, sync, fragment, stage_io, dispatch, tessellation, mesh, raytracing
structurize/ The structurizer over the AIR CFG, the emit walk that drives the families, and single-store promotion
spirv/ The typed SPIR-V IR and interners, the module and function builders, dead-value removal, the roll pass, the verifier, requirement derivation and the serializer. spirv::interp is a CPU interpreter used only by tests
spv.rs The SPIR-V grammar's opcodes and enumerants the translator names, generated from Khronos's grammar (scripts/regen-spirv-grammar/)
spirv_binary/ A reader of SPIR-V's binary form over the grammar's instruction table, used only by tests
device/ DeviceDescription (from a Khronos profile, or from ash), DevicePolicy, and the derived DeviceProfile every decision reads
library/ Library, Function, CompiledFunction, FunctionCompileKey
reflection/ Metal-shaped reflection of functions and pipelines
pipeline/ Descriptors, compile entry points, link and relocate, PipelineInterface, the pipeline layout, vertex input and fixed-function state, runtime facts, precision notes
bind/ The binder: BindState and BindShape, BindingPlan, per-command instantiation, neutral resources, argument, handle and heap tables, residency, indirect-command replay, and the helper kernels the runtime records. It never calls Vulkan
cache/ PipelineKey, SEMANTICS_VERSION, the artifact encoding
metal/, vk/, ash_interop/ Metal's enums and format facts; plain-data Vulkan values; ash conversions (feature ash)
error/ The typed errors every entry point returns
main.rs The command line (feature cli)

The translator core (lower, memory, spirv, spv, structurize) and every submodule of a public module are crate-private; no feature or cfg exposes them. The runtime (crates/metal2vulkan-runtime), validation and devtools use the public API only. A test that needs an internal item is one of the crate's own tests (src/tests/).

Decisions come from structure and the device

  • The device profile. Device::new derives one DeviceProfile from the description and the policy. Every device-dependent choice (subgroup tier, buffer views, storage widths, robustness, push-constant room, limits, measured driver deviations) reads it, and its fingerprint is part of every cache key.
  • The policy's accuracy choices. The maths, the sampler and the texel conversions are the device's own on every device. Off Apple's GPUs the default policy also takes the device's own half rounding, NaNs and blends where they are faster (FAST-PATHS.md).
  • Structure, not names. Families decide from IR types, address spaces, the metadata ABI and the air.* and llvm.* intrinsic contract. No branch keys on a function, type or variable name.
  • Typed refusals. An input the device cannot run exactly is Error::Unsupported, naming the Metal feature and what would make it translatable. A missing pipeline input (a function-constant value, a stage-input or vertex descriptor, a storage texture's format) is Error::NeedsInput, asked for and never guessed. A deterministic cap is Error::LimitExceeded. Only a deadline (Error::Budget) or a cancellation (Error::Cancelled) is transient.
  • Recorded differences. Where the output gives a near-equivalent of Metal's answer, the stage records a PrecisionNote, and Reconvergence::ImplementationDefined where the profile lacks maximal reconvergence.

Validity by construction

  • The builder makes invalid modules hard to write. Typed constructors check operand and result types; storage-class rules hold by construction; if_, switch_ and loop_ are the only construct openers, each closed by its scope, so constructs nest correctly.
  • Types are interned with their layout, so a type is unique and its explicit layout is part of its key.
  • Capabilities and extensions are derived from what the module contains, never written by a lowering, and must lie within the profile (else Error::Internal, kind RequirementsExceedProfile).
  • The serializer writes the logical layout and numbers result ids densely in order, so equal modules give equal words. Nothing nondeterministic (such as hash-map order) reaches the output.
  • The verifier always runs, in release builds too, before any word leaves the crate: ownership, SSA dominance, structured control flow and canonical loops, convergent instructions, atomic pointers, an acyclic call graph, stage rules, the recorded interface and requirements, and the profile's rules. A violation is Error::Internal (kind Verify): a translator bug, never an input error.

Structurization

The structurizer reads the CFG through a view: blocks are opaque units and terminators are shapes.

  1. Prune unreachable blocks and fold trivial branches.
  2. Make an irreducible graph reducible with a multi-entry dispatch; refuse an irreducible region that holds a convergent instruction, and nesting or output past the structural limits.
  3. Find the loop nest.
  4. Demote every block-crossing value and phi to a Function variable.
  5. Canonicalize loops: back edges become continue, exits a break through one exit dispatch per loop.
  6. Place every acyclic region on the dominator tree, innermost loop first.
  7. Let tail jumps fall out and route the rest through one pending variable.
  8. Emit the tree through the builder, each block lowered by the plan's strategies.
  9. Promote single-store variables back to values where dominance allows.

The output size is checked against Limit::OutputBlocks before anything is emitted.

Bounded work

Every compile takes a Budget: a wall deadline, a CancelToken, a deterministic work-unit cap and a byte ledger. The Meter is threaded through every loop that scales with the input: it ticks work units and charges each input-sized container before reserving it, so a refusal comes before the allocation and the same input refuses the same way on every host. The crate keeps no global cache and memoizes nothing; the caller caches compiled functions, pipelines and plans under the public keys. A consumer that needs a hard memory ceiling or crash isolation compiles in a child process (HOWTO.md).

Checks

Match the evidence to the claim; VALIDATION.md has the full ladder.

Check Catches
clippy with warnings denied warnings and common defects
unit and integration tests construction and lowering regressions
the always-on verifier, and spirv-val in tests and the command line invalid modules
interpreter tests (spirv::interp) wrong compute lowering, out-of-bounds access, non-termination
the fixture inventory (tests/public_fixture_expectations_engine.tsv) a fixture that stops compiling or starts refusing on a committed profile
golden output hashes (src/tests/golden_hashes.rs) unintended output changes
authored cases run on Metal and Vulkan answers that differ from Metal's
bounded release-mode corpus translation time, memory and coverage over real AIR

A valid module is necessary, not sufficient. A change that only silences the verifier or spirv-val is unsound; unknown semantics stay refusals.