Commit Graph
17 Commits
Author SHA1 Message Date
Anees Iqbal 9d629a3e9f Reflect the image the module binds, not the one the type name implies
`ShaderReflection::texture_shape` is what a consumer feeds into
`VkImageViewCreateInfo`, and Vulkan requires the created view's type to match the
`Dim` and `Arrayed` of the image variable the descriptor is read through. The
shape was decoded from the AIR type name, and the emitter does not always bind the
image that name implies: SPIR-V has no cube texel fetch, so `resources::discovery`
binds a `texturecube` that is only ever texel-read as a `Dim2D` ARRAY image with
the face in the layer slot. Reflection kept saying `Cube`, so a consumer following
it created a `VK_IMAGE_VIEW_TYPE_CUBE` view for a 2D-array image variable and the
dispatch was invalid.

`reconcile_texture_shapes` corrects each shape from the module's own `OpTypeImage`
at that binding, the same way `reconcile_buffer_address_table` and
`report_synthesized_placeholders` read their facts off the finished module.
`array_ref` and `array_length` describe the descriptor array rather than the
image, so they stay with the metadata that decides the descriptor count.

A binding is only corrected when its image variables all declare the SAME image
type. A function-constant-gated `air.location_index` puts several
differently-shaped variables on one binding -- 67 corpus modules do -- and there
the module has no single answer to read: the consumer picks one by choosing its
function constants. `reflect_sanitized` builds no module and keeps the
type-name-derived shape; its doc comment already listed what it approximates.

`TextureFormat::from_spirv_format` inverts the existing `to_spirv_format` over a
new `TextureFormat::ALL`, with a round-trip test that also proves the mapping is
injective -- otherwise the inverse would not be single-valued.

Measured over 2880 corpus sources by comparing every reflected shape against the
`OpTypeImage` behind its binding: 2 modules disagreed, both cube textures
reflected as `Cube` while the module declares 2D arrayed; 0 after. SPIR-V bytes
identical and the failure count unchanged at 204; exactly those 2 modules' -- and,
from the version bump, every module's -- reflection changed.

New `tests/reflection_describes_the_image_it_binds.rs`. The cube fixture binds one
AIR type name, `texturecube<float, ...>`, as two different emitted images: the
texel-read source as a 2D array, the written destination as a cube. Verified as a
detector -- with the reconcile removed it fails. A second authored kernel covers
four shapes across dimensionality, component class, and storage format, and
asserts they stay four distinct shapes so a decoder that widened them all could
not pass by moving both sides together. Only one public fixture binds a texture,
which is why the grammar probe carries the coverage; the fixture sweep is there
for when that changes.

`REFLECTION_VERSION` 33 -> 34: a cached v33 shape can name a view type the module
rejects. `docs/REFLECTION.md` follows.

Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test
-p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation.
2026-08-31 23:54:56 +03:00
Anees Iqbal e195fce0be Report the descriptors only the translator knows about
Two passes bind a real resource with no Metal argument behind it, so an AIR value
has a legal SPIR-V type: `air.get_null_texture_*()` gets an `OpTypeImage`,
`air.get_read_sampler()` gets an `OpTypeSampler`. The parent commit retracts those
whose value nothing consumes. One that IS consumed stays -- and nothing in the AIR
metadata describes it, so a consumer building its `VkDescriptorSetLayout` from
`ShaderReflection` produced a layout the module reads outside of.

This was the last of the module-vs-reflection descriptor mismatches. Over 2880
corpus sources the count is now 0, down from 267 when the oracle was first run.

`ResourceKind::SynthesizedNullTexture` and `ResourceKind::SynthesizedReadSampler`
report them. Which placeholders survive is a fact only the passes hold, so
`transform` now returns it -- `Transformed` replaces the `(Module, EmitSidecar)`
tuple -- and `finish_module` narrows the list to what the finished module still
declares, since the steps after `transform` delete instructions and the liveness
pass there can take a variable with them. Reflection reads each placeholder's
class from the module's own `OpTypeImage`/`OpTypeSampler`, and a null texture's
`texture_shape` off that image's operands, so nothing is inferred from binding
numbers. That mirrors `reconcile_buffer_address_table`, which closed the same kind
of gap for the address table.

`validate_descriptor_abi` constrains a placeholder to its ABI band rather than to
a recomputed `base + index`: it takes the first binding in the band no Metal
argument claims, so there is no index to recompute from.

