Commit Graph
71 Commits
Author SHA1 Message Date
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 aafe9f1342 Read the address table off the module instead of predicting it
Whether a shader needs a buffer-address table is decided by the constructed
pointer graph: the emitter creates the descriptor when the graph needs one.
Reflection derived the same fact a second way, from a text scan of the AIR --
`has_device_address_pointer_load` looks for an `inttoptr` or a `load ptr` through
a device-address pointer, and only for `Stage::Kernel`.

Two independent derivations of one fact disagree. Measured over 2880 corpus
sources: 39 modules, in both directions. 13 declared a table at binding 640 that
reflection omitted -- a consumer building its descriptor-set layout from the
reflection under-binds and the shader reads an unbound descriptor. 26 reflected a
table the module never declared, demanding a buffer nothing reads. The binding
number could have disagreed too; nothing tied the emitter's choice to
reflection's first-free-synthetic search.

`ShaderReflection::reconcile_buffer_address_table` observes the module: it reports
one `BufferAddressTable` per synthetic-band binding the finished module decorates,
replacing whatever was predicted. `translate_sanitized_native_reflected` calls it
right after translation, before footprints and the final descriptor-ABI check, and
no longer calls `add_buffer_address_table` beforehand.

`reflect_sanitized` builds no module and keeps the prediction. That is now stated
at the function, with the measurement, rather than left as an unmarked equivalence.

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

  - emitted-vs-reflected address table disagreements: 39 -> 0
  - declared-but-unreflected bindings overall: 17 -> 4. The 4 that remain are
    `default_null_image_of` placeholders (3 of them with an unconsumed load, the
    same shape the read sampler had in cae8971).
  - 2880 sources byte-identical: this changes reflection, not emission.

No new test. `deterministic_output.rs::the_device_address_kernel_really_reads_an_
address_table` already pins the positive case and still passes through the new
path. I tried to author a failing case -- a fragment entry doing the same
device-address load, where the prediction is gated off by stage -- and the emitter
built no table for it, so the fixture would have asserted nothing. The corpus
numbers above are the evidence; the disagreeing sources are private.

Folded into the unreleased reflection v31 rather than bumping again.

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:55:54 +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 7e47d44e8c State the global-variable liveness rule once
`fc_specialize` carried its own copy of it. After pruning the arms that read a
disabled feature's resources, `drop_unreferenced_entry_interface_globals`
rebuilt the entry interface from the variables function bodies still reference,
dropped the variables that left, and swept the debug/decorate records the prune
had orphaned -- 95 lines, including a second `defined_ids` identical to
`module_cleanup`'s.

That is `passes::drop_unreferenced_global_variables` followed by
`passes::drop_dangling_debug`. The copy differed in one way: it declined to
remove a variable that was not already in the entry interface. That narrowing
protects nothing -- `finalize` applies the broad rule to every module this
specializer is ever handed -- and it is not what the copy was for.

Verified, since this is a public API (`specialize_function_constants_zero`) with
no CLI path and therefore no ordinary corpus coverage. Translating all 2880
corpus sources and specializing each result:

  - the narrowing was inert: 1816 variables removed across 880 sources, every
    one of them already in the original entry interface, none outside it
  - specialized output is byte-identical before and after, 0 of 2880 differ
  - translator output is byte-identical too, 0 of 2880 differ

