Files
metal2vulkan/docs/ARCHITECTURE.md
T
Anees Iqbal 57855c6097 Link: the synthesized geometry stage goes, both forms (the barycentric weights and the rate map's fan-out)
The translator built geometry stages in two forms that no Metal function asks for:
- the barycentric weights: a fragment function's [[barycentric_coord]] read as varyings, which a
  generated geometry stage of each topology class wrote, on a device without
  fragmentShaderBarycentric;
- the rate map's fan-out: a draw of a rasterization-rate-mapped pass's triangles once, a geometry
  stage emitting a copy of each per region, with its probe and its region-copy vertex variant.

Neither form reached a guest. The runtime enables no geometryShader, so it refused the weights
form already. It never sets BindShape::region_fan_out, and draws a rate-mapped pass region by
region (the regions route, RateMapRegions, and region_viewports, which stay). Validation never set
region_fan_out either.

After this change, one form is left for each:
- A fragment function that reads [[barycentric_coord]] reads the device's own
  BaryCoordKHR/BaryCoordNoPerspKHR. Without fragmentShaderBarycentric it is refused as
  Unsupported(Barycentrics) needing that feature alone; geometryShader is no longer offered.
- A rate-mapped pass draws through the regions route.

Rule 1: no precision note stops being raised. The fan-out's copies were a near-equivalent of the
regions route, which carries its own note (RateMapRegions::precision), and the weights form
raised none. The catalogue is unchanged.

Removed:
- pipeline::link::geometry (GeometryStages, the three classes' stages) and pipeline::link::fan_out,
  with their tests (link/tests/geometry.rs, link/tests/fan_out.rs) and tests/engine_region_fan_out;
- bind::fan_out (the region table, the probe's word layout and its constants);
- RegionFanOut and FanOutState;
- the region_fan_out fields of GraphicsState, BindState, BindShape, VariantKey and
  RenderLinkInputs, and LoweringInputs::region_copies;
- the region copy's lowering: StageIoPlan::region_copy, RegionCopy and the region table's
  declaration;
- PushField::RegionBox and RegionProbe;
- SyntheticBinding::RateMapRegions and RateMapFlags, and WriteSource::RateMapRegions and
  RateMapFlags;
- RuntimeFact::SynthesizedGeometry, RenderPipeline::runs_stage and Linked::geometry;
- IoRole::Barycentric with VaryingKey::barycentric and its key tag;
- VkProperty::SubgroupGeometryStage;
- the SPIR-V IR's geometry execution model, which only these stages produced: ExecModel::Geometry,
  OpEmitVertex and OpEndPrimitive, the InputPoints, InputLines, OutputLineStrip,
  OutputTriangleStrip and Invocations modes, ModelNeed::Geometry, EntryRule::GeometryModes and the
  builder's geometry ops;
- from scripts/regen-spirv-grammar/items.txt, the opcodes EmitVertex and EndPrimitive, the
  execution model Geometry and those five execution modes. spv.rs is regenerated: the opcodes and
  the model stay as test-only values, which the test parser reads, and the modes go;
- in validation, the census's geometry stage filter, the draw's runs_stage filter and the
  candidate's GEOMETRY stage arm. The census test that read three geometry stages from
  engine/bary_weights goes with them.

The SPIR-V builder now marks only Position Invariant; ClipDistance was the fan-out's.
band::plan loses its geometry flag, and takes the four SPIR-V helpers it shared with the
geometry module. The binder's stage map takes a geometry stage as no render stage.

Validation cases that executed either form: none.
- Fan-out: no validation code sets region_fan_out.
- Weights: two authored cases read [[barycentric_coord]], fa8b920d3cf3 and ae0a7e39b12f. Neither
  has a stored Vulkan observation on a profile without fragmentShaderBarycentric. fa8b920d3cf3 is
  observed on Metal and MoltenVK, and moltenvk-m3 has the feature. ae0a7e39b12f is observed on
  Metal only.

Fourth user of GeometryStages: none. It was used by link, the compile API's splice, the binder's
selection (through RuntimeFact::SynthesizedGeometry and GraphicsState::region_fan_out) and its
own tests.

Tests:
- engine_stage_io_tail's weights test is now without_the_feature_the_weights_are_refused: on
  lavapipe, ANV's Iris Xe, NVIDIA's Pascal (each with geometryShader) and runtime-floor (without
  it), both barycentric entries are refused needing fragmentShaderBarycentric.
- engine_target_indices checks each pipeline's stages valid where it counted geometry stages, and
  loses the_weights_stage_beside_a_vertex_layer_is_not_implemented: that combination is now the
  plain refusal above.
- engine_amplification no longer counts geometry stages.
- The binder's render stage test refuses a geometry stage.
- The builder's invariant test refuses ClipDistance.
- engine_rotated_weights' rotated draw runs on moltenvk-m3 and RDNA3's RADV, each with
  fragmentShaderBarycentric, where it ran on lavapipe through the weights form.
- The fact mechanism test numbers its 100 RuntimeFact variants densely again (PrivateArena,
  which development added, takes 99).

Bless due until the next named pin, where the M3 bless job takes them; nothing is blessed here:
- tests::public_fixtures_engine (the inventory): every [[barycentric_coord]] cell on a profile
  without fragmentShaderBarycentric becomes Unsupported(Barycentrics) needing it alone, where it
  compiled through the geometry stages (with geometryShader) or offered GeometryShader as the
  alternative;
- tests::golden_hashes, and pipeline::compile::tests::the_old_render_descriptor_key_keeps_its_value
  (the render key), as under the commit below: the profiles' fingerprints change;
- the authored compile census.

SEMANTICS_VERSION 2247 -> 2248 and ARTIFACT_FORMAT_VERSION 583 -> 584 are placeholders that main
renumbers.
SEMANTICS: a fragment function's weights and every rate-mapped variant change form. ARTIFACT: the
codec loses the RegionFanOut, FanOutState, GraphicsState::region_fan_out, IoRole::Barycentric,
RuntimeFact::SynthesizedGeometry, PushField, SyntheticBinding and VkProperty tags. RUNTIME_VERSION
stays: the runtime's render-pipeline kind no longer reads region_fan_out, which it never set, and
its SynthesizedStages doc names the bands alone. runtime-sources.sha256 keeps development's (land-pkt
re-pins it), api_signatures and api_surface drop the removed items, and docs/REFUSALS.md is regenerated.
API.md drops the geometry stages from RenderPipeline's stages, its barycentric bullet and its band
bullet. ARCHITECTURE.md's link line drops pipeline::link::geometry, and the runtime README's
Barycentrics gap names the feature alone.

Consumer check (consumer_check.sh, consumer development b76d6ac4a9): region_fan_out,
RegionFanOut, FanOutState, region_copies, region_copy, RateMapFlags, RegionBox, RegionProbe,
SynthesizedGeometry, FEW_COPIES, PROBE_DRAW_WORDS, RegionCopies and runs_stage have 0 hits.
GeometryStages appears in crates/reims-vgpu-c/link-order.txt only. fan_out's hits are the
consumer's own event fan-out in crates/reims-vgpu/src/graphics/decode/cmdbuf.rs, not this
module.

Verified (jobs read):
- m3-max-61801: the suites at this change's work in progress (4f1f934423); its real reds were the
  mechanism numbering and the rotated weights on amd-rdna3-radv, both fixed here; the render key
  reads bless-due.
- At the stack's tip over this change (dvl-5 1fa4aed963 and dvl-6 92fe40c38f): 61978 and 61987,
  fmt, clippy in every configuration, Rustdoc, each feature alone, the API docs and the Windows
  clippy, green; 61891, the suites at dvl-4: 13 failures, each a bless-due golden above or
  development's own (the raster state test, the inventory's sample_fill rows); 61968, the lavapipe
  device suite of metal2vulkan-validation, 1483 of 1483, and public case qualification Match;
  62042, the metal2vulkan-validation suite at dvl-5, 1378 of 1378 passed.
- States-only play of this change's player (p-gd.zst) over 35 distinct streams on gem10 (61919),
  um870 (61924), ms01 (61967) and um790 (62004): 456,384 render and 91,972 compute states made,
  0 refused, every stream exit 0. The msi stream (windrag-780m-b2) is not played: msi had no
  memory free.

Rebased onto development 4cf936ed4d (selidx landed as 3ecf606aa8). The conflicts: the version
lines; the mechanism test, where development added RuntimeFact::PrivateArena; runtime-sources.sha256,
where development's is kept; and api_signatures.tsv and docs/REFUSALS.md, both regenerated
(signatures.py --bless, refusal_surface.py) and differing from development by this change's items
alone. The jobs above ran at the old base; the rebased tip's are in the report to main.
2026-11-21 00:03:34 -08:00

181 lines
16 KiB
Markdown

# 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](API.md).
## The pipeline
```text
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, loops of constant trip
count unrolled where that decides a branch and
leaves the entry no larger, private arrays
allocated as far as bounded indices reach,
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,
half values held at 16 bits under the 16-bit float hoist, half_hold}
controls, repeated regions of large entries rolled
into loops, loop-invariant loads of uniform views
moved before their 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::band
tessellation stages that draw a wide line as a
band
── 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 (each `byval` argument's copy made at its call first), function constants, SCCP (a value one of a few constants, from a PHI of literal constants or a `select` between two, folded member by member so a branch every member decides alike is decided; reading the integer fields of a constant global whose value is known, folding the integer bit operations `llvm.ctpop`, `llvm.bitreverse` and `llvm.bswap` and the scalar `llvm.umin`, `llvm.umax`, `llvm.smin` and `llvm.smax` on constants, settling the float operations a constant operand decides whatever the others hold (a NaN operand, the first in order: as it is beside a value the run computes, quieted where every operand is a constant; a product by a zero under `nnan` and `nsz`, `+0`), and reading the immediates of an intrinsic call that its function's parameters gave it once inlining makes them its call site's constants), the unrolling of loops whose constant trip count decides a branch where that leaves the entry no larger, the allocation of a private array of nested arrays as far as its indices reach where constants and counted loops bound every one of them (`canon::reach`), a pointer loaded from a constant table at an index only the run knows (a table of constexpr samplers) read as the `select` chain over the table's elements (`canon::const_tables`), each of MSL 4.1's generic pointers made a pointer of the one address space every pointer it may hold comes from, its space queries answered (`canon::generic`), devirtualization, linking, the load of a stack allocation's field that one dominating store wrote read as the stored value (an aggregate holding a pointer excepted), and an allocation no read is left of removed with its stores, so a lambda's closure of captured addresses leaves the captured objects' own (`canon::forward`), pruning, pointee erasure, the speculation of the short branch arms Metal's backend runs in every lane, the split of a whole array's or struct's load or store in buffer or threadgroup memory into its members' accesses, and a kernel of a pipeline of OpenCL mode linked as Metal links it: the three hidden buffers appended, its buffer indices 3 on, OpenCL C's work-item reads made reads of their built-ins or of the first buffer, each image format query a read of the third, and each operation of a 1D image the 2D texture's that Apple's OpenCL binds for it, `canon::opencl` and `canon::opencl_1d`; and OpenCL C's vector data loads and stores made their element accesses, `canon::vector_data`). 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; `memory::views`, a descriptor slot's views: a storage block or a uniform block |
| `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` (each float operation in the AIR's order, decorated by its own fast-math flags, so the device's compiler groups and fuses only what they allow; `half_chain`, a fast-math `half` chain held at `float` precision between its roundings where the device has no 16-bit floats), `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 move of loop-invariant loads of uniform views out of their loops (`hoist`), the 16-bit holding of `half` values under the 16-bit float controls (`half_hold`), 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`), conformance, 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::from_queries` derives one `DeviceProfile` from the description's
Vulkan queries and the policy, reading no vendor, device or driver identity. Every
device-dependent choice (subgroup tier, buffer views, storage widths, robustness, push-constant
room, limits) reads it, and its fingerprint is part of every cache key.
- **The device's native forms.** The maths, the grouping and fusion of fast-math arithmetic, NaN
bits, minimum and maximum, `half` rounding and blends, the sampler and the texel and color
conversions are the device's own on every device,
each difference from Metal recorded as a precision note; on MoltenVK on Apple's GPUs most are
Metal's own.
- **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 stage-input or
vertex descriptor, a storage texture's format, a linked function) is `Error::NeedsInput`, asked
for and never guessed; a function constant left undefined is no such input, as in Metal
([API.md](API.md), "Accepted differences"). 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](HOWTO.md#5-bound-a-compile)).
## Checks
Match the evidence to the claim; [VALIDATION.md](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.