Validation: `unsupported_reflection_requirements` marks a reflection carrying a
placeholder with the new `ToolingRequirement::SynthesizedPlaceholderDescriptor`.
The Vulkan executor has no authored resource to write at a descriptor no Metal
argument produces, and the Metal oracle has nothing to encode, so the row is
honestly not executable until the harness can supply a deterministic placeholder
resource. It is not claimed as supported without execution evidence. Before this,
such a row built a layout that omitted a binding the shader reads, so it was
already failing rather than silently passing. The exhaustive `ResourceKind` match
in `executor_contract.rs` is what forced the decision; that is what it is for.

`reflect_sanitized` builds no module and therefore reports neither placeholder;
its doc comment now says so alongside the address-table approximation it already
documented.

`REFLECTION_VERSION` 32 -> 33: a cached v32 reflection is missing a binding its
module declares. `docs/REFLECTION.md` gains both kinds in its binding-map and
descriptor-type tables.

Verified over 2880 corpus sources: SPIR-V bytes identical, failure count unchanged
at 204, and -- measured before the version bump, which changes every reflection
hash -- exactly one module's reflection changed, the one the mismatch scan named.

New authored fixture in `tests/reflection_covers_declared_bindings.rs`: a kernel
that queries the placeholder's width, the counterpart to the unconsumed probe
beside it. Verified as a detector: passing an empty placeholder list to
`report_synthesized_placeholders` fails exactly that test.

Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test
-p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation.
2026-08-31 23:34:36 +03:00
Anees Iqbal eaaf85abb0 Retract every descriptor the translator invented and nothing read
Two passes synthesize a resource with no Metal argument behind it, purely so an
AIR value has a legal SPIR-V type. `air.get_read_sampler()` gets an `OpTypeSampler`
because AIR threads a sampler pointer into the sampler-less `texture.read(coord)`;
`air.get_null_texture_*()` gets an `OpTypeImage` because a function-constant-gated
optional attachment still has to yield a handle. Either value can end up consumed
by nothing -- a phi that folds away, an `air.is_null_texture` that becomes a
constant -- and the descriptor then demands a resource the shader never reads,
which reflection cannot report because no Metal argument corresponds to it.

`cae8971` retracted the sampler. The rule was written over one named variable, so
the identical null-texture case kept shipping. It is now stated once, over
`Ctx::placeholder_descriptor_vars`: a third synthesized placeholder is covered by
registering it rather than by copying the pass.

The four sites that create a synthesized descriptor -- read sampler, null image,
implicit imageblock plane, custom fragment imageblock plane -- had four copies of
the same create-variable / decorate / add-to-interface block. They now share
`Ctx::descriptor_variable`, and the two placeholder callers go through
`Ctx::placeholder_descriptor`, which is what registers them for retraction.
Choosing the binding stays with each caller, since the ABI band is what actually
differs between them.

Measured over 2880 corpus sources: module-declared bindings reflection omits went
4 -> 1, and exactly 3 modules changed bytes -- each dropping one OpTypeImage, one
OpTypePointer, one OpVariable, its two descriptor decorations, and the unconsumed
OpLoad. spirv-val passes on all three. The remaining 1 is a placeholder image the
module genuinely reads, which needs reporting rather than retracting.

New authored fixture in `tests/reflection_covers_declared_bindings.rs`: a kernel
that asks `air.is_null_texture` about a placeholder and does nothing else with it.
Verified as a detector -- it fails at the parent commit, where the module declares
a texture binding reflection does not report.

`native_get_null_texture_models_unmodeled_placeholder` asserted that binding
exists. Its shader only stored the handle into an alloca nothing reads, which is
now the retraction case, so it moves to a kernel that queries the placeholder's
width -- a placeholder something DOES read keeps its descriptor -- and its
band claim is now checked against every Binding decoration rather than a substring.

Reflection output is byte-identical on all 2880 sources, so no REFLECTION_VERSION
bump: this removes a binding reflection never reported.

Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test
-p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation.
2026-08-31 23:18:07 +03:00
Anees Iqbal 42a7998514 Name each reflected resource once
`ShaderReflection::bindings` is a work list: a consumer walks it and acts once per
entry, allocating a descriptor, writing it, and sizing per-resource budgets from
the length. `from_fragment` called `append_embedded_resources` twice with the same
arguments, so every fragment entry with an `air.indirect_buffer` argument listed
each of its argument-buffer residents twice and asked for that work twice.