`drop_dangling_debug` now takes `&mut Module` rather than `&mut Ctx`, which is
all it ever read, and `drop_unreferenced_global_variables` filters interface
entries against the referenced set on every call rather than only when it has a
variable to remove -- so an interface entry naming an id that is not a declared
variable at all is dropped too, which is what the copy did and the shared rule
did not.

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:18:40 +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 bf8493b773 Delete four string helpers the typed carrier replaced
`is_phi_line`, `redirect_label`, `is_ident_char` (`structured_emit/phi_util.rs`) and `relower_phi`
(`tir/phi_edit.rs`) are `#[cfg(test)]`, so they are not in a release build at all — they are what is
left of the string-line era, kept alive by their own tests. Each has a typed successor that the
codebase already points at: `TirInst::is_phi` (`tir/mod.rs:1191` calls the string form its "dual"),
the typed terminator redirects (`tir/mod.rs:379,413`, "the typed dual of applying the text
`redirect_label`"), and the specific typed phi edits `relower_phi`'s own module doc lists in its
place. `is_ident_char` had no caller but `redirect_label`.

`inline.rs` keeps its own private `is_phi_line`; that one is production and untouched.

The three tests that exercised only the deleted helpers go with them (1732 -> 1728). Test-only code
with production visibility reads as live behaviour, and this crate has enough of it that I mistook
one for a live bug site earlier in this session.

`cargo fmt --all --check`, clippy `-D warnings`, `RUSTDOCFLAGS='-D warnings' cargo doc`,
`cargo test -p metal2vulkan` debug and release, `cargo test -p metal2vulkan-validation`. No release
binary change is possible: every deleted item was `#[cfg(test)]`.
2026-08-31 21:17:13 +03:00
Anees Iqbal 6f01edbc44 Extend the decline discipline past the memcpy family, and to the sidecar
Five more handlers outside `memcpy_memset.rs` emit before they know they will decline. They are
less severe than the memcpy cluster — none of them emits a store — but each leaves the caller
holding instructions after reporting that nothing happened:

- `emit_selected_access_tree_phi` builds the access tree for the first incoming edge and bails on a
  later one whose pointer kind does not match, leaving abandoned access chains **and abandoned
  `OpPhi`s** while the caller falls through to `emit_bda_address_phi`;
- `emit_provenance_pointer_icmp` flattens both operands' gep provenance, emitting the index
  arithmetic, then declines when a later index pair will not compare;
- `emit_selected_load_pointer_gep` emits the true arm's access chain and then finds the false arm
  has neither a pointer nor a raw offset — the guard exists precisely because an arm can be absent;
- `emit_pointer_from_local_dynamic_field_load` and
  `emit_first_scalar_aggregate_reinterpret_store` materialize an operand through `value_id_in` and
  then fail a later type check.

All five now run through `staged_emit`.

The last one also had a leak `staged_emit` cannot reach. It pushed a
`LocalPointerDynamicFieldLoad` naming `result` into the emit sidecar *before* three of its four
`Ok(false)` paths — and the handler the caller falls through to is given the same `result`, so a
declined attempt left the sidecar describing an id that a different lowering produced. The record is
still built where its inputs are in scope, but is pushed only on the two paths that define `result`.

Verified: 2880 corpus sources byte-identical against a327e4e, so none of these five declined on a
translating source here — unlike the memcpy leak, which changed three. Fixed for the same reason
that one was: the contract is not checkable by reading, and the next edit does not preserve it.

`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:13:04 +03:00
Anees Iqbal a327e4e5ae A declined emit step must emit nothing
The emitter dispatches most lowerings as a chain of responsibility: a handler takes the caller's
instruction stream and answers `Ok(true)` for "I emitted it", `Ok(false)` for "not mine, try the
next". So `Ok(false)` is a claim about the stream as much as about the handler, and the next handler
— or `drop_unmodeled_memcpy`, which discards the call outright — acts on it.

A handler that walks an aggregate cannot know it will decline until it reaches the member that
defeats it, and by then it has emitted the members before it. Seven in the memcpy family do this.
The worst is `emit_prefix_struct_memcpy`: it copies field 0 with a real `OpCopyMemory`, finds field
1 running past the requested byte count, and reports that it did nothing. A 6-byte `llvm.memcpy`
between two `{ i32, i32 }` allocas reaches it — the destination's first field is written and the
rest is not, in a module that would validate cleanly.

`emit_raw_to_typed_struct_memcpy` already avoided this by building into a scratch vector and
splicing it in only on success, with the reason written next to it: "nothing partial may be
committed to the real stream". That pattern is now `staged_emit`, named and applied, so it is used
rather than remembered. Seven handlers run through it; ids a declined attempt minted stay minted,
which costs nothing and keeps every id unique across attempts.

Measured over 2880 corpus sources: **3 change, and every difference is dead code the leak left
behind** — 12 `OpBitcast`, 17 `OpCompositeExtract` and 1 `OpLoad` removed from each, with the
`OpStore`/`OpCopyMemory` counts and every other opcode identical, and all three still spirv-val
clean. So on this corpus the leak was dead weight rather than a partial write; the partial write is
reachable, not observed.

I could not author a shippable fixture that shows the leak inside a *translating* module: the
shapes I built either translate without reaching the declining handler, or fall back because the
memcpy survives as an `OpFunctionCall` (`bugs/memcpy/` holds them). The regression cover is
therefore `staged_emit`'s own tests plus the corpus measurement, not a fixture.

`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:09:28 +03:00
Anees Iqbal 83993b3175 The selection loop's forest is maintained, not current — say so where it is read
`record_pass_through` documents a real and narrow argument: splicing one pass-through `S` in front
of `T` leaves every pre-existing dominance relation intact, because every path is the old path with
`S` elided. Reading that at `cur_forest` invites the conclusion that the forest the selection loop
reasons with describes the graph the loop is holding. It does not.

Only two of the eleven mutations in that loop record anything. Measured over a 2880-source corpus:
17 sources finish with `cur_forest` disagreeing with a fresh `analyze(&out)` about a pair of blocks
that both already existed, in both directions, and the first divergence was attributed each time to
`synth_unique_selection_merge_phi_explicit` or `finish_construct_tree_selection_owner` — neither of
which is a pass-through splice.

I did not repair it, and the comment says why rather than leaving the next reader to re-derive it:
re-deriving the forest at the top of every iteration produced byte-identical SPIR-V for all 2880
sources and doubled the slowest one, 2.96s to 6.12s against a 20-second ceiling. So the staleness
costs nothing observable today and the fix costs half the ceiling's headroom. The comment also
states the residual risk plainly — a query that lands on a stale pair would be a wrong ownership
decision and nothing would catch it — and records that neither `bounded_work.rs`'s generated
selection chain nor a generated irreducible nest reaches the state, so the guard this wants has no
fixture yet.

Comment only; no behaviour change. `cargo fmt --all --check`, clippy `-D warnings`,
`RUSTDOCFLAGS='-D warnings' cargo doc`, `cargo test -p metal2vulkan`,
`cargo test -p metal2vulkan-validation`.
2026-08-31 20:47:33 +03:00
Anees Iqbal bc23fe636b Say which view went unrepaired, not which arithmetic computed the offset
Nine of the twelve remaining non-function-pointer corpus rejections are one shape, and its
diagnostic pointed away from it. `index 0 into %22 (TypeStruct %21) is %658 (BitwiseOr %657 %655)`
names the instruction that computed the offset, so the message reads as though the AIR contained an
`or` — it does not; none of these sources contain a single `or`, and the operand is emitter-
synthesized address arithmetic that varies by source (`BitwiseOr` in eight, `SConvert` in the
ninth). A previous session authored three synthetic reductions of that `BitwiseOr` shape and all
three translated cleanly, because the operand was never the trigger.

What the module does say, and did not report: `%22` is a single-member struct over a runtime array
of `TypeInt 32`, and the chain's own result pointee is `TypeInt 8`. That is the whole diagnosis — a
byte view of a word array, arriving as one dynamic index into the raw-word block, which is the shape
the four `rewrite_dynamic_struct_index_*` passes exist to repair and none of them matched. It also
distinguishes the ninth source, whose struct has six members and so is a genuine bad member select,
not a view at all.

So on that shape — and only that shape, since a dynamic index into any other struct really is a bad
member select — the violation now names the element type and the view type. Verified against the
corpus: it reports `TypeInt 8` over `TypeInt 32` on all eight, and stays silent on the ninth.

Behaviour is otherwise unchanged: 2880 corpus sources byte-identical against d862cd1 (a rejected
source is still rejected, with a longer message). `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 20:20:06 +03:00
Anees Iqbal d862cd11ee Key the structurizer's cached analyses on a block revision, not on remembering to invalidate
`forest_loop_merges` caches a `LoopForest` and a selection-merge map across the loop headers it
plans, because deriving them once per graph edit instead of once per header is the difference
between a bounded translation and a quadratic one. It invalidated that cache by hand: eight
separate `collision_cache = None` assignments, one per mutation site, plus a `mutated` flag
threaded through the collision branch to drive two more. Every future edit that adds a mutation
has to remember to add a ninth, and a missing one is invisible — the stale forest still answers
every query, just about the graph as it was.

`RewriteBlocks` owns the block list and a revision only it can advance; `AnalysisCache` remembers
the revision an analysis came from and re-derives exactly when it no longer matches. The eight
assignments and the `mutated` flag are gone, and there is nothing left to forget.

`rewrite` advances the revision only when a rewrite commits, which is sound because a decline
leaves the list untouched (02c3f9e). Debug builds check that instead of trusting it: a rewrite that
declines with the list edited fails at that call rather than at whatever wrong answer the poisoned
cache produces later. `edit` — for a rewrite that does not report whether it fired — advances
unconditionally.

The reuse this buys was previously argued rather than checked. The collision test re-derived the
forest that the top of the same iteration had just derived; they are the same forest because the
only edit between them is on a path that `continue`s, which is a claim about code shape that
nothing enforced. Now they are the same forest because the revision is the same.

Verified: 2880 corpus sources byte-identical against eac559d. Slowest source (`fc78a004`) 2.81s ->
2.56s, and 2.77s at eac559d, so the analysis this recovers more than pays for the staged copy
02c3f9e added. `bounded_work`'s kernel: 871 -> 867 source CFGs (it reaches the selection
structurizer, not this cache; comment updated). `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 20:02:54 +03:00
Anees Iqbal 02c3f9e2a8 A declined CFG rewrite must hand back the CFG it was given
The structurizer's `synth_*`/`split_*` primitives all advertise the same contract —
`synth_two_target_dispatch` states it outright: "Apply only after every region/type/dominance
proof succeeds, so a declined dispatch leaves the caller's owned CFG untouched" — and callers
depend on it. `forest_loop_merges` only drops its cached `LoopForest` and selection-merge map when
a primitive reports `Some`; a decline that edited the blocks anyway leaves that cache describing a
graph that no longer exists, and every later header is planned against it.

Six primitives edit before their last proof. Two are reachable, and the new tests reach them:

- `split_two_target_critical_edges` redirects the source terminator to both fresh edge blocks
  before it has checked that each dispatch target is a block. When one is not, it bails with the
  redirect applied and the edge blocks never inserted — the source ends up naming successors that
  are not in the function.
- `synth_multi_exit_merge` composes that split with the dispatch proof, and the split must run
  first (the proof needs one unambiguous predecessor per exit). So any dispatch decline — an
  uncarried block, a non-dominating live-in, a live-in whose type cannot cross the funnel — returns
  `None` with the loop's critical exit edges already split.

The other four (`synth_two_target_dispatch`, `synth_multi_latch_continue`,
`synth_unique_selection_merge_phi_explicit`, `split_phi_overlap`) each stage their proofs correctly
and then leak on one trailing `lower_block_carrier(...)?` — the last of which would abandon phi
rewrites and edge redirects pointing at a merge block it failed to build. I could not author an
input that reaches any of them: they lower a fixed synthetic `br` line, which the codebase treats
as infallible elsewhere (`terminal_exit.rs` `.expect("synthetic conditional carrier is always
parseable")`). They are unreached today, not guaranteed.

That is the shape of the problem: the contract held only where someone had proved every `?` in a
body unreachable-after-the-first-edit. That is not a property a reviewer can check by reading, and
not one the next edit preserves. So `atomic_rewrite` now runs each of the six against a private
copy and commits it only on `Some`. `BodyBlock` keeps its payload behind an `Arc`, so the copy is a
vector of (name, role, pointer) and only blocks the rewrite actually edits are deep-copied — the
copy-on-write `typed_mut` already performs on every edit. A borrowed name counter is deliberately
not rolled back, so names a declined attempt consumed stay consumed and every synthesized name
stays unique across attempts.

Verified: 2880 corpus sources byte-identical against eac559d, so nothing currently observed took a
corrupting path. Slowest source (`fc78a004`, 44 blocks) 2.81s -> 2.85s, against a 20s ceiling.
`cargo fmt --all --check`, clippy `-D warnings`, `RUSTDOCFLAGS='-D warnings' cargo doc`,
`cargo test -p metal2vulkan` (debug and release, so the `bounded_growth` and `bounded_work` guards
ran), `cargo test -p metal2vulkan-validation`.

The diff reads large only because six bodies moved one level in; `git diff -w` is the wrapper.
2026-08-31 19:50:26 +03:00
Anees Iqbal eac559dcb3 Build the structurizer's test CFGs from one fixture, not six copies
Six `#[cfg(test)] mod`s under structured_emit each carried a private, byte-equivalent
`bb(name, lines)` (reject.rs's took a role, which is bb_role). A file without a test module
therefore had to grow a seventh copy before it could grow its first test, and a change to how
production populates a block carrier had to be found in six places.

One `test_support` module owns both constructors; every test module imports them.
2026-08-31 19:43:03 +03:00
Anees Iqbal 4968b0a7dd Say which residual CFG limit left a function with no construction
`native emitter: selected CFG function cannot be constructed` was the whole error. A shader that
crosses the state-machine construction's fixed 8192-block ceiling got exactly that, and the ceiling
is not derivable from anything its author can see: finding it means bisecting the shader. It took
one this session -- an 8195-block generated kernel translates at 8192 and fails at 8195, with no
hint that a size boundary was the reason.

The reasons already existed. `rewrite_function` names a residual CFG limit at each of its thirteen
`bail` sites, and every one of them went only to a `METAL2VULKAN_RELOOP_WHY` trace. They now come
back to the caller as `ReloopDecline { function, blocks, reason }`, and the emitter's error carries
them:

    native emitter: selected CFG function cannot be constructed; the state-machine construction
    declined %1041 with 8195 blocks: too-many-blocks (the state-machine ceiling is 8192 blocks)

`rewrite_function` returns `Result<(), &'static str>` rather than `bool` so that an unnamed decline
cannot be written. Three of its declines were a bare `return false` -- a block with no label, a phi
with no result type, malformed phi operands -- and are now `block-without-label`,
`phi-without-result-type` and `malformed-phi-operands`. The type is the enforcement; a test that
scanned the source for `return false` would have been checking what the compiler already checks.

`relooper_block_ceiling` gives the boundary a name (`MAX_RELOOPER_GROUPS` nested dispatch groups of
`MAX_RELOOPER_BLOCKS` cases) instead of leaving it as a multiplication inside a bail condition, and
`a_function_over_the_state_machine_ceiling_declines_by_name` pins it exactly: a function at the
ceiling does not decline for size, and one block over does, by that name and with that count. It
builds its module directly rather than assembling, so it needs no `spirv-as` -- the size check runs
before any terminator is decoded.

The decline list is bounded to four with a count of the rest, like the contract renderer in
`af3a097`.

Scope of the evidence: no source in the 2880-source local corpus reaches this path, so the message
is verified on the generated 8195-block kernel, not on captured input; output over those 2880 is
byte-identical. Full gate green -- fmt, clippy `-D warnings`, rustdoc `-D warnings`,
`cargo test --release -p metal2vulkan`, `cargo test -p metal2vulkan-validation`, and the debug build.

The nesting structurizer, which declines first, still reports no reason of its own; the error says
only what the state-machine construction knows and claims nothing on its behalf. The 8192-block
ceiling itself is deliberate and unchanged -- large flat dispatch switches have pathological driver
compile behaviour -- so this makes the boundary visible rather than moving it.
2026-08-31 19:26:55 +03:00
Anees Iqbal c43bb11612 Record the structurizer's selection splits too, and count the analyses so neither comes back
The selection structurizer re-derived dominance and rebuilt the source CFG after every private
merge it spliced in, the same defect fixed one commit ago in the merge-ownership pass. Counted on
the slowest source in the local corpus -- a 44-block kernel that took 4.2 seconds -- translation
built 19,384 source CFGs, and 9,522 of them, 55% of the total block-visits, came from that one
statement. It is now 2.7 seconds, and it is the slowest source in the corpus by wall clock.

`unique_selection_merges_with_loop_exit_and_forced_inner` splices a pass-through in front of a
shared natural merge, once per header that claims it, and the `!construct_tree_owned` arms then
re-derived so the new block would participate in the next header's ownership question. Recording
the split answers that exactly, for the reasons `Dominators::record_pass_through` sets out: a
pass-through elides out of every path through it, so the blocks that were already there keep their
dominators, and the new block's follow from its predecessors. The natural loops were already known
to be unchanged -- an acyclic pass-through in front of an existing block adds no back edge -- which
is why the old code called `analyze_reusing_natural_loops` rather than `analyze`.

The last commit's `PassThroughDominance` is folded into `Dominators` itself. The structurizer's
`cur_forest` has to stay a `LoopForest` (the synthesis functions take one), so the recording has to
be reachable from there; putting it on the dominator relation gives it to both callers with no
signature churn, and `LoopForest::record_pass_through` forwards. The contract that a pass-through is
never itself a split target is now a `debug_assert!` that costs nothing until something records.

`header_owned_merge_predecessors` replaces two identical copies of the rule for which predecessors a
selection header owns. It has a third caller now -- recording a split means naming the edges it
carried -- and three copies of that filter would be three things to keep in step.

Two regression guards, because the two ways to be quadratic need different instruments:

* `src/native/tests/bounded_work.rs` counts source CFG constructions for a kernel whose loop exit is
  claimed by six selections. 871 as it stands; 2209 with the re-derivation put back; the bound is
  1400. The count is exact and machine-independent -- six sizes reproduce to the block over repeated
  runs -- where the wall time this defect actually costs is neither. The counter is `#[cfg(test)]`,
  thread-local, and absent from a release library.
* `tests/bounded_growth.rs`'s total-allocation bound, added last commit, is what covers the
  merge-ownership pass; this kernel does not reach that pass, and its peak-memory bound sees
  neither. Both files now say which defect each number catches.

Verified byte-identical over 2880 local corpus sources, and over the generated irreducible chain at
1502, 3002 and 6002 blocks. A fresh timing sweep over the same 2880: 0 over the 20-second ceiling,
slowest 2.74s. 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!` and the counter both run.

Not claimed fixed: 871 whole-function analyses for a seventeen-block kernel is still far more than
that kernel is worth, and the retry ladder, not any one pass, is where the rest of them come from.
2026-08-31 19:12:03 +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 9d662c9461 Classify the rejected graph once, not two or three times
The construct-tree recovery in `emit_function` tries two recognizers in turn,
and each opened by calling `structured_reject_reason` on the graph -- which
replays the whole planner ladder: privatization prepasses, loop forests,
dominators, post-dominators, several `structured_plan` variants. The caller
hands both recognizers the same blocks (the arm that rewrites them is also the
arm that skips the second recognizer), so that was the same pure function of
the same input, computed twice. The straddle recognizer then derived it a third
time inside its witness derivation.

The comment above the call site already said this "duplicates the very planner
work the global ownership tier exists to replace", and the response had been to
gate it on block count. That bounds the damage; it does not remove the work.
Under 300 blocks it was still paid in full, and 300 blocks is most shaders.

Both recognizers now take the classification as an argument, so they cannot
re-derive it, and `emit_function` derives it once.

Measured, release build, byte-identical output:
  fc78a004… (73-block fragment)  9.81s -> 4.54s
  5c3f91cc… (31-block fragment)  4.53s -> 2.16s
  2cc5611e… (31-block fragment)  4.63s -> 2.16s
  f0592493… (31-block fragment)  4.48s -> 2.13s
These were the four slowest sources in a 2880-source corpus sample; the sample
is byte-identical end to end (0 of 2880 differ).

Two tests pin the sharing rather than the timing. Each recognizer is handed an
*admitted* graph plus its own classification and must get past the gate to the
witness derivation; handed no classification it must decline. An edit that
reached for `structured_reject_reason` inside either one would derive `None`
for these graphs and fail both directions.
2026-08-31 18:06:33 +03:00
Anees Iqbal 07c999ad65 Finish the job: the source CFG and the emitted CFG share the one dominator core
Correction to db01510. Its subject said "one dominator computation, not three",
which was wrong when I wrote it: `native::cfg::graph` had a fourth (string-keyed
CHK, reused by the loop forest for post-dominators) and `native::cfg::exit_check`
a fifth (label-keyed, over the emitted SPIR-V CFG). Three was the number I had
just touched, not the number that existed. This commit makes the claim true.

Both now go through `native::dominators`. `graph::named_dominators` is the
adapter for named blocks -- dense indices from a deterministic block order,
dominance run once, results mapped back -- and the loop forest's reverse-graph
post-dominators use it too, since post-dominators are dominators of the reverse
graph rooted at a virtual exit. `EmittedDominators` builds the same dense view
from the label list and keeps only the intervals.

`EmittedDominators::new` loses its `entry` parameter. Every caller passed
`labels.first()`, so the entry is now defined as `labels[0]`, which is also what
the shared computation assumes; passing it separately was a way for the two to
disagree.

exit_check's own module doc already recorded that its dominator *sets* had once
"drove large translations far beyond their resident-memory budget". The same
quadratic form was still live in the structurizer's shape layer, three
directories away, and cost 400 MiB on a 6301-block function. That is the case
for one implementation rather than a warning in each.

Verified: full test suite, clippy, rustdoc, and byte-identical output over a
2880-source corpus sample (0 of 2880 differ).
2026-08-31 17:56:40 +03:00
Anees Iqbal db01510465 Leave one dominator computation in the crate, not three
The owned-CFG check, the relooper's loop-header scan, and (as of the previous
commit) the nesting structurizer each ran Cooper-Harvey-Kennedy over reverse
postorder and numbered the result into Euler intervals. Three copies of one
algorithm is how the structurizer ended up with dominator *sets* in the first
place: nobody writing it had a shared implementation to reach for.

Moved the index-based core out of `owned_cfg` into `native::dominators`, which
is now its only home, and pointed the structurizer's shape layer at it through
a label-to-index map it can build in one pass. `owned_cfg` and `rewrites` are a
pure move; the shape layer loses the private copy added in fdece24.

The core carries the oracle test the duplicates never had:
`the_intervals_answer_exactly_what_the_dominator_sets_answer` runs the dense
fixpoint as a test-only reference and cross-checks every ordered block pair on
nine shapes -- straight line, diamond, loop with exit, nested loops, self loop,
irreducible pair, unreachable block, rejoining paths, single block.
`the_tables_hold_one_entry_per_block` pins the linear representation.

Verified: full test suite, clippy, rustdoc, and byte-identical output over a
640-source corpus sample (0 of 640 differ).
2026-08-31 17:37:54 +03:00
Anees Iqbal fdece243c0 Stop asking one reducibility question with a quadratic dominator table
The nesting structurizer decided reducibility from full dominator *sets*: a
`BTreeSet` of every dominating block, per block. That is quadratic in the block
count, and generated shaders reach block counts where it dominates the whole
translation's memory. On an MPS convolution kernel with a 6301-block function
it materialized ~40 million set entries -- peak RSS went 85 MB -> 502 MB inside
`Graph::is_reducible` alone, and the module then finished at 535 MB, over the
500 MiB per-translation budget that AGENTS.md makes a correctness contract.

Replaced it with the Cooper-Harvey-Kennedy immediate-dominator iteration over
reverse postorder, numbered into one pre-order interval per block. Dominance is
then two integer comparisons, and the structure is linear in the block count.
The reducibility walk itself is untouched; only the question's answer moves.

Measured on the 21 corpus sources the audit recorded as memory-limit failures,
release build, `/usr/bin/time -l`: the 16 that reach the structurizer drop from
509-546 MB to 86-107 MB peak RSS, and are a little faster (2.6-3.0s vs
3.0-3.4s). The other 5 fall back early and are unchanged. Output is
byte-identical on all 21, and on a 640-source corpus sample (0 of 640 differ).

Two tests. `the_dominator_tree_agrees_with_the_dominator_sets` keeps the dense
fixpoint as a test-only reference and cross-checks every ordered block pair on
eight graph shapes, including the irreducible ones the verdict exists for.
`the_dominator_structure_stays_linear_in_the_block_count` asserts the structure
holds one number per reachable block on an 8001-block graph, which is the
property that regressed here: the dense form would report n*(n+1)/2.
2026-08-31 17:18:54 +03:00
Anees Iqbal d882fa599b Report every contract violation a phase leaves, not just the first
The pass-contract trace stopped at the first owned-construction failure, and
in flight that is routinely the least interesting one. Lowering leaves dangling
debug `OpName`s behind constantly and repairs them a few phases later, so on
the two access-chain repros the trace read "Name references undefined id" for
five consecutive phases -- masking, in one of them, an access-chain violation
that was already present and never repaired. A reader following the trace
blames whichever phase runs after the repair. That is not hypothetical; it cost
a previous session a round.

Split `owned_module_failure` into a prerequisite stage and a set of independent
checks. Section layout and the id-collection scan stay hard stops, because a
failure in either leaves the definition table incomplete and every later check
would be reading nonsense. Everything after is collected into
`owned_module_failures(module, limit)`. The gate calls it with limit 1 and is
unchanged; the trace calls it unbounded and prints all of them.

On the `particle_compact_data` repro the trace now shows the bad struct index
present from "air lowering start" onward -- i.e. introduced by the interface
phase -- where before that line said only "Name references undefined id %50".
2026-08-31 16:55:40 +03:00
Anees Iqbal af3a097cdc Bound the contract renderer, and correct two claims I made earlier
describe_owned_id printed every operand of the defining instruction, so a
wide OpTypeStruct or a phi with many arms would have buried the sentence
the message exists to say. It now shows eight and counts the rest, and has
a test that pins all four renderings including the undefined-id case.

Two corrections to the record, since the commits that made these claims
cannot be amended:

1. c2ba4ab said the non-constant-struct-index class is the "base has type
   TypeInt 64" class seen from the other side. It is not. The repro I
   checked (entry particle_compact_data) has zero device-address loads --
   no `load ptr addrspace(1), ptr addrspace(2)` anywhere -- and its 64-bit
   value comes from lower_scalar_i64_arithmetic_to_u32_halves recombining
   u32 halves. The two classes share a symptom, not a cause, and want two
   fixes.

2. I then read METAL2VULKAN_PASS_CONTRACT's "cleanup start" verdict as
   proof the class originates in the emitter. Also wrong: that verdict is
   a different violation which a later phase repairs. Scanning for the bad
   *shape* after every pass instead puts the origin in
   passes::stage_input::build_stage_input, which emits 24 chains of the
   form `OpInBoundsAccessChain %blockvar %runtimeIndex` on synthesized
   StorageBuffer block variables -- one index where a {RuntimeArray} block
   struct needs two. word_access.rs gets the same rebase right: it pushes
   const_uint(0) ahead of the word index for every storage class except
   Workgroup.

No fix here. The exact site inside build_stage_input is a base/result-type
substitution on an existing chain rather than one of the two AccessChain
constructions in stage_input/, and I would be guessing. The localization is
recorded so the next pass at it does not start from the symptom.

Also verified while here: the cross-stage corpus sweep is clean at 706
translating source/stage pairs, 0 varied.
2026-08-31 16:38:28 +03:00
Anees Iqbal ad355fcf49 Let the lowering pipeline name the phase that broke a contract
A contract violation is a property of the FINISHED module. Which of the
phases in transform_with_options_and_sidecar introduced it is not recorded
anywhere, so diagnosing one means bisecting the pipeline by hand -- which
is exactly what I was doing when I wrote this.

METAL2VULKAN_PASS_CONTRACT=1 now prints the owned-construction verdict
after every phase. It is a debugging aid, not a gate: a module part-way
through lowering is allowed to violate the contract, since several phases
exist to repair what an earlier one left behind. What the trace shows is
the shape of the run, and the phase whose verdict first turns bad and
never recovers is the one to read.

Two things were needed to make it readable rather than noisy:

- The verdict merges ctx.new_globals into the module before checking.
  Phases stage new declarations there and splice them in only at the end,
  so checking ctx.module alone reported an undefined id for every phase in
  between and drowned out the real signal. phase_contract_verdict is split
  out from the printing so both halves of that are unit-tested.

- "owned module references an undefined id" now names the referencing
  instruction and the id: "owned Name references undefined id %50". On the
  module I was bisecting, that one change turned five phases of noise into
  a diagnosis -- a stale OpName left pointing at a removed id, cleaned up
  later, and nothing to do with the failure being chased.
2026-08-31 16:28:56 +03:00
Anees Iqbal c2ba4ab9a4 Name the value a non-constant struct index actually is
The clause split in 63b0c80 made a second class visible: 25 of the 200
sampled corpus failures reject a struct member index for not being a
constant, which the old blanket message had folded in with the rest. The
message named the id but not what defined it, which is the one fact that
identifies the bug.

It now reads:

  index 0 into %63 (TypeStruct %62) is %4019 (BitwiseOr %4018 %4016), and
  a struct member index must be an OpConstant of 32-bit integer type

so the class reads as what it is: a 64-bit device address, assembled by
OR-ing two 32-bit halves, arriving as the leading index of a buffer block
chain. That is the same defect as the "base has type TypeInt 64" class --
a device address reaching an access chain without OpConvertUToPtr -- seen
from the other side. Together they are 41 of the 200, which reads very
differently from two unrelated buckets.

The renderer already had every result id in the module available, not just
the types, so this is the same helper applied to the operand; it is renamed
from describe_owned_type to describe_owned_id to say so.
2026-08-31 16:18:00 +03:00
Anees Iqbal a2f4380448 Discover BDA storage pointers in the order the module presents them
A sixth instance of the emission-order class fixed in a5e01c3: the
buffer-device-address aggregate specialization walks a HashSet of storage
pointers and mints one OpTypePointer per distinct storage class it meets,
so a module whose pointers span two storage classes declared those two
types in whichever order the run's hasher produced.

The fixpoint that discovers them already walks the instruction stream in
order, so keeping the discovery order in a Vec alongside the set costs
nothing. The set still answers membership and still drives the fixpoint's
changed flag; only the iteration that mints now uses the ordered list.

Found by auditing the rest of the pipeline for the same shape rather than
by an input, so there is no reduced module for it here -- the cross-stage
fixture sweep and the corpus sweep both cover it going forward.
2026-08-31 16:15:40 +03:00
Anees Iqbal 63b0c80d0b Say which clause of the access-chain contract failed
"owned InBoundsAccessChain violates its pointer storage, index path, or
result-pointee contract" names three possible causes and commits to none.
It is the largest single failure class in the corpus audit (~40 of 88 at
the last fingerprint), and diagnosing one instance meant disassembling the
module by hand to find out which of the three it was.

The check was one boolean conjunction, so it had nothing to report. It now
evaluates the clauses in the order the contract reads and names the first
one that fails, with the offending type rendered as its declaration:

  base %418 has type %27 (TypeInt 64 0), which is not a pointer type

which is the dominant class, and says plainly what it needs: a 64-bit
device address used as an access-chain base wants OpConvertUToPtr into
PhysicalStorageBuffer, not anything to do with index paths.

The verdict is unchanged -- the accept/reject decision is still the same
conjunction, and which clause gets named cannot move it. What changed is
that the twelve rejections in owned_module_enforces_access_chain_contracts
are now paired with the clause each must be rejected FOR. All twelve turn
out to trip nine distinct clauses; a blanket "was rejected" assertion would
have stayed green if one of them had started tripping an unrelated clause
by accident.

The triage normalizer collapses digit runs, so the ids in these messages
fold away and the audit groups these by reason instead of by one bucket.
2026-08-31 16:12: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 9a642e930c Hold constructed shapes to validity and to a binary round trip
Executing a construction says it computes the right thing. It does not say a driver
would accept it: SPIR-V's structured control flow rules -- a block before every
block it dominates, a merge dominated by its header, a construct left only at its
own merge or an enclosing loop's continue -- are all things a semantically correct
rewrite can still break. spirv-val is what knows them, and until now it only ever
saw authored fixtures.

Point it at the generated family. The authored shape is invalid on purpose, since
that is what selects construction, so only the output is validated. Two fixture
corrections were needed first, both of them the fixture's fault rather than the
product's: the header claimed SPIR-V 1.6, which is rejected before any content is
examined under the Vulkan 1.2 target, and the entry point did not list its Private
globals, which SPIR-V 1.4 onward requires whatever the storage class.

Also round-trip each constructed module through binary and compare the
disassembly. An assembler and a parser that disagree about an instruction's
encoding are invisible to both validation and execution of the in-memory module,
and a consumer takes the bytes.

Verified: 3600 constructed modules over depths 2-7 and 0-3 crossings, every one
accepted by spirv-val. The committed guards hold 64 of those plus 48 round trips,
which keeps the suite fast -- spirv-val is a subprocess per module. cargo test -p
metal2vulkan: 1704 passed. Workspace clippy -D warnings and all-features Rustdoc:
clean.
2026-08-31 15:03:17 +03:00
Anees Iqbal e33ff25ce2 Run the constant-folding optimizer against an executable oracle
constfold is a general optimizer -- constant propagation, conditional-branch
folding, unreachable-block removal, trivial-phi collapse, DCE, to a fixpoint --
and its whole correctness argument is that it only removes what cannot execute.
Its tests were authored fixtures asserting which instructions survive. That checks
the rewrite it performed, not the meaning it was supposed to keep.

Give it a subject it cannot argue with. A generated shape seeded from a
constant-initialized Private global -- the shape a Metal [[function_constant]]
compiles to at its disabled default, and exactly what the optimizer keys on -- has
one answer. Author it as a void GLCompute entry point that stores that answer into
a Private slot, run it, fold it, and run it again.

The entry point is not decoration: sweep_uncalled_functions deletes any function no
entry point reaches, so a module without one has nothing left to check after
folding. Building it needs the entry-point mode and Private globals now in the
builder, and module-scope variables with initializers in the interpreter.

Both pass orders are exercised. Folding a constructed CFG and constructing a folded
one both happen in the pipeline, and an optimizer that is right on the input shape
can be wrong on the shape a structurizer left behind.

Verified: 8000 constant-seeded modules over depths 2-6, 0-2 crossings and four seed
values, each checked in both orders -- 16000 runs, none disagreeing with the
function before folding. The committed sweep holds 128 of those.
constant_folding_actually_removes_blocks_from_a_constant_seeded_shape pins that
the fold is doing work at all (measured 4131 blocks to 3772; the rest are inside
loops whose accumulator is not a constant), so the sweep cannot pass by folding
nothing. cargo test -p metal2vulkan: 1702 passed. Workspace clippy -D warnings and
all-features Rustdoc: clean.
2026-08-31 14:58:16 +03:00
Anees Iqbal 706ba952d3 Put the phi-demotion swap hazard under the differential sweep
Every generated shape carried one live value, so every join had one OpPhi and the
hardest question a phi demotion has to answer never came up: what happens when two
phis at the same block read each other.

`x = phi(x0, y); y = phi(y0, x)` is a simultaneous assignment. Demoting the pair to
memory turns it into two sequential stores, and in the obvious order the first
clobbers what the second was about to read. Both structurizers demote phis -- the
state machine demotes every value that crosses a block boundary, the nesting
demotes phi results specifically -- so both have to get this right, and nothing was
asking them.

Carry three values through a generated function instead of one. The accumulator
still drives every condition and still guarantees termination; the two new ones
drive nothing and are swapped with each other on every back edge, which puts the
hazard at every loop header in the family. The returned value combines all three
asymmetrically, so exchanging any two of them changes the answer.

Add the authored minimal case as well, and a test that the family really does
carry back edges for the swap to ride on -- measured 105/112 shapes and 262
swapping edges -- so this cannot silently decay into straight-line value flow.

Verified: 8000 shapes over depths 2-6 and 0-3 crossings, all three values live
across every construct boundary, every one computing what it computed before
construction. cargo test -p metal2vulkan: 1700 passed. Workspace clippy -D
warnings and all-features Rustdoc: clean.
2026-08-31 14:51:02 +03:00
Anees Iqbal 47060c4e44 Take the differential sweep onto the state machine's own territory
The generated family was reducible by construction, so the nesting structurizer
answered most of it and the state-machine constructor was only ever reached
through what nesting handed back. That is the constructor of last resort — there
is nothing behind it — and it was the least directly exercised.

Let a generated shape take an edge into the interior of a region already written.
The target keeps its predecessors and gains one that does not go through whatever
header used to dominate it, which is exactly irreducibility, and the nesting
structurizer declines it by contract. Guard the crossing with the same monotonic
`accumulator < bound` test the loops use, never a mask, so it stops being taken
once the accumulator passes the bound; a crossing guarded by a mask could close a
cycle containing no bounded test and the shape would stop terminating.

The cross-edge coin is flipped whether or not crossings are allowed, so a seed
names the same underlying shape either way and a failure can be diagnosed against
its reducible sibling.

Also give the generator a switch region. A SPIR-V switch is not a conditional with
more arms — a nested construct may break out to an enclosing switch and not to an
enclosing selection — so the two take different paths through the emitter and the
family should contain both.

Verified: 4500 shapes over depths 2-6 and 1-3 crossings, 2879 of them declined by
nesting and so constructed by the state machine; every one computes what it
computed before construction. The two committed tests hold 96 of those, with
irreducible_shapes_are_declined_by_the_nesting_structurizer pinning that the
family really is reaching the state machine (measured 66/96) rather than quietly
becoming a second run of the reducible sweep. cargo test -p metal2vulkan: 1698
passed. Workspace clippy -D warnings: clean.
2026-08-31 14:46:38 +03:00
Anees Iqbal 24f9f04308 Name the destination of every staged edge that leaves through a dispatch
The nesting structurizer stages an edge that has to leave more than one construct:
it records its destination in a function-scope flow variable, branches to the
innermost construct's merge, and every dispatch it passes through reads that
variable to decide whether to enter its own continuation or forward one more
level.

`resolve` decided whether to write the variable by asking the frame that owns the
*destination* — but the edge branches to the *innermost* frame's merge. When those
differ, the innermost merge is a dispatch (`classify` marks every frame it
forwards through) and reads the variable that this edge never wrote. Ask the frame
the edge actually leaves through instead.

`while (c) { if (d) { if (e) break; } q(); }` is the smallest case: the `break`
left the flow variable unwritten, so the dispatch at the selection's merge read
whatever the previous iteration had stored and ran `q()` after the break. The
module was valid SPIR-V and properly nested, so neither spirv-val, the
construct-ownership checks, nor the value-flow check in owned_cfg saw anything --
SSA dominance says nothing about what is in memory.

Contain the class as well as the case. reloop_nest::verify runs a
definite-assignment analysis for the flow variable over the emitted blocks and
declines a nesting that can reach a dispatch without having written it; a declined
function falls back to the state machine, which writes its selector on every edge.
Phi slots are deliberately out of scope there: their loads sit behind dispatch
arms the flow variable selects, so a path-insensitive analysis reports intended
routing as an unwritten read.

Add src/native/cfg_testkit, the differential harness that found this:

- build: author a synthetic uint(uint) function from named blocks, with reserved
  ids for forward references and reverse-postorder emission, so a CFG shape costs
  a few lines instead of a few hundred.
- interp: execute the authored integer subset -- phi, select, function-scope
  variables, all four terminators -- with a step limit, so a construction that
  loses an exit edge reports instead of hanging.
- shapes: grow reducible-but-unstructured graphs from a seed (sequence /
  conditional / switch / loop, perforated with multi-level breaks and continues).
  One monotonic accumulator threads the function, which both guarantees every
  generated shape terminates and makes a mis-selected phi change the answer.

Verified: over 1500 generated shape/depth combinations, 105 constructions
disagreed with the function they replaced before the fix and 0 after. With the fix
reverted but the verifier in place, adoption falls from 1327/1500 to 956/1500 and
disagreements stay at 0 -- the class degrades to a fallback, not to wrong code.
With both reverted, the two sweep tests and the named regression fail. The
adoption-rate test pins that correctness is not being bought by declining.
cargo test -p metal2vulkan: 1696 passed. Workspace clippy -D warnings and
all-features Rustdoc: clean. cargo test -p metal2vulkan-validation: 172 passed, 1
failed -- combined_depth_stencil_outputs_use_separate_native_attachments, which
needs a Metal toolchain this machine does not have.
2026-08-31 14:40:07 +03:00
Anees Iqbal 38d1ae3750 Pin both reported bugs with regression tests that fail without their fixes
The two bundles under bugs/ are fixed at HEAD, but neither loss was pinned by a
test that fails when the fix is reverted, and bugs/ is gitignored, so the
reproducers cannot serve as the guard. Both defects also passed spirv-val, so
validation cannot be the guard either. Author the guards from the property each
bundle actually lost.

fragment-code-size-explosion: the module reached the driver as one OpFunction in
state-machine form -- 2286 of 2296 blocks were sibling OpSwitch cases inside a
single loop, with 3516 function-scope variables because sibling cases cannot
dominate each other -- and vkCreateGraphicsPipelines never returned. Build a
reducible-but-unstructured function (one loop over a chain of undeclared-merge
diamonds), run it through the real construction path, and assert the emitted
shape: a surviving loop construct, dispatch over a minority of blocks, and no
variable-per-crossing-value demotion. Held at 16 and at 64 diamonds.

compute-multisample-query-reports-one: air.get_num_samples_texture_2d_ms lowered
to the literal 1, so a four-sample kernel visited only sample zero. Extend the
family to texture2d_ms_array, and add the data-flow guard the opcode-presence
assertions cannot make: the queried count must be what bounds the per-sample
loop.

Verified: with reloop_nest::structure_selected_functions stubbed out, the two
shape tests fail reporting 51 cases over 58 blocks and 195 over 202 -- the
reported 99%-coverage state machine. With the sample-count lowering forced to
the constant, all three multisample tests fail; with the query emitted but its
result replaced by the constant at the use, only the new data-flow test fails,
which is the case it exists for. cargo test -p metal2vulkan: 1688 passed.
Workspace clippy with -D warnings: clean.
2026-08-31 13:57:18 +03:00
Anees Iqbal 47009b2693 Trace when the nesting structurizer adopts a construction
METAL2VULKAN_RELOOP_WHY already reports every decline. Without the
matching adopt line there is no way to find which inputs actually reach
the nesting path, which is what authoring an execution case for it
needs.
2026-08-31 13:39:32 +03:00
Anees Iqbal 28580a51f6 Read a buffer's one element view, not the first of several
A buffer parameter whose entry body indexes it with a single index and
reads a different type at each index is navigating a record, not a flat
array. body_buf_elem_type returned the first of those views, so the
interface builder wrapped the buffer as { RuntimeArray<that type> } and
every access through another view kept its own result type while the
chain now addressed the wrong element: a float2 load off a chain into a
float4 array.

Return the element type only when the body has exactly one view. With
several, the AIR struct layout is reconstructed instead, which is what
the metadata already describes.

Re-auditing the 107 known translation failures: 88 fail, 19 translate
(was 90/17). Both cross-library cases that reported 'owned Load violates
its pointer-pointee and value-type contract' now translate.
2026-08-31 13:10:54 +03:00
Anees Iqbal 2722041b06 Hold a nesting to the whole construction contract, not just its value flow
Splitting the owned-CFG check leaves a structural half that reads only control
flow: construct containment, structured exits, switch merges, back edges, and
continue-target ownership. It needs no module-wide type tables, so the nesting
structurizer can hold its own output to it before adopting it.

Re-auditing the 107 rows the corpus-wide translation census failed on: 17 now
translate, and every 'owned switch case exits to a non-structured target' and
'owned edge exits a construct without a structured target' failure is gone --
those functions go back to the state machine instead of shipping a nesting that
leaves a construct through an unstructured edge.

bugs/fragment-code-size-explosion is unaffected: still 168 loops, 608 dispatch
cases, 33 function-scope variables, spirv-val vulkan1.2 PASS.
2026-08-31 12:46:23 +03:00
Anees Iqbal a8f6803ea5 Promote a demoted phi at the block where its edges meet
The promotion pass wrote the phi back into the block that loads the slot.
Nesting usually puts that block one unconditional hop below the join: a loop's
original header becomes the body of a synthesized header, and it is the
synthesized header that owns the back edge and so the meeting of the two
values. With two predecessors one step up and one step here, the slot did not
promote and stayed a function-scope variable -- exactly the loop-carried values
whose live ranges span the most blocks.

Walk up through single-predecessor blocks that do not write the slot before
choosing the phi's block. Every block stepped over is dominated by the one
before it, so the phi stays in scope wherever the load was.

On the bugs/fragment-code-size-explosion shader this takes function-scope
variables from 489 to 33 (3516 before the nesting structurizer) and the module
from 196,052 to 192,860 words, with the same 168 loops and 608 dispatch cases.
spirv-val vulkan1.2 passes.
2026-08-31 12:12:15 +03:00
Anees Iqbal acc37fdcc5 Check the nesting structurizer's value flow before adopting it
Nesting keeps ordinary values in registers on the premise that it preserves
the original CFG's dominance. It does not always: an edge that has to leave
more than one construct is staged through a merge dispatch, so its destination
is reached from that merge rather than from the block that left it, and a
definition inside the construct can stop reaching a use beyond it. The state
machine this pass replaced repaired such functions incidentally, by demoting
every crossing value.

Two private corpus cases regressed to a translation failure because of that.
Verify the emitted function against the same value-flow contract the module is
held to -- definitions dominating their uses, and phi incoming pairs matching
the block's predecessors and result type -- and put the function back on the
state machine when it fails, alongside the existing structural gates.

owned_cfg gains the function-scoped entry point for that check, reusing its
existing phi and ordinary-use rules rather than restating them.
2026-08-31 12:05:52 +03:00
Anees Iqbal a7f9119651 Put back the phis the nesting did not actually disturb
A phi has to be demoted while the structure is being derived, because
nesting is free to rewrite which block physically branches into a merge.
Most merges come through unchanged: each incoming edge still ends in a
block that branches straight at the merge, and the merge has no other
predecessor. That is exactly an OpPhi, so the slot is folded back and the
variable, its stores and its load all disappear.

The check runs on the emitted blocks, so it needs no model of how they
were produced -- an edge that got a helper block of its own is as good a
phi predecessor as the original block. It also looks through a chain of
single-predecessor branch-only blocks when hunting for the store, which is
what reaches a loop's continue target: the value is written by the latch
that branches into it, and each block in such a chain dominates the next,
so the value is still available where the phi needs it.

Measured on bugs/fragment-code-size-explosion/input-frag.air:

  function-scope variables   951 -> 489
  emitted words           199869 -> 196052

Against the state machine this replaced, that is 3516 -> 489 variables.

Verified: spirv-val vulkan1.2 passes on the emitted module; full
1682-test product suite green; fmt, workspace clippy with -D warnings and
all-features Rustdoc clean.
2026-08-31 11:41:26 +03:00
Anees Iqbal 0ac159bd6f Nest reducible control flow instead of flattening it to a state machine
The nesting structurizer now expresses everything the fragment shader in
bugs/fragment-code-size-explosion needs, so that module no longer reaches
the driver as one dispatch state machine.

Three things were missing.

Staged exits. SPIR-V lets a block leave the construct it is in and no
further, but `while (c) { if (d) { p(); if (e) break; } q(); }` leaves a
selection and a loop on one edge. Such an edge now records its destination
in one function-scope flow variable and leaves the innermost construct;
each construct it crosses carries a dispatch at its merge that either
enters its own continuation at the named destination or forwards through
that dispatch's merge block, which sits directly inside the next construct
out. An analysis pass decides which constructs need a dispatch, so a
construct no staged edge crosses and with one way out keeps a plain merge
and never touches the variable.

Switch constructs. A divergent terminator declares a selection of its own,
and SPIR-V allows breaking out of a nested construct only to an enclosing
loop or switch -- never to an enclosing selection. The analysis marks the
dispatches this applies to and they are written as OpSwitch.

Dispatch headers and arm entries. A dispatch entered from an enclosing
construct rather than fused into one terminator now gets a header of its
own, which is what gives it a merge block its arms' nested constructs may
break to; and an arm is a shape, not a block, so a loop arm is entered at
its synthesized header rather than at the original block. The latter was
producing a back edge into a loop body that bypassed the header.

Measured on that shader (release, 2.4s, unchanged):

  function-scope variables   3516 -> 951
  widest OpSwitch            1024 ->  122
  total switch cases         2286 ->  608
  OpLoopMerge                   0 ->  168
  emitted words            249063 -> 199869

The count that mattered is the first: the driver's compile went unbounded
promoting thousands of variables back to SSA inside one loop that held the
whole program. There are now 168 real nested loops and no whole-function
dispatch.

Verified: spirv-val vulkan1.2 passes on the emitted module; 12 nesting
tests including a new end-to-end pin for the two-construct break; full
1681-test product suite green; fmt, workspace clippy with -D warnings and
all-features Rustdoc clean.
2026-08-31 11:34:38 +03:00
Anees Iqbal 465c76d41e Add a nesting structurizer for reducible control flow
The state-machine constructor can express any CFG, and that generality
is why it makes every non-entry block a sibling case of one OpSwitch
inside one loop. Sibling cases do not dominate each other, so every
value crossing a block boundary is register-demoted to a function-scope
variable. On a large function that yields one loop containing the whole
program plus thousands of variables whose live ranges all span it. The
module is valid, and it is also the shape a driver's shader compiler can
take unbounded time on: promoting those variables back to SSA inside one
enormous loop makes the dominance-frontier work superlinear in
(variables x blocks). bugs/fragment-code-size-explosion is a boot that
dies inside vkCreateGraphicsPipelines on exactly that module.

Reducible control flow does not need it. This adds src/native/reloop_nest:
the relooper shape derivation (Simple / Loop / Multiple) as pure,
unit-testable graph analysis, and an emitter that writes those shapes as
genuinely nested SPIR-V loop and selection constructs. Nesting preserves
the original CFG's paths and therefore its dominance, so ordinary SSA
values are emitted untouched; only OpPhi -- whose meaning is the
predecessor list that nesting rewrites -- is demoted.

It is a strict addition. Construction tries the nesting first and keeps
its output only when the same structural checks that selected
construction in the first place accept it; irreducible graphs and any
shape the emitter does not express are declined, and those functions
stay on the state machine byte-for-byte.

Not yet expressed: a branch that leaves more than one enclosing
construct, and loops with several entries. The fragment shader in the
bug bundle still declines on the former and is unchanged for now.

Verified: 11 new tests (8 shape-derivation, 3 end-to-end through
spirv-as/spirv-val) plus the full 1681-test product suite green; fmt,
workspace clippy with -D warnings, and all-features Rustdoc clean.
2026-08-31 10:57:26 +03:00
Anees Iqbal 91a5e83f75 Lower AIR texture sample-count queries to OpImageQuerySamples
`air.get_num_samples_texture_2d_ms(texture)` is a property of the bound
image, but it lowered unconditionally to the literal 1. A guest kernel
that loops `for (s = 0; s < tex.get_num_samples(); ++s)` therefore visited
sample zero only and silently dropped every other sample of a 4x MS
texture. The emitted module stayed structurally valid, so spirv-val could
not catch the semantic substitution.

Decide the lowering from the image type instead of from a harness
assumption: when the resolved operand is a 2D image with MS=1, emit
OpImageQuerySamples on it; when it is single-sample, the constant 1 is
the exact sample count rather than a stand-in. A multisample operand with
a non-2D Dim is now an honest error, since OpImageQuerySamples is
undefined there.

Op::ImageQuerySamples was also missing from the ImageQuery capability
inference in module_cleanup, which would have produced an invalid module
the first time the query was emitted.

Verified: bugs/compute-multisample-query-reports-one/repro.sh now reports
PASS; two new regression tests pin the MS and single-sample paths; full
`cargo test -p metal2vulkan` (1670 tests) green; fmt and workspace clippy
with -D warnings clean.
2026-08-31 10:21:36 +03:00
Anees Iqbal 52c961b4de Tighten owned numeric conversion contracts
Split ConversionClass so each width-changing conversion carries its own
shape contract instead of sharing IntegerToInteger and FloatToFloat
buckets. OpUConvert, OpSConvert, and OpFConvert now require the source and
result component widths to differ: a same-width conversion is not a no-op,
it is an invalid instruction. OpUConvert additionally requires an unsigned
result type, since it names a zero extension or truncation.

Reject OpSatConvertSToU and OpSatConvertUToS as a shape class before they
reach a numeric contract that does not describe them; the saturating OpenCL
conversions require the Kernel capability and have no Vulkan environment.

Switch the conversion checks from scalar_type_shape to numeric_type_shape
so component width is available alongside opcode and lane count.

Cover each rejected and accepted shape with a test that pairs the owned
verdict against the independent spirv-val verdict, so the construction-time
rule stays a restatement of the Vulkan rule rather than a local invention.

Verified: cargo clippy --all-targets (clean). Per request, the cargo doc
check and workspace test run were skipped.

Claude-Session: https://claude.ai/code/session_015sJUGShcKseDFnk4WvaJU2
2026-08-31 09:50:44 +03:00
Anees Iqbal 08970cacd2 Consolidate translation, linkage, and validation work
Squash 147 commits (2026-08-20 through 2026-08-31) into one change on top
of the exact-kernel-grid work. Covers native lowering and pointer/layout
construction, AIR intrinsic and funnel-shift coverage, BDA address
preservation across aggregate calls, CFG structurization, function-constant
and visible-function specialization, the 30-second translation ceiling, the
authored-case corpus and linkage validation suite, and refreshed byte-exact
MoltenVK evidence.

The kernel-grid lowering in this tree supersedes the 324-line variant in
the parent commit; that file is reduced to its current 139-line form here.

Resulting tree is identical to 7174c7b. Prior history remains reachable at
tag pre-squash-backup and branch backup/pre-squash-7174c7b.

Claude-Session: https://claude.ai/code/session_01D1u4vU7Mr5QNWrnnRHC8iS
2026-08-31 09:03:42 +03:00
nkhaooat d98eae794b fix: float literal and phi parser fixes
Five LLVM IR parser bugs in metal2vulkan that caused shader translation
failures on macOS Ventura x86 guests:

1. f0x hex f32 literals (f0x358637BD etc.) not parsed
   - Added LlValue::Float32Bits(u32) variant
   - Added parse_float32_hex_literal() in lex.rs

2. Decimal float used as Half type (1.0 for half-typed constant)
   - Added LlType::Half arm to LlValue::Float dispatch
   - Converts decimal floats to half via f32_to_f16_bits

3. NaN/Inf special literals (+qnan, -qnan, inf, -inf, snan)
   not recognized by parse_value()
   - Added parse_float_special_literal() in lex.rs
   - Handles: +qnan, -qnan, qnan, snan, -snan, +inf, -inf, inf, nan, -nan
   - Maps to IEEE 754 f32 bit patterns

4. phi incoming values with typed vector constants not parsed
   (<4 x float> <float 0x3F800000, ...>)
   - Added parse_phi_incoming_value() in parse.rs
   - Tries parse_typed_value before parse_value for phi incomings
   - Same fix in operand_from_bare() in operands.rs

5. Diagnostic: phi_parse_error field on TirInst
   - Captures parse_phi error string for debugging

Tests: 1,390 pass, 0 fail (3 new regression tests)
Verified on macOS 13 Ventura x86 guest: 0 phi errors, 0 m2v refusals,
0 draw skips (was 4 phi errors, 94 refusals, 106 draw skips before fix)
2026-08-31 08:04:21 +03:00
Anees Iqbal 9ff250502c Make exact kernel grids safe by default
Model kernel dispatch geometry as a typed contract shared by lowering, reflection, validation, and the CLI. Cull surplus dispatchThreads invocations using fixed or reflected push-constant grid bounds, make that safe dynamic-grid path the default, and require an explicit whole-workgroup assertion to omit it.

Reject unsafe source-barrier kernels before every product emission facade by following the selected AIR entry graph, including quoted LLVM symbols. Exercise the same default contract in authored candidate validation and document the host ABI.

Keep corpus audit parent concurrency bounded by feeding isolated translation workers from scratch-backed stdin files instead of creating one feeder thread per row. This removes the scoped-thread exhaustion that aborted late full censuses while retaining child decoding inside the time and memory watchdog.

Verified with format checking, warnings-denied workspace clippy and Rustdoc, validation tests at concurrency 16, the unchanged downstream repro, a forced 88,819-row audit completing in one invocation at jobs 16, failure retries, and a zero-read warm pass.
2026-08-22 02:16:13 +03:00
Anees Iqbal 8e95e84d0c Close specialization and descriptor audit gaps
Distinguish image descriptors from texel buffers, scope synthesized binding occupancy by descriptor set, and decouple the Metal texture source limit from configurable descriptor ranges. Centralize retry finalization and runtime sampler projection so layout and specialization contracts cannot drift across paths. Refresh consumer documentation and add adversarial descriptor tests.
2026-08-20 08:31:42 +03:00