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
2026-07-22 13:15:24 +03:00
2026-07-22 13:15:24 +03:00

metal2vulkan

License: LGPL-3.0-or-later

Alpha. The public API, CLI, reflection schema, and emitted SPIR-V may change during the 0.x series. The project is suitable for experimentation and integration pilots, but consumers should version their cached outputs and expect upgrades to require integration work.

metal2vulkan translates Metal AIR—LLVM bitcode or sanitized LLVM IR—into Vulkan 1.2 SPIR-V with a native Rust emitter and retained-SPIR-V passes.

What it provides

  • Vertex, post-tessellation vertex, fragment, compute-kernel, and generated passthrough interfaces
  • A Rust library and an in → out.spv command-line interface
  • Structurally selected construction with one final validation pass; unsupported inputs fail visibly instead of returning known-invalid SPIR-V
  • Consumer reflection for descriptors, stage interfaces, function constants, argument buffers, and conservative buffer byte footprints
  • An optional unpublished validation workspace for authored semantic cases, GPU evidence, and exact translator A/B

Requirements

  • Rust 1.87 or newer
  • llvm-dis when the input is AIR bitcode
  • spirv-val from SPIRV-Tools for product translation

Tool paths are found through the usual search path. Override an individual tool with METAL2VULKAN_LLVM_DIS, METAL2VULKAN_SPIRV_VAL, or the corresponding METAL2VULKAN_<TOOL> variable.

Install

# CLI without reflection JSON
cargo install metal2vulkan

# CLI with --emit-meta JSON support
cargo install metal2vulkan --features serde

For a library dependency:

[dependencies]
metal2vulkan = { version = "0.1", features = ["serde"] } # serde is optional

Quick start

The CLI auto-detects vertex, fragment, or kernel stage metadata by default:

metal2vulkan input.air output.spv
metal2vulkan input.air output.spv --emit-meta reflection.json

Use an explicit stage when the input does not carry stage metadata or when generating a passthrough vertex shader:

metal2vulkan input.ll output.spv --stage kernel
metal2vulkan input.ll output.spv --stage passthrough

--emit-meta requires a build with the serde feature and is unavailable for passthrough output, which has no Metal stage metadata. On success the CLI writes validated SPIR-V, prints PASS, and exits 0. On failure it prints FALLBACK, exits nonzero, and writes a reproducer under $TMPDIR/metal2vulkan-repros by default. Set METAL2VULKAN_REPRO_DIR to choose another location.

Fragment AIR that calls air.get_num_samples.i32 also needs the graphics pipeline's exact sample count because Vulkan has no equivalent shader-side query:

metal2vulkan fragment.air fragment.spv --raster-samples 4

Accepted values are 1, 2, 4, 8, 16, 32, and 64. Library callers set TransformOptions::raster_sample_count; translation fails visibly when the query is present and the value is unknown.

Metal dispatchThreads can make boundary workgroups smaller. Exact-thread kernels therefore expose specializable local sizes and a reflected KernelDispatch::plan: create a compute pipeline for each distinct region local_size, specializing KERNEL_LOCAL_SIZE_SPEC_IDS, then dispatch every region with its 48-byte logical-grid payload. This produces at most eight rectangular dispatches, with no surplus invocations and uniform workgroup barriers.

For a fixed grid, the CLI can instead bake the exact bounds into a pipeline variant:

metal2vulkan kernel.air kernel.spv --local 8,8,1 --threads-per-grid 57,9,1

--threads-per-grid-push-constant OFFSET moves the default dynamic dispatch payload. Library callers select an override with TransformOptions::kernel_dispatch; reflected translation returns the effective contract in ShaderReflection::kernel_dispatch. Callers that can prove every launch covers complete workgroups may explicitly select KernelDispatch::Workgroups or pass --whole-workgroups to retain a single fixed-local-size dispatch.

Library

Library translation takes caller-owned scratch space. Use a unique directory for concurrent calls and remove it when the operation finishes:

use metal2vulkan::passes::Stage;
use std::path::Path;

fn translate_kernel(sanitized_ll: &str, scratch: &Path) -> Result<Vec<u8>, String> {
    metal2vulkan::translate_sanitized_native(sanitized_ll, Stage::Kernel, scratch)
}

For a complete executable that auto-detects the stage, writes SPIR-V and reflection JSON, and cleans up its scratch directory on every return path:

cargo run --features serde --example translate_reflected -- \
  input.air output.spv reflection.json

Documentation

Document Start here when…
How to translate and integrate a shader You want an end-to-end CLI or Rust integration recipe
Shader reflection You need the complete reflection schema and binding contract
Architecture You are changing the emitter, retained module, passes, or retries
Validation playbook You are checking byte stability or authored semantic behavior
Contributing You need the repository layout and required development gates
Validation crate You are operating the unpublished corpus tooling
Changelog You need unreleased API and behavior changes

The generated Rust API documentation is available from cargo doc --all-features --open.

Coverage policy

Grammar and lowering behavior is locked with owned synthetic Rust tests. This repository does not ship third-party captured shaders. Optional private system-metallib harvest, authored manifests, and dependency-exact evidence stay in the validation workspace and are described in the validation playbook.

Passing spirv-val proves structural validity, not agreement with Metal or correct pixels. Use the authored validation ladder for semantic claims.

License

Licensed under the GNU Lesser General Public License v3.0 or later (LGPL-3.0-or-later).

Metal is a trademark of Apple Inc. metal2vulkan is an independent project and is not affiliated with, sponsored by, or endorsed by Apple Inc.

S
Description
No description provided
Readme
1.7 GiB
0 Stars 1 Watchers 0 Forks
Languages
Rust 61.3%
LLVM 31.7%
Metal 3%
Objective-C 2.2%
Python 1.2%
Other 0.5%