Nothing in the emitted module records the repeat -- the decorations it duplicates
are already there once -- so `reflection_covers_declared_bindings.rs`, which asks
whether reflection covers what the module declares, cannot see it. Measured over
2880 corpus sources: 405 fully-identical duplicate entries across 19 modules, all
fragment `EmbeddedArgBufferTexture` and `EmbeddedArgBufferBuffer`. After: 0.

To keep the class from returning silently, `validate_descriptor_abi` -- which both
`reflect_sanitized` and the reflected translation path run -- now rejects two
entries that agree in every field. Equality is the right test rather than the
`(set, binding)` pair, which raw-word alias buffers legitimately share and which
this check deliberately still allows; genuinely distinct resources always differ
somewhere, in the Metal index, the entry-parameter index, or an argument-buffer
resident's field offset.

New `tests/reflection_describes_each_resource_once.rs` with an authored fragment
fixture: one `air.indirect_buffer` holding a writable texture and a nested device
buffer. Verified as a detector -- with the second append restored the fixture test
and the gate test both fail. It also sweeps every public fixture and pins the gate
itself, so deleting the check cannot make the other two pass by not looking.

`REFLECTION_VERSION` 31 -> 32: a cached v31 reflection for such a fragment carries
entries a consumer would act on twice. `docs/REFLECTION.md` follows.

Verified: 2880 corpus sources, SPIR-V bytes identical and the failure count
unchanged at 204; 19 modules differ in reflection only, the same 19 the duplicate
scan named.

Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test
-p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation.
2026-08-31 23:09:09 +03:00
Anees Iqbal ca14b5b544 Report an imageblock plane wherever the module asks for one
The interface pass materializes a descriptor-backed render-target plane wherever
it lowers an `air.load/store.implicit_imageblock.*` call, and the detector that
finds those calls scans the module body -- it never looks at the stage. Reflection
did look at the stage: `KernMeta` carried the detected attachments and `from_kernel`
reported them, while `from_fragment` and `from_vertex` hardcoded an empty list.

A fragment entry that reads its render target back through the implicit imageblock
therefore emitted `OpDecorate %n Binding 200` and reflected nothing, so a consumer
building its `VkDescriptorSetLayout` from `ShaderReflection` produced a layout that
did not cover the shader. Verified on the authored fixture: before this change the
module declared Binding 200 with `implicit_imageblock_attachments: []`; now it
reports the plane at that binding.

`FragMeta` and `VertMeta` now carry the field, filled by the same stage-agnostic
detector, and one `implicit_imageblock_planes` helper does the meta-to-reflection
mapping for all three constructors instead of the one copy `from_kernel` had.

Scope of the evidence: all five corpus users of those intrinsics are kernels, so
this is not a claim about how common fragment imageblock read-back is in real AIR.
It is the module and its description disagreeing, which is a defect whether or not
a shipped shader has hit it.

`REFLECTION_VERSION` 30 -> 31, since a cached reflection from v30 is missing a
binding its module declares. `docs/REFLECTION.md` said 29 and now says 31.

Verified: 2880 corpus sources byte-identical (this changes reflection, not
emission).

The sweep in `tests/reflection_covers_declared_bindings.rs` stays at each fixture's
declared stage. Translating a module at a stage its AIR does not declare leaves the
stage parse with no source at all, so the reflection is a stub regardless of what
the module contains; that is a different question from this one.

Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test
-p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation.
2026-08-31 22:46:04 +03:00
Anees Iqbal cae8971fb7 Do not bind a sampler for a read that never samples
Metal's `texture.read(coord)` takes no sampler. AIR threads one in anyway, from
`air.get_read_sampler()`, and `lower_read` discards it -- so `default_read_sampler`
materialized a real `OpTypeSampler` UniformConstant variable, decorated it with a
DescriptorSet and Binding, and put it on the entry-point interface purely to give
that discarded value a type.

The result was a descriptor the shader never samples with, and one no consumer
could learn about: no Metal argument corresponds to it, so `ShaderReflection` has
nothing to report, while the module demands the binding regardless. A consumer
building a `VkDescriptorSetLayout` from the reflection produces a layout that does
not cover its own shader.

Measured over 2880 corpus sources: 267 bindings the module declared and reflection
omitted; 250 of them were this sampler, and in every single case the load of it had
no consumer at all -- 0 of 250. (The other 17 are two smaller classes, unchanged
here and stated below.)

The fix retracts the synthesis rather than papering over it in reflection: after
lowering, drop the loads of the default sampler that feed nothing, and the sweep
added in 7aac6cd removes the now-unreferenced variable, its decorations, and its
interface entry. This is not general dead-code elimination, which this pipeline
deliberately does not do -- it withdraws one descriptor the translator itself
synthesized, only where the synthesis turned out to be unnecessary. A load whose
result IS consumed keeps the sampler.

Verified over 2880 corpus sources, release build, rebuilt for the run:

  - reflection-omitted bindings: 267 -> 17
  - 251 sources differ: 250 with output changes, plus one whose FALLBACK
    diagnostic names %383 instead of %384 because one fewer id is allocated. Same
    failure, same class. The remaining 2629 are byte-identical.
  - removed across those 250: 250 OpVariable, 500 OpDecorate, 297 OpLoad, 180
    OpTypeSampler, 180 OpTypePointer; 22,072 bytes. Nothing else changed.
  - spirv-val --target-env vulkan1.2: 2676 VALID / 204 FALLBACK, unchanged

`tests/reflection_covers_declared_bindings.rs` states the contract: every
`(set, binding)` a module decorates on a variable must appear in reflection, from
any of the three places reflection carries one -- `bindings`,
`implicit_imageblock_attachments`, and `fragment_imageblock.members`. The reverse
is allowed and deliberate: Metal may declare a resource the shader never touches,
and dropping it would renumber a consumer's expectations.

The authored fixture is a `texture.read` kernel and it is not vacuous: before this
change it emitted `OpDecorate %28 Binding 160` and an `OpTypeSampler`, and now it
emits neither. The fixture sweep runs at each fixture's declared stage.

Residue, stated rather than hidden. 17 declared-but-unreflected bindings remain on
the corpus: 13 StorageBuffer blocks in the band above 608 and 4 synthesized
textures. Separately, `from_fragment` and `from_vertex` hardcode an empty
`implicit_imageblock_attachments` while the detector that fills `from_kernel`'s is
stage-agnostic and the passes emit the plane regardless of stage -- so translating
`kernel_implicit_imageblock_half2.ll` as fragment declares Binding 200 and reflects
nothing. All five corpus users of those intrinsics are kernels, so nothing here is
evidence about real fragment AIR; it is a reporting gap, and the reason this file's
sweep does not vary the stage.

Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test
-p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation.
2026-08-31 22:36:48 +03:00
Anees Iqbal 7aac6cdb3a Stop shipping descriptor bindings no instruction reads
A translated module could declare a module-scope OpVariable that no
instruction anywhere references, list it in the entry point's interface, and
decorate it with a DescriptorSet and Binding. A consumer that builds a
VkDescriptorSetLayout from the interface -- the normal way to do it -- then has
to bind a descriptor the shader never touches.

Measured on the private corpus: 58 of 2880 sources, 1105 stranded variables
(1053 Private, 40 StorageBuffer, 12 UniformConstant). spirv-val accepts every
one of them, which is why nothing noticed.

The cause is a liveness snapshot that outlives the bodies it described.
`finalize` filters the entry-point interface to the variables the function
bodies reference, which is right -- and `function_referenced_ids` already says
so: "Entry-point interface variables should be live because code loads/stores/
access-chains them, not because an earlier pass registered them before a later
raw-alias rewrite replaced every use." But instruction-deleting work runs after
it at two boundaries: the pointer and access-chain closures at the tail of
`transform`, and dead-value elimination, constant-CFG pruning, and CFG
construction in `finish_module`. Once one of those deletes a variable's last
use, the arrangement is self-sustaining and nothing downstream can undo it:
`gc_dead_globals` roots liveness AT the entry-point interface, so the interface
entry keeps the variable alive and the variable justifies the interface entry.

`module_cleanup::drop_unreferenced_global_variables` breaks that cycle. It is
the rule stated once -- a global variable lives because an instruction names it
-- applied to the interface, the variable, its decorations, and its debug names
as one transaction, and it runs at each boundary after the last instruction
change there. It can only shrink the interface (an id it keeps is one an
instruction still names), so SPIR-V 1.4's requirement that the interface list
every global the entry point references is preserved. At the `finish_module`
boundary it is placed ahead of the existing null/undef constant sweep so the
initializers it strands are collected in the same step.

Verified over 2880 corpus sources, release build, rebuilt for the run:

  - stranded module-scope variables: 58 modules -> 0 modules
  - 58 modules differ, every one still OK; the other 2822 are byte-identical,
    including all 204 unchanged FALLBACK messages
  - removed across those 58: 1105 OpVariable, 1050 OpConstantNull, 104
    OpDecorate, 2 OpName; 40,636 bytes. Nothing else changed.
  - spirv-val --target-env vulkan1.2: 2676 VALID / 204 FALLBACK, unchanged
  - corpus total 100.1s -> 100.7s, slowest source 2.54s -> 2.57s

Known residue, stated rather than hidden: removing the variables leaves 47
OpTypePointer and 2 OpConstantComposite declarations unreferenced across 29
modules. Those are inert declarations with no interface entry and no binding;
collecting the general type graph at that boundary is `gc_dead_globals`' job
and it does not run there.

Tests. The unit tests in `module_cleanup` are the pin: a module with two
descriptors in its interface and a load of only one must come out with the
stranded variable gone from the interface, the globals, its decoration, and its
name, with the live one untouched -- and the sweep must reach a fixed point in
one pass, since the pipeline runs it at more than one boundary.
`tests/live_module_scope_variables.rs` is the end-to-end net: no fixture, under
any stage it translates under, may produce a module declaring a global variable
no instruction references. That sweep is honest but currently vacuous on the
committed fixtures -- it still passes with both call sites removed. The trigger
needs a use deleted by SPIR-V-level constant folding, and llvm-reduce converged
only on inputs (a load through a null constant pointer) too artificial to
commit as an owned fixture. The corpus numbers above are the evidence that the
defect was real; the guard is what keeps a future fixture from reintroducing it
silently.

`fc_specialize::drop_unreferenced_entry_interface_globals` is a third statement
of the same rule, narrowed to variables that were already in the interface.
Consolidating it is a separate change; it is a public API's behavior.

Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test
-p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation.
2026-08-31 22:09:01 +03:00
Anees Iqbal 0546ccec98 Make the rule that names must not decide a translation a test
AGENTS.md's first ground rule is that emit and lowering decisions come from
IR structure, never from a hardcoded function, type, or variable identifier,
and that a name-keyed branch is a defect even when it happens to work. Nothing
checked it. That is the worst shape for a rule: the shader that was tested keeps
translating, so the branch is invisible until a consumer ships an identically
shaped shader spelled differently.

The check is metamorphic. Rewrite every identifier the AIR/LLVM contract does
not own -- global symbols, named struct/class/union types, named local values,
and the bare block labels that define them -- to a generated placeholder, and
translate again. Structure and semantics are untouched, so the two runs must
produce the same module. Only the SPIR-V debug-name section, which exists to
carry those identifiers, may differ; it is dropped before the comparison and
nothing else is.

The contract families that may NOT be perturbed are listed with the code that
reads each: air.*, llvm.*, __air_sampler_state, mtl.*, _GLOBAL__sub_I*, and any
symbol carrying MTL_ (function constants, visible-function references). That
list is the first written-down statement of which names are ABI here.

Committed AIR names the entry after the Metal function and leaves everything
else numbered, so sweeping the public fixtures perturbs one or two names each.
Three inputs are authored for the test instead:

  - a kernel whose entry, helpers, parameters, and locals are all spelled as
    near-misses of contract names (air_get_width_texture_2d, llvm_fabs_f32,
    %texture_buffer, %_cube_array). The helpers are called, so a loosened
    residual-intrinsic test leaves their calls unlowered.
  - a texture-handle array whose LLVM struct type claims
    metal::texture_buffer<float, access::write> while the AIR metadata declares
    array<texture2d<float, sample>, 2>. The metadata is the ABI: the emitted
    image must be 2D. texture_buffer is the first substring the texture shape
    decoder tests for.
  - a kernel whose Metal entry is already named main, the one case where an
    incoming name collides with an emitted one.

Verified: the suite is a detector, not decoration -- loosening
is_residual_intrinsic from starts_with("air.") to starts_with("air") in
native::ir::ordinary_inline fails the look-alike kernel, and the label-renaming
path was itself found by the fixture sweep rejecting a module whose %body uses
were renamed but whose body: definition was not.

Separately measured, not asserted here: over 2880 private corpus sources this
rewrite leaves every translation byte-identical once debug names are dropped,
and each of air., llvm., __air, and _GLOBAL__sub_I is load-bearing (dropping
one from the contract list changes 136-417 of 500 sampled modules).

Test-only; no product path changed. Gate: fmt, clippy -D warnings, warnings-
denied all-features rustdoc, cargo test -p metal2vulkan (debug and release),
cargo test -p metal2vulkan-validation.
2026-08-31 21:44:28 +03:00
Anees Iqbal 8506f33a6d Pin the byte-view vector store, the one remaining rejection class that is a gap
Eight of the twelve non-function-pointer corpus rejections are one shape, and until now nobody could
author it. Three previous attempts produced modules that translate cleanly, because they reduced
from the diagnostic's text — which named the address arithmetic, not the shape. `llvm-reduce` got it
in three passes: 708 lines to 44, then renamed so it carries no third-party identifiers.

The shape is a `<3 x float>` store through a `device uchar*` view of a `{ RuntimeArray<uint> }`
block, reached across a call. Every surviving part is load-bearing, each checked by deleting it:

- the `i32` load and the byte `getelementptr` in the kernel, which between them fix the block's
  element width at 32 bits and open the byte view — dropping either translates;
- the pointer crossing a call boundary through an `alloca`d struct — inlining the callee translates,
  which is why every single-function reduction before this one missed;
- the callee's pass-through blocks and the full argument list, both of which change which
  construction attempt the module reaches.

It is pinned as a must-FALLBACK because it is the class most likely to be closed wrongly, and the
test says so. Both tempting lowerings are unsound: a non-atomic read-modify-write of the surrounding
words races another thread writing the neighbouring bytes — which is exactly what
`emit_scalar_narrowing_store` restricts to thread-local slots and what
`emit_raw_byte_store_from_u32` uses atomics for on shared storage — and a plain word store is
byte-exact only under four-byte alignment, which the AIR asserts with `align` but which does not
reach the SPIR-V pass that would need it. So the suite's header now separates this gap from the
function-pointer limits around it: closing it has to be a deliberate edit to this test.

`cargo fmt --all --check`, clippy `-D warnings`, `RUSTDOCFLAGS='-D warnings' cargo doc`,
`cargo test -p metal2vulkan` debug and release, `cargo test -p metal2vulkan-validation`.
2026-08-31 21:01:13 +03:00
Anees Iqbal 1b119af370 Pin the two unsupported classes that actually turn up
`tests/must_fallback.rs` exists so a refactor cannot quietly turn a clean FALLBACK into SPIR-V that
"succeeds" with garbage, and it covered the classes that were easy to name: raytracing intrinsics,
emask intrinsics, texture atomics, malformed modules. It did not cover either of the two classes
that account for almost every real rejection.

Measured over the 2880-source local corpus sample: 204 sources do not translate, and 191 are one of
two shapes -- a call through a Metal visible function table (136) and an intersection whose custom
intersection functions come from a function buffer (about 55). Both are function pointers, which
Logical SPIR-V does not have, so neither is a lowering waiting to be written; the only way they can
change is by becoming wrong. Each is now an authored kernel in the negative suite, and each was
checked to produce the same diagnostic the corpus sources produce, through the public
`translate_sanitized_native` path rather than a component entry point:

    unsupported indirect call through function pointer %fp (Metal visible function table)
    unhandled air.* intrinsic: air.intersect.intersection_function_buffer.triangle_data

Both inputs are authored, not extracted: the `HEAD`/`TAIL` template already in that file with one
construct injected, so the rejection is attributable to the construct and to nothing else --
`base_kernel_translates` is the anchor for that. `kernel_with_declarations` is the only new
scaffolding, for the two cases whose callee needs declaring.

The `intersection_function_buffer` tag suffix is a combinatorial family -- the corpus alone has
`instancing`, `triangle_data`, `world_space_data`, `user_data`, `primitive_motion`,
`instance_motion` and `multi_level_instancing` in about twenty combinations. The rejection is on the
`intersection_function_buffer` stem rather than on any one combination, so one of them stands for
all of them and the test says so.

Tests only; no product code changed. Full gate green.
2026-08-31 19:33:18 +03:00
Anees Iqbal 1eec182d2b Record each merge split instead of re-deriving the whole function's dominance after it
`privatize_reused_emitted_merge_targets` gives every owned construct its own merge by splitting
edges into a shared merge target. It called `loopforest::analyze(blocks)` once per claim, so a
function with one construct per block paid a whole-function analysis per construct. Measured on a
generated irreducible chain (`tests/bounded_growth.rs` builds the same shape):

    blocks   before   after
      1502    2.99s   0.40s
      3002   11.53s   1.27s
      6002   27.92s   4.87s

The 6002-block case was over the hard 20-second per-attempt ceiling in AGENTS.md. 87% of its
samples were inside that one call; a 750-claim run over 250 distinct targets re-derived dominance
750 times.

Two things were wrong and both are structural.

The pass only ever asks whether one block dominates another -- it never touches a natural loop --
but it asked for the loop forest, which pays for back-edge discovery, a body closure per header,
and a nesting comparison between every pair of loops before it can answer. `graph::block_dominators`
is now the way to ask the narrow question.

And re-deriving after a split is not needed at all. A split inserts one pass-through `S` between
some predecessors of `T` and `T`; every path through `S` is the old path with `S` elided, so
dominance among the blocks that were already there is exactly unchanged, and every path to `S` is a
path to one of its predecessors plus one edge, so a block dominates `S` exactly when it dominates
all of them. `graph::PassThroughDominance` computes the relation once and records each split.
Recorded splits resolve transitively to original blocks, so a pass-through carrying an earlier
pass-through is answered too.

`a_recorded_pass_through_answers_what_a_fresh_analysis_answers` performs two chained splices by
hand and cross-checks every dominance pair against the definitional path oracle already in that
file, so the equivalence is checked rather than argued.

`tests/bounded_growth.rs` gains the guard for this defect class. A peak-memory bound cannot see it:
each dominance table is linear and short-lived, so the high-water mark stays flat however many
times it is rebuilt. Total bytes handed out does see it. Doubling the function multiplied total
allocation by 3.71 before (187 MB -> 694 MB) and by 1.95 after (27 MB -> 54 MB); the bound is 2.6,
between them, the same way the existing peak bound sits between 2.00 and the dominator-set
representation's 3.85.

Verified byte-identical over 2880 local corpus sources and over the generated chain at 752, 1502,
3002 and 6002 blocks. Full gate green: fmt, clippy `-D warnings`, rustdoc `-D warnings`,
`cargo test --release -p metal2vulkan`, `cargo test -p metal2vulkan-validation`, and the debug
build so the new `debug_assert!` runs.

Still superlinear, and not claimed fixed: the per-claim scan over every block remains, now at a
couple of hash lookups each rather than a rebuilt analysis. A 12002-block chain still takes 18.3s
before returning an honest construction FALLBACK.
2026-08-31 18:44:17 +03:00
Anees Iqbal de7a3b7ba2 Measure that translation memory grows with the function, not its square
The 500 MiB per-translation budget does not get broken by leaks; it gets broken
by an analysis whose representation is quadratic in the block count. One such
representation shipped and stayed for a long time, because nothing about it is
visible on a small graph and every individual translation it produced was
correct.

`tests/bounded_growth.rs` installs a counting global allocator, translates a
generated kernel at 302 and 602 blocks, and asserts that doubling the function
does not much more than double peak translation memory. The ratio is a property
of the code rather than the machine: the allocator counts bytes the translation
asked for, which is the same number on any host, so this is not a microbenchmark.

The generated function is a chain of irreducible pairs. That shape is what
reaches the nesting structurizer's reducibility question -- the one that carried
the quadratic table -- and it also forces the whole function onto the
CFG-construction path instead of the ordinary structured planner, so the
analyses under test actually run.

Calibrated by running it against the defect: with the dominator-set form put
back behind `Graph::dominators`, the two functions measure 4.59 MB and 17.66 MB,
a 3.85x growth, and the test fails with that number in the message. With the
tree form they measure 2.50 MB and 5.00 MB, exactly 2.00x. The limit is 2.6.
2026-08-31 18:19:11 +03:00
Anees Iqbal a5e01c3f0e Take five more emission decisions off hash-map iteration order
A kernel with an unbound buffer parameter translated to different bytes on
almost every run. Its loads from the absent resource each become a copy of
that type's null, and the nulls were minted by iterating a HashSet of the
load result types -- so three loads of three distinct types came out in one
of six orders. tests/deterministic_output.rs has the reduced kernel, plus a
probe asserting it still reaches that rewrite, so the test cannot quietly
start passing over nothing.

Auditing the rest of the pipeline for the same shape -- a hash collection
whose iteration order decides what gets minted or pushed -- found four more:

  native/psb.rs                 OpTypePointer per memory-view pointee
  native/rewrites.rs            wrapper struct + pointer + decoration per
                                candidate pointer type
  passes/.../texture_array.rs   one access-chain id per bound handle, and
                                the dead-root list
  passes/.../selected_load.rs   OpDecorate ArrayStride per pointer type

Each now walks the module's own instruction stream instead, which makes the
order a property of the input. src/emission_order.rs holds that idiom in one
place so the correct spelling is the short one, and says which collection
each kind of question wants: a HashSet is still right for pure membership,
where nothing is ever iterated.

Verified over 900 local-corpus sources: 820 translated, 0 varied across four
in-process translations each. Before these fixes the same sweep found 24
varying inputs in its first 400.

The cross-stage fixture sweep is new and is what made the reduction findable:
determinism has to hold for whatever stage the caller passes, and translating
each fixture at all three reaches paths the declared stage never does -- a
parameter the declared stage binds to a descriptor is an unbound Private
placeholder under another.
2026-08-31 16:08:04 +03:00
Anees Iqbal e73c87d49b Stop three emission decisions from following hash-map iteration order
The same AIR translated to different SPIR-V on every run. Not different ids that
canonicalization normalizes away -- genuinely different modules: a different
prologue order, different constant declarations, different type declarations. Each
run was individually correct and passed spirv-val, which is why nothing caught it.

It matters because the validation ladder compares a candidate's output by SHA-256,
consumers cache translated SPIR-V by content hash, and a bug report is only
reproducible if the module that produced it can be produced again.

Three sources, all the same shape -- an unordered collection deciding the order
something is emitted or minted in:

- native emitter (functions.rs): the device-address prologue materializes one
  address per direct buffer parameter, and that list was built by iterating
  `raw_offsets`. The position each address lands at fixes which address-table slot
  the module reads there, so the whole prologue permuted. Order by entry parameter
  ordinal, which is stable and is the order a reader expects. The rewrite also
  drops a redundant `contains_key` and, with it, an eager map index that would have
  panicked on any raw offset that is not a direct parameter.
- buffer-address lowering (buffer_addresses.rs): `ctx.const_uint` mints a constant
  the first time it sees a value, so the order the table's location constants were
  requested in -- taken from a `HashSet` -- was their declaration order.
- nesting structurizer (reloop_nest/emit.rs): `demote_phis` walked `blocks.keys()`,
  minting a variable and a `TypePointer Function` per demoted phi in hash-map
  order. Record the function's own block order at indexing time and walk that.

tests/deterministic_output.rs pins the contract. Rust seeds every HashMap's hasher
differently, including two built in the same process, so translating one input
twice in one test is enough to expose an order-following emission decision -- it is
strictly stronger than comparing two CLI runs, and it found the second and third
sources after the first was already fixed. It covers an authored four-buffer
device-address kernel (with a guard that the kernel still lowers to an address
table, so the case cannot decay into covering nothing) and every public fixture
that translates.

Verified: the authored kernel produced 6 distinct hashes in 6 CLI runs before the
first fix and 1 after; 12 in-process runs collapsed from 2 distinct modules to 1
after the second. Over 1267 sampled local-corpus sources, 1159 translated and 2
still varied before the third fix; after it, a 240-source sample was fully stable
and the two known varying cases were checked individually. cargo test -p
metal2vulkan: 1704 lib + 3 determinism + 3 env + 6 fallback, all passing.
Workspace clippy -D warnings and all-features Rustdoc: clean.
2026-08-31 15:39:00 +03:00
Anees Iqbal 8b78eaca3b Expand macOS 26 AIR translation coverage
Overhaul the validation workflow around sharded authored cases, dependency-exact observations, incremental indexed corpus audits, bounded parallel translation, and native Metal/Vulkan comparison.\n\nExpand native AIR lowering, reflection, linked-function specialization, resource and stage-interface support, and structural CFG/pointer repair across the harvested macOS 26 corpus. Add exact intrinsic inventory, distributed 16x16x16 matrix lowering, explicit opaque tensor linkage, and regression coverage for the newly supported feature classes.\n\nThe final corpus verification accounts for all 88,819 indexed AIR modules under the current product fingerprint: 65,355 translate and validate directly, 23,464 require exact authored linkage, and zero fail or remain unresolved.
2026-08-13 21:46:27 +02:00
Anees Iqbal 1b013834bc Improve translation correctness and oracle safety
Add structural lowering fixes for function constants, byte aggregates, texture arrays, sampling, and SIMD operations. Harden corpus oracle planning and quarantine unsafe or non-comparable rows without GPU resubmission. Reject reused SPIR-V merge ownership and fast-fallback oversized systematic CFG failures so broken AIR returns promptly instead of emitting invalid bytes after lengthy retries.
2026-08-10 16:54:26 +02:00
Anees Iqbal 3007485352 🆕 Open Source metal2vulkan 2026-07-22 13:15:24 +03:00