Expand macOS 26 AIR translation coverage
Overhaul the validation workflow around sharded authored cases, dependency-exact observations, incremental indexed corpus audits, bounded parallel translation, and native Metal/Vulkan comparison.\n\nExpand native AIR lowering, reflection, linked-function specialization, resource and stage-interface support, and structural CFG/pointer repair across the harvested macOS 26 corpus. Add exact intrinsic inventory, distributed 16x16x16 matrix lowering, explicit opaque tensor linkage, and regression coverage for the newly supported feature classes.\n\nThe final corpus verification accounts for all 88,819 indexed AIR modules under the current product fingerprint: 65,355 translate and validate directly, 23,464 require exact authored linkage, and zero fail or remain unresolved.
This commit is contained in:
1 parent
1b013834bc
commit
8b78eaca3b
353 files changed
+70288
-53288
No files matched your search
@@ -37,17 +37,14 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
sudo apt-get update
|
||||
# llvm: llvm-dis; spirv-tools: spirv-val, spirv-as, spirv-diff (needed by spirv_delta)
|
||||
# mesa-vulkan-drivers + libvulkan1: lavapipe software ICD so the Linux validation
|
||||
# executor can create a VkInstance on GPU-less GitHub runners. Without an ICD,
|
||||
# Instance::new fails with VK_ERROR_INCOMPATIBLE_DRIVER (not an apt-tool-age issue).
|
||||
sudo apt-get install -y llvm clang spirv-tools mesa-vulkan-drivers libvulkan1
|
||||
# llvm: llvm-dis; spirv-tools: spirv-val + the product passthrough path's spirv-as.
|
||||
# Keep lavapipe available for explicit
|
||||
# corpus-vulkan qualification on GPU-less Linux runners.
|
||||
sudo apt-get install -y llvm spirv-tools mesa-vulkan-drivers libvulkan1
|
||||
command -v llvm-dis
|
||||
command -v spirv-val
|
||||
command -v spirv-as
|
||||
command -v spirv-diff
|
||||
# Fail setup early if the loader has nothing to bind — otherwise the atomic-float
|
||||
# executor (and any other runner_linux test) panics mid-suite.
|
||||
# Fail setup early if an explicit corpus-vulkan run would have no ICD.
|
||||
shopt -s nullglob
|
||||
icds=(/usr/share/vulkan/icd.d/*.json /etc/vulkan/icd.d/*.json)
|
||||
echo "Vulkan ICDs: ${icds[*]:-none}"
|
||||
@@ -67,7 +64,6 @@ jobs:
|
||||
command -v llvm-dis
|
||||
command -v spirv-val
|
||||
command -v spirv-as
|
||||
command -v spirv-diff
|
||||
|
||||
- name: Format
|
||||
run: cargo fmt --all -- --check
|
||||
@@ -76,8 +72,40 @@ jobs:
|
||||
- name: Clippy (warnings denied)
|
||||
run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
|
||||
- name: Build public documentation (warnings denied)
|
||||
env:
|
||||
RUSTDOCFLAGS: -Dwarnings
|
||||
run: cargo doc --workspace --all-features --no-deps
|
||||
|
||||
- name: Test metal2vulkan
|
||||
run: cargo test -p metal2vulkan -- --test-threads=1
|
||||
|
||||
- name: Test validation suite
|
||||
run: cargo test -p metal2vulkan-validation -- --test-threads=1
|
||||
|
||||
# Machine-specific semantic qualification remains explicit. Linux CI has lavapipe, so it can
|
||||
# execute the owned public cases against their exact committed Metal observations without a
|
||||
# physical GPU. Rows written here are ephemeral CI evidence, not committed environment slots.
|
||||
- name: Qualify public cases on native Vulkan (Linux)
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cargo build -p metal2vulkan-validation --bins
|
||||
for case_id in \
|
||||
d9ce86618e0924966fbb1e7de63761ef471bb6e85b592a70193a26375ec0423f \
|
||||
4659fedddd1695fba79c3faa797ec3be647e3fd1a87ecec23bde55ccbfbcf656 \
|
||||
1e54315eb0ffcac633d4992c577f3e6ac384ed1bdf2321887c1f37242c00c887
|
||||
do
|
||||
target/debug/corpus-vulkan \
|
||||
--case-id "$case_id" \
|
||||
--metal-environment-id apple-m2-macos26.5.2 \
|
||||
--environment-id ubuntu-26.04-lavapipe
|
||||
done
|
||||
target/debug/corpus-index
|
||||
target/debug/corpus-index --check
|
||||
status=$(target/debug/corpus-status --limit 20)
|
||||
echo "$status"
|
||||
if grep -Eq 'vulkan=(missing|stale|failed)' <<<"$status"; then
|
||||
echo "native Vulkan qualification is incomplete" >&2
|
||||
exit 1
|
||||
fi
|
||||
+6
-5
@@ -16,12 +16,13 @@ validation/tests/fixtures/
|
||||
*.spv
|
||||
*.spvasm
|
||||
|
||||
# Optional private metallib corpus (mined data).
|
||||
# Committed under validation/corpus/: README.md + metal2vulkan-ledger.jsonl (translate hashes).
|
||||
# Execution goldens (metal/vulkan/moltenvk JSONL) may be committed for reproducibility:
|
||||
# hash-identified plans, deterministic digests, and output_b64 payloads; no AIR bodies.
|
||||
# Everything under local/ is user-supplied and must never be committed.
|
||||
# Optional private metallib corpus (mined data). Everything under local/ is user-supplied and must
|
||||
# never be committed. Authored cases and hash-identified observations outside local/ are canonical.
|
||||
validation/corpus/local/
|
||||
validation/corpus/.index.sqlite
|
||||
validation/corpus/.index.sqlite-*
|
||||
validation/corpus/.index.sqlite.*
|
||||
validation/corpus/.transactions/
|
||||
*.jsonl.tmp
|
||||
|
||||
# OS / editor
|
||||
|
||||
@@ -6,13 +6,12 @@ explicitly overrides a rule for the current task.
|
||||
## What this project is
|
||||
|
||||
**metal2vulkan** is a standalone Rust crate and CLI that translates **Metal AIR** (LLVM bitcode
|
||||
or sanitized `.ll`) to **Vulkan SPIR-V** with a native emitter (no LLVM `llc` in the product path).
|
||||
or sanitized `.ll`) to **Vulkan SPIR-V** with a native Rust emitter.
|
||||
|
||||
- **License:** LGPL-3.0-or-later (`LICENSE`)
|
||||
- **Publishable crate:** `metal2vulkan` (library + `metal2vulkan` binary)
|
||||
- **Optional workspace member:** `validation/` (`metal2vulkan-validation`, `publish = false`) —
|
||||
Metal oracle / Vulkan executor helpers and offline tools such as `spirv_delta` (uses `rspirv`
|
||||
there only; the product crate does **not** depend on `rspirv`)
|
||||
- **Unpublished workspace member:** `validation/` (`metal2vulkan-validation`, `publish = false`) —
|
||||
authored semantic cases, dependency-exact observations, deterministic harvest, and GPU-free A/B
|
||||
|
||||
This tree is **not** the paravirtual GPU monorepo. Do not reintroduce monorepo paths (`host/`,
|
||||
`vm/`, `kb/`, `journal/`), device/protocol code, or private capture corpora.
|
||||
@@ -22,6 +21,7 @@ This tree is **not** the paravirtual GPU monorepo. Do not reintroduce monorepo p
|
||||
| Doc | Role |
|
||||
|---|---|
|
||||
| `README.md` | Install, CLI, quick library use |
|
||||
| `docs/HOWTO.md` | End-to-end translation and consumer integration |
|
||||
| `docs/ARCHITECTURE.md` | Pipeline, structurizer/relooper, retry cascade |
|
||||
| `docs/REFLECTION.md` | Consumer binding metadata (`ShaderReflection`) |
|
||||
| `docs/VALIDATION.md` | Developer validation ladder (harvest, drift, A/B) |
|
||||
@@ -35,10 +35,10 @@ This tree is **not** the paravirtual GPU monorepo. Do not reintroduce monorepo p
|
||||
| `src/` | Product library + CLI (`translate*`, native emitter, passes, reflect) |
|
||||
| `tests/` | Integration tests for the product crate |
|
||||
| `examples/` | Small runnable examples |
|
||||
| `validation/` | Optional oracle/executor tooling (not published to crates.io) |
|
||||
| `validation/` | Authored-case validation tooling (not published to crates.io) |
|
||||
| `docs/` | Architecture and consumer guides |
|
||||
| `scripts/` | Dev utilities (`mtlb-extract`, harvest, A/B, drift, SPIR-V grammar regen) |
|
||||
| `.github/workflows/ci.yml` | Format, clippy `-D warnings`, serial tests on `ubuntu-26.04` + `macos-26` |
|
||||
| `scripts/` | Dev utilities (`mtlb-extract`, SPIR-V grammar regeneration) |
|
||||
| `.github/workflows/ci.yml` | Format, warnings-denied clippy/Rustdoc, and serial tests on `ubuntu-26.04` + `macos-26`; public Vulkan qualification on Linux |
|
||||
|
||||
Crown-jewel code lives under `src/native/`, `src/passes/`, and `src/reflect/`. Prefer structural
|
||||
fixes over one-off workarounds.
|
||||
@@ -77,10 +77,95 @@ fixes over one-off workarounds.
|
||||
- When fixing a bug class, add or update a **test** (or a clear measurable check) so it cannot
|
||||
regress silently.
|
||||
|
||||
### Validation coverage is a closed contract
|
||||
|
||||
- **Chase closure, not a better-looking queue.** The authoring-capability census covers every
|
||||
indexed AIR identity, including identities that already have authored cases. A fresh complete
|
||||
census is closed only when `classified == total`, `remaining == 0`, and `unresolved == 0`.
|
||||
Reviews, annotations, allowlists, previous observations, or a smaller selection do not resolve a
|
||||
tooling gap. A newly observed requirement is work to model honestly, not a row to suppress.
|
||||
- **One typed capability vocabulary owns the truth.** `ToolingRequirement` and the shared
|
||||
structural checks in `validation/src/executor_contract.rs` are the contract among classification,
|
||||
the case checker, both Metal and Vulkan executors, persisted facts, and reporting. Do not grow
|
||||
parallel string lists or component-local support tables. Adding support for a structure means
|
||||
updating the literal schema, validation, both applicable execution paths, classification, and
|
||||
regression tests together; if one side cannot execute it exactly, it remains an unsupported
|
||||
requirement.
|
||||
- **Describe supported families independently from missing tooling.** A focused `AuditTarget`
|
||||
selects current typed structural facts, not rows carrying an unsupported requirement. Fixing a
|
||||
capability must not make its regression audit select zero rows. Keep descriptive facts and
|
||||
blocking requirements separate even when they initially identify the same corpus family.
|
||||
- **Prefer architectural fit over policy patches.** Put shared semantics at the narrowest common
|
||||
boundary and delete superseded blocker fields, adapters, commands, and duplicated mappings.
|
||||
Never post-filter a stale classifier result, special-case a hash/name, or add a review policy to
|
||||
make incompatible components appear consistent.
|
||||
- **The disposable index is the acceleration structure, not another corpus.** It owns compact
|
||||
identities, exact source byte locations, dependency hashes, and versioned structural facts.
|
||||
Ordinary refresh and lookup paths must inspect only new/changed shards or directly selected byte
|
||||
ranges. Once warm, a no-change capability audit should select no rows and open/read zero source
|
||||
shards; exact-row and focused audits must not scan unrelated shards.
|
||||
- **Cache validity follows semantics.** Analyzer, executor, oracle, product, and dependency
|
||||
fingerprints must include every behavior that can change classification, translation, or
|
||||
expected output. Bump the appropriate version when that behavior changes and recompute through
|
||||
the normal indexed path. Do not trust cached validation produced by different semantics, and do
|
||||
not rebuild or rescan source data merely to invalidate derived facts.
|
||||
- **Tests own their inputs.** Index, cache, and audit tests must build isolated synthetic shards and
|
||||
observations. They may not depend on the developer's ambient private corpus, pre-existing index,
|
||||
filesystem ordering, or cache warmth.
|
||||
- **Use the right proof for the claim.** After capability/classifier changes, run a full fresh
|
||||
`authoring-capabilities --reclassify-all` census and then a warm pass that proves zero source
|
||||
reads. After feature-specific changes, run the corresponding focused audit across its complete
|
||||
selected family in bounded, resumable batches. After product translation changes, run a fresh
|
||||
translation fingerprint sweep when the local corpus is available. Corpus-wide claims require
|
||||
corpus-wide results; otherwise state the measured subset.
|
||||
- **Authored evidence is execution, not bookkeeping.** Qualify an authored case freshly on Metal,
|
||||
then execute the Vulkan candidate and compare the declared observations. Existing observation
|
||||
files, successful SPIR-V validation, or an authored manifest alone are not semantic proof.
|
||||
- **`authored_linkage_required` is narrow and structural.** Use it only when exact AIR structure
|
||||
establishes that translation needs explicit authored linked inputs which a standalone harvested
|
||||
row cannot supply. Timeouts, resource-limit breaches, malformed input, unsupported lowering, and
|
||||
ordinary translator errors remain failures; never relabel them to complete a census.
|
||||
|
||||
### Translation performance is a correctness contract
|
||||
|
||||
- **30 seconds is a hard end-to-end ceiling per translation attempt.** Measure from handing the
|
||||
selected AIR input to an isolated worker through translation, SPIR-V validation, and reporting
|
||||
the result. Success or an honest unsupported-input `FALLBACK` must arrive within the ceiling;
|
||||
exceeding it, timing out, or killing a stuck worker is a failing result that must be diagnosed
|
||||
and fixed before the affected work is done. A timeout is a safety rail, not an acceptable way
|
||||
to classify supported input. Do not meet the ceiling by skipping required validation, reducing
|
||||
semantic coverage, or converting an input that was supported before into a premature fallback.
|
||||
- **512 MiB is the hard memory budget per translation attempt.** Enforce it at the worker
|
||||
boundary, covering peak translation-attributable live allocations and resident growth. Kill
|
||||
the complete worker process group on a time or memory breach and clean up its scratch files.
|
||||
Do not raise either budget without explicit user approval.
|
||||
- **Keep total resource use bounded.** Parallelize only independent rows or phases, cap worker and
|
||||
queue counts, and account for the aggregate worst case (`workers * 512 MiB`). No optimization
|
||||
may introduce unbounded threads, processes, queues, caches, retained IR, or candidate modules.
|
||||
- **Remove work instead of hiding it.** Prefer shard-local incremental indexing, parsing only the
|
||||
selected or changed source, caching immutable analysis, reusing still-valid CFG facts, skipping
|
||||
equivalent retry states, and releasing failed candidates promptly. Never reuse analysis across
|
||||
a semantics-affecting rewrite unless its validity is structurally guaranteed.
|
||||
- **Warm indexes must prevent corpus-wide revisits.** Refresh only new or changed sources; an
|
||||
exact-row translation should read its hash-derived shard, not scan unrelated shards. If a
|
||||
compatibility migration needs a broader scan, make it explicit, resumable, one-time, and
|
||||
measured rather than silently placing it on the translation path.
|
||||
- **Performance changes require release-mode evidence.** When touching translation, retry,
|
||||
planner, indexing, or validation hot paths, measure the end-to-end wall time and peak memory for
|
||||
the largest relevant locally available row plus a bounded representative batch. Report the
|
||||
slowest row and the scope measured. Debug-build timing does not verify the ceiling.
|
||||
- When a slow or memory-heavy failure class is found, add a deterministic regression check for
|
||||
the underlying redundant-work or boundedness property. Avoid machine-fragile microbenchmarks;
|
||||
keep the 30-second and 512-MiB worker guards as hard integration backstops.
|
||||
- **Do not normalize known breaches.** An observed over-budget translation is an active correctness
|
||||
bug, not acceptable technical debt or a reason to weaken the workload. Profile where its time
|
||||
and memory go, remove redundant or global work structurally, and remeasure the same input under
|
||||
the same release-mode boundary before claiming the regression fixed.
|
||||
|
||||
### Tooling and temp files
|
||||
|
||||
- External tools on some paths: **`llvm-dis`**, **`spirv-val`**, and for validation **`spirv-diff`**
|
||||
/ **`spirv-as`**. Resolve via PATH or `METAL2VULKAN_<TOOL>` overrides.
|
||||
- External tools: **`llvm-dis`** for AIR bitcode input, **`spirv-val`** for product validation, and
|
||||
**`spirv-as`** for passthrough generation. Resolve via PATH or `METAL2VULKAN_<TOOL>` overrides.
|
||||
- Scratch files under the OS temp dir (or a caller-supplied `tmp`) must be **removed as soon as
|
||||
the tool no longer needs them**. The CLI removes its work directory on success and before
|
||||
`process::exit` on FALLBACK. Do not reintroduce long-lived dumps under fixed `/tmp/...` paths.
|
||||
@@ -95,21 +180,19 @@ fixes over one-off workarounds.
|
||||
- `target/`, `Cargo.lock` (gitignored for this library-first tree), `.cache/`
|
||||
- Name-keyed special cases “just to pass one case”
|
||||
|
||||
**Allowed (committed):** synthetic fixtures under `validation/fixtures/public/`;
|
||||
`validation/corpus/metal2vulkan-ledger.jsonl` (AIR + SPIR-V translate hashes only — **no**
|
||||
shader bodies). Execution ledgers (`metal2vulkan-ledger-{metal,vulkan,moltenvk}.jsonl`) may be
|
||||
committed for reproducibility: they store hash-identified plans, deterministic input/output
|
||||
digests, and `output_b64` payloads, but never AIR source bodies.
|
||||
**Allowed (committed):** synthetic fixtures under `validation/fixtures/public/`, authored case
|
||||
shards under `validation/corpus/cases/`, and dependency-exact observation shards under
|
||||
`validation/corpus/observations/`. None may contain AIR source bodies.
|
||||
|
||||
## Layout & ownership
|
||||
|
||||
- **Product logic** stays in the `metal2vulkan` crate (`src/`).
|
||||
- **Optional offline/oracle work** stays in `validation/` (may depend on `rspirv`, MoltenVK, a
|
||||
Vulkan ICD). Do not pull that into the published crate’s default dependency graph.
|
||||
- **Optional offline/oracle work** stays in `validation/` (may depend on MoltenVK or a Vulkan ICD).
|
||||
Do not pull that into the published crate’s default dependency graph.
|
||||
- **Grammar tables** under `src/spirv_binary/*_generated.rs` are regenerated via
|
||||
`scripts/regen-spirv-grammar/` from Khronos SPIRV-Headers + rspirv-autogen; do not hand-edit.
|
||||
- **Reflection** for consumers: `src/reflect/` + `docs/REFLECTION.md`. Binding numbers must stay
|
||||
aligned with the interface pass ABI (set 0; bases 0 / 32 / 64 / 96).
|
||||
aligned with the interface pass ABI (set 0; bases 0 / 32 / 64 / 96 / 128 / 160).
|
||||
|
||||
## Build, test, CI
|
||||
|
||||
@@ -118,6 +201,7 @@ Always run Rust tests **serially**:
|
||||
```sh
|
||||
cargo fmt --all
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
RUSTDOCFLAGS='-D warnings' cargo doc --workspace --all-features --no-deps
|
||||
cargo test -p metal2vulkan -- --test-threads=1
|
||||
cargo test -p metal2vulkan-validation -- --test-threads=1
|
||||
```
|
||||
@@ -147,8 +231,9 @@ When diagnosing a hang, prefer reading full `cargo test` output over piping thro
|
||||
## Git workflow
|
||||
|
||||
- Prefer **focused commits** with a clear subject and body (what / why / how verified).
|
||||
- **Pre-commit gate (Rust):** `cargo fmt --all`, then clippy with `-D warnings` as above. Do not
|
||||
commit unformatted code or known clippy/rustc warnings; CI will fail the same checks.
|
||||
- **Pre-commit gate (Rust):** `cargo fmt --all`, clippy with `-D warnings`, and warnings-denied
|
||||
all-features Rustdoc as above. Do not commit unformatted code or known clippy/rustc/Rustdoc
|
||||
warnings; CI will fail the same checks.
|
||||
- Do not force-push shared history unless the user asks.
|
||||
- Do not commit secrets, large binaries, or lockfiles that this repo intentionally ignores.
|
||||
|
||||
@@ -158,10 +243,13 @@ When diagnosing a hang, prefer reading full `cargo test` output over piping thro
|
||||
2. **Validate** — read the relevant code and `docs/`; do not assume monorepo facts.
|
||||
3. **Change** — implement; keep product paths free of env gates and name keys.
|
||||
4. **Test** — serial `cargo test` for the packages you touched; full workspace clippy with
|
||||
`-D warnings` when Rust sources changed.
|
||||
`-D warnings` when Rust sources changed; warnings-denied all-features Rustdoc when public APIs or
|
||||
documentation changed.
|
||||
5. **Document** — update `docs/` or comments only when the durable contract changed.
|
||||
6. **Commit** — `cargo fmt --all` first, then one concern per commit when practical. Only commit
|
||||
when fmt and clippy are clean.
|
||||
when fmt, clippy, and applicable Rustdoc checks are clean.
|
||||
|
||||
**Done** = it works under the checks above, claims match evidence, fmt/clippy are green, and the
|
||||
tree stays publishable as a general AIR→SPIR-V translator.
|
||||
**Done** = it works under the checks above, claims match evidence, fmt/clippy/Rustdoc are green,
|
||||
measured translations in the touched scope stay within 30 seconds and 512 MiB, relevant capability
|
||||
audits remain closed without stale evidence or unrelated source reads, and the tree stays
|
||||
publishable as a general AIR→SPIR-V translator.
|
||||
+63
-6
@@ -12,18 +12,39 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
- Public `specialize_function_constants_zero` helper for baking discovered Metal function
|
||||
constants to their zero/default values, including branch pruning and removal of now-dead entry
|
||||
interface globals.
|
||||
- Reflection schema v3: AIR `constexpr sampler` globals are reported as `StaticSampler` bindings
|
||||
with decoded sampler state. Texture bindings also expose declared access through
|
||||
`ResourceBinding::access` where the AIR metadata carries it.
|
||||
- Public byte-exact function-constant specialization, reflection-only AIR inspection, authored
|
||||
linked-function/table specialization, and vertex-observer generation APIs.
|
||||
- Reflection schema v21: consumer metadata now covers decoded static samplers, texture shape and
|
||||
access, argument-buffer resources, kernel stage inputs, tessellation, imageblocks, exact function-
|
||||
constant ABI types, buffer extent/access classification, and conservative final-module static and
|
||||
invocation-strided buffer footprints.
|
||||
- A task-oriented translation and reflection integration guide plus a compiled serde reflection
|
||||
example.
|
||||
- Additional stage-interface support for fragment `[[point_coord]]`, `[[primitive_id]]`, and
|
||||
`[[sample_id]]`, flat varyings, framebuffer-fetch color inputs, vertex builtins, and fragment
|
||||
outputs with nonzero render-target locations.
|
||||
- Broader native translation support for texture arrays, storage-image arrays, texture
|
||||
gather/sample/read/write variants, half/integer render-target formats, scalar 64-bit integer
|
||||
arithmetic, and Workgroup memory patterns used by shared-memory reductions.
|
||||
- Native lowering and reflection for linked functions, tessellation patch inputs, ray/intersection
|
||||
queries and result fields, argument-buffer resources, and implicit, custom, and direct-layout
|
||||
imageblocks.
|
||||
- Native distributed `simdgroup_matrix` 16x16x16 multiply-accumulate lowering for the observed
|
||||
f32, f16, bf16, float8, and signed/unsigned i8 AIR element combinations, including dynamic
|
||||
transpose operands and 32-lane tile ownership.
|
||||
- Authored validation contracts and executable Metal/Vulkan cases for tessellation, depth/stencil
|
||||
attachments, framebuffer fetch, multisample and buffer textures, narrow vertex attributes,
|
||||
vertex side effects, function constants, argument buffers, imageblocks, and ray intersections.
|
||||
- A sharded validation workflow with dependency-exact observations, an incremental SQLite source
|
||||
index, focused hash/shard selection, explicit full reclassification, capability audits, native
|
||||
Metal and Vulkan/MoltenVK A/B execution, and optional OpenRouter-authored case proposals.
|
||||
|
||||
### Changed
|
||||
|
||||
- Native emitter wrapper APIs under `tools` now use `emit_vulkan_spirv*` names that match their
|
||||
implementation.
|
||||
- The CLI accepts `--raster-samples` for AIR sample-count queries and derives a default `.vk.spv`
|
||||
output path when the output argument is omitted.
|
||||
- Floating-point lowering is closer to AIR for the covered cases, including f32-to-f16 clamping,
|
||||
bf16 narrowing and NaN handling, fast `sin`/`cos`, `pow` zero edges, and exact `mix` endpoints.
|
||||
- Buffer, pointer, control-flow, and access-chain lowering handles more structural cases, reducing
|
||||
@@ -31,7 +52,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
copies, raw subword loads/stores, and local pointer tables.
|
||||
- Structured control-flow retries are bounded more tightly, improving behavior on large shaders and
|
||||
avoiding unnecessary fallback to slower emission paths.
|
||||
- Reflection documentation now describes the schema v3 descriptor contract.
|
||||
- Corpus translation and classification use bounded parallel workers, a 30-second per-item
|
||||
watchdog, a 512 MiB per-item memory ceiling, size-aware scheduling, and incremental index/cache
|
||||
reuse. Warm audits avoid reopening unchanged source shards; forced audits remain explicit.
|
||||
- Validation capability checks, authored schema validation, backend execution gates, and cache
|
||||
identities now share one typed contract so a clean audit cannot hide a later executor rejection.
|
||||
- Corpus capability audits now use the product's canonical AIR-call inventory and report every
|
||||
called intrinsic outside a recognized lowering or static-linkage family, including exact symbols
|
||||
and counts, instead of interpreting an unrelated clean authoring contract as complete support.
|
||||
- Full AIR-intrinsic reclassification now updates every cached source in bounded keyset batches,
|
||||
independent of `--limit`, without reopening source shards; matrix capability recognition and
|
||||
lowering share one exact ABI parser.
|
||||
- Reflection documentation now describes the complete schema v21 descriptor, argument-buffer,
|
||||
stage-interface, and conservative buffer-staging contracts.
|
||||
|
||||
### Removed
|
||||
|
||||
- Retired the monolithic validation ledgers and superseded mint/remint/run/why utilities in favor of
|
||||
sharded authored cases, dependency-exact observations, the source index, and unified corpus
|
||||
commands.
|
||||
- Removed obsolete emitter naming and compatibility terminology; the product and tooling describe
|
||||
only the native AIR-to-SPIR-V pipeline.
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -64,13 +105,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
- Fixed fragment `[[sample_id]]` lowering to use `BuiltIn SampleId` with the required
|
||||
`SampleRateShading` capability, and lowered AIR `texture2d_ms` reads to MS `OpTypeImage` fetches
|
||||
with a `Sample` operand instead of treating the sample id as a mip LOD.
|
||||
- Corrected native lowering for tessellation patch inputs; ray-intersection result typing and
|
||||
setters; custom, direct, narrow, and integer imageblocks; embedded texture arrays; array gather
|
||||
operands; array depth comparison sampling; and integer storage-image atomics.
|
||||
- Corrected Metal SIMD/quad operations for vector `u16` prefix scans, integer extrema, active
|
||||
masks, and exact votes, and preserved signedness for same-width integer conversions and atomic
|
||||
subtraction.
|
||||
- Repaired additional raw byte/word buffer, opaque-pointer, aggregate-pointee, record-layout,
|
||||
cross-storage select, and late pointer-typing cases without name-keyed workload exceptions.
|
||||
- Reduced worst-case translation time and memory growth by caching retry verdicts, pruning dead CFG
|
||||
before source re-emission, using linear CFG ordering and candidate scans, bounding generated CFG
|
||||
growth, and applying resource limits from worker startup.
|
||||
- Validation now uploads sampled 3D images through bounded transfer buffers instead of relying on
|
||||
non-portable linear-tiling 3D images, restoring exact issue-4 and issue-5 Metal/MoltenVK checks.
|
||||
- Opaque private-tensor descriptor intrinsics now have an explicit exact static-linkage contract,
|
||||
keeping their Apple-defined layout paired with the externally defined tensor-operation helper
|
||||
that consumes it instead of inventing a partial native representation.
|
||||
|
||||
## v0.1.0
|
||||
|
||||
### Added
|
||||
|
||||
- First public release of the `metal2vulkan` crate and CLI: native Metal AIR / sanitized
|
||||
LLVM IR → Vulkan SPIR-V (no LLVM `llc` on the product path).
|
||||
- First public release of the `metal2vulkan` crate and CLI: native Metal AIR / sanitized LLVM IR →
|
||||
Vulkan SPIR-V.
|
||||
- Library entry points for stage-aware translate, optional reflection metadata, and
|
||||
function-constant specialization.
|
||||
- CLI: `metal2vulkan <in.air|.ll> <out.spv> --stage …`, optional `--emit-meta` JSON with the
|
||||
|
||||
+23
-25
@@ -9,11 +9,7 @@ standalone crate.
|
||||
- External tools used by some paths:
|
||||
- `llvm-dis` (LLVM)
|
||||
- `spirv-val` (SPIRV-Tools)
|
||||
- `spirv-diff` / `spirv-as` (validation suite / some tools)
|
||||
- Optional but required for Linux executor tests (e.g.
|
||||
`shader_shared_f32_atomic_add_executes_known_result`): a Vulkan ICD. On headless Linux that
|
||||
means `mesa-vulkan-drivers` (lavapipe) + `libvulkan1`. Without an ICD, `Instance::new` fails
|
||||
with `VK_ERROR_INCOMPATIBLE_DRIVER`. On macOS, MoltenVK for the same path.
|
||||
- A Vulkan ICD or Metal-capable macOS host only for explicit machine-specific authored-case runs
|
||||
|
||||
## Repository layout
|
||||
|
||||
@@ -22,8 +18,8 @@ standalone crate.
|
||||
├── src/ # library + CLI
|
||||
├── tests/ # integration tests
|
||||
├── examples/ # cargo examples
|
||||
├── validation/ # optional oracle / Vulkan helpers (workspace, not published)
|
||||
├── docs/ # architecture + reflection notes
|
||||
├── validation/ # authored-case validation tools (workspace, not published)
|
||||
├── docs/ # integration, architecture, reflection, and validation guides
|
||||
├── scripts/ # developer utilities
|
||||
├── Cargo.toml # workspace root + metal2vulkan package
|
||||
├── LICENSE # LGPL-3.0-or-later
|
||||
@@ -35,9 +31,9 @@ standalone crate.
|
||||
| `src/` | Library + CLI (`metal2vulkan`) |
|
||||
| `tests/` | Integration tests |
|
||||
| `examples/` | Small runnable examples |
|
||||
| `validation/` | Optional oracle / Vulkan helpers (not published) |
|
||||
| `docs/` | Design notes (`ARCHITECTURE.md`, `REFLECTION.md`) |
|
||||
| `scripts/` | Developer utilities (A/B harness, mtlb-extract, grammar regen, …) |
|
||||
| `validation/` | Authored cases, exact evidence, harvest, and A/B tools (not published) |
|
||||
| `docs/` | User integration and developer guides (`HOWTO.md`, architecture, reflection, validation) |
|
||||
| `scripts/` | Developer utilities (mtlb extraction, harvest helpers, grammar regen, …) |
|
||||
|
||||
## Development
|
||||
|
||||
@@ -48,6 +44,9 @@ cargo fmt --all
|
||||
# clippy (CI denies warnings)
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
|
||||
# public Rustdoc, including feature-gated APIs (CI denies warnings)
|
||||
RUSTDOCFLAGS='-D warnings' cargo doc --workspace --all-features --no-deps
|
||||
|
||||
# unit + integration tests (serial)
|
||||
cargo test -p metal2vulkan -- --test-threads=1
|
||||
|
||||
@@ -61,7 +60,7 @@ External tools used by some paths: `llvm-dis`, `spirv-val` (and friends). On mac
|
||||
PATH=/opt/homebrew/opt/llvm/bin:$PATH cargo test -p metal2vulkan -- --test-threads=1
|
||||
```
|
||||
|
||||
Byte-level A/B of two translator binaries: [`scripts/metal2vulkan-ab/`](scripts/metal2vulkan-ab/).
|
||||
GPU-free byte A/B is provided by `corpus-ab` in the validation crate.
|
||||
|
||||
## Build
|
||||
|
||||
@@ -79,17 +78,16 @@ cargo build --release --features serde
|
||||
fine; prefer structural tests when possible.
|
||||
3. **No third-party captured shaders in tree.** Reduce regressions to synthetic `.ll` tests.
|
||||
Optional **private** harvest writes gitignored shard JSONL under
|
||||
`validation/corpus/local/shards/` — see
|
||||
[`validation/corpus/README.md`](validation/corpus/README.md). Translate ledgers store hashes;
|
||||
execution ledgers may also store deterministic input/output digests and output payloads for
|
||||
reproducibility, but never AIR source bodies.
|
||||
`validation/corpus/local/sources/` — see
|
||||
[`validation/corpus/README.md`](validation/corpus/README.md). Committed authored manifests and
|
||||
hash-identified observations never contain AIR source bodies.
|
||||
4. **Honest FALLBACK.** Unsupported inputs must return `Err` / CLI `FALLBACK`, never emit
|
||||
wrong-but-valid SPIR-V.
|
||||
|
||||
### Validation while refactoring
|
||||
|
||||
The full developer workflow (synthetic tests → binary A/B → hash ledger → private system
|
||||
harvest → optional oracle) is in **[`docs/VALIDATION.md`](docs/VALIDATION.md)**.
|
||||
The full developer workflow (synthetic tests → exact binary A/B → authored cases → optional GPU
|
||||
evidence) is in **[`docs/VALIDATION.md`](docs/VALIDATION.md)**.
|
||||
|
||||
Quick anchors:
|
||||
|
||||
@@ -100,14 +98,13 @@ cargo test -p metal2vulkan -- --test-threads=1
|
||||
# before/after a byte-stable refactor
|
||||
cp target/release/metal2vulkan ./m2v-old
|
||||
# … edit …
|
||||
scripts/metal2vulkan-ab/metal2vulkan-ab.sh --old ./m2v-old
|
||||
# optional: translate ledger + execution goldens (see validation/README.md, plan.md)
|
||||
# cargo run -p metal2vulkan-validation --release --bin corpus-mint
|
||||
# cargo run -p metal2vulkan-validation --release --bin corpus-remint -- --failed-only
|
||||
# cargo run -p metal2vulkan-validation --release --bin corpus-why -- <air_sha256>
|
||||
# cargo run -p metal2vulkan-validation --release --bin corpus-run-metal # macOS
|
||||
# cargo run -p metal2vulkan-validation --release --bin corpus-run-vulkan # Linux
|
||||
# cargo run -p metal2vulkan-validation --release --bin corpus-run-moltenvk
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-ab -- \
|
||||
--old ./m2v-old --new target/release/metal2vulkan --canary --expect-no-change
|
||||
|
||||
# inspect the bounded authoring/evidence queue
|
||||
cargo run -p metal2vulkan-validation --bin corpus-index
|
||||
cargo run -p metal2vulkan-validation --bin corpus-next -- --limit 1
|
||||
cargo run -p metal2vulkan-validation --bin corpus-status
|
||||
|
||||
# optional private real-AIR bank (macOS; shard JSONL is gitignored)
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-harvest
|
||||
@@ -121,4 +118,5 @@ See also [AGENTS.md](AGENTS.md) for the full agent operating guide.
|
||||
- Include tests for new behavior or bug fixes
|
||||
- Update `docs/ARCHITECTURE.md` when the pipeline shape changes
|
||||
- Update `docs/REFLECTION.md` when the consumer binding contract changes
|
||||
- Update `docs/HOWTO.md` when the recommended CLI or library integration changes
|
||||
- Update `CHANGELOG.md` under `[Unreleased]`
|
||||
@@ -41,6 +41,11 @@ name = "metal2vulkan"
|
||||
path = "src/main.rs"
|
||||
required-features = []
|
||||
|
||||
[[example]]
|
||||
name = "translate_reflected"
|
||||
path = "examples/translate_reflected.rs"
|
||||
required-features = ["serde"]
|
||||
|
||||
[lib]
|
||||
name = "metal2vulkan"
|
||||
path = "src/lib.rs"
|
||||
|
||||
@@ -2,79 +2,129 @@
|
||||
|
||||
[](LICENSE)
|
||||
|
||||
> **Alpha.** This project is early and under active development. The public API, CLI flags,
|
||||
> reflection layout details, and SPIR-V output may change without a stable semver guarantee
|
||||
> while the crate is in the `0.x` series. Treat it as research-quality: useful for
|
||||
> experimentation and integration pilots, not a frozen interface.
|
||||
> **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.
|
||||
|
||||
Translate **Metal AIR** (LLVM bitcode / sanitized `.ll`) to **Vulkan SPIR-V** using a native Rust
|
||||
emitter. Production translation does not invoke LLVM `llc`.
|
||||
`metal2vulkan` translates **Metal AIR**—LLVM bitcode or sanitized LLVM IR—into Vulkan 1.3 SPIR-V
|
||||
with a native Rust emitter and retained-SPIR-V passes.
|
||||
|
||||
## Features
|
||||
## What it provides
|
||||
|
||||
- Native AIR/LLVM-IR → `OpCapability Shader` / Logical GLSL450 SPIR-V
|
||||
- Stage interface lowering for vertex, fragment, compute (kernel), and passthrough
|
||||
- Library API plus a CLI compatible with simple `in → out.spv` harnesses
|
||||
- Optional `serde` feature for reflection metadata JSON
|
||||
- Optional workspace package for local Metal oracle / Vulkan executor experiments
|
||||
- Vertex, post-tessellation vertex, fragment, compute-kernel, and generated passthrough interfaces
|
||||
- A Rust library and an `in → out.spv` command-line interface
|
||||
- Validation-gated retry tiers: 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
|
||||
|
||||
```sh
|
||||
# CLI
|
||||
# CLI without reflection JSON
|
||||
cargo install metal2vulkan
|
||||
|
||||
# Library (Cargo.toml)
|
||||
metal2vulkan = "0.1"
|
||||
# CLI with --emit-meta JSON support
|
||||
cargo install metal2vulkan --features serde
|
||||
```
|
||||
|
||||
## CLI
|
||||
For a library dependency:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
metal2vulkan = { version = "0.1", features = ["serde"] } # serde is optional
|
||||
```
|
||||
|
||||
## Quick start
|
||||
|
||||
The CLI auto-detects vertex, fragment, or kernel stage metadata by default:
|
||||
|
||||
```sh
|
||||
metal2vulkan <in.air|.ll> <out.spv> --stage vertex|fragment|passthrough|kernel
|
||||
# optional interface metadata JSON (requires --features serde)
|
||||
metal2vulkan in.ll out.spv --stage kernel --emit-meta out.json
|
||||
metal2vulkan input.air output.spv
|
||||
metal2vulkan input.air output.spv --emit-meta reflection.json
|
||||
```
|
||||
|
||||
- Success: prints a line containing `PASS`, writes SPIR-V, exits `0`
|
||||
- Failure: prints `FALLBACK`, exits non-zero
|
||||
|
||||
On failure the CLI writes a repro bundle under `$TMPDIR/metal2vulkan-repros` (override with
|
||||
`METAL2VULKAN_REPRO_DIR`).
|
||||
|
||||
### Example
|
||||
Use an explicit stage when the input does not carry stage metadata or when generating a passthrough
|
||||
vertex shader:
|
||||
|
||||
```sh
|
||||
cargo run --example translate_native -- path/to/shader.ll kernel out.spv
|
||||
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:
|
||||
|
||||
```sh
|
||||
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.
|
||||
|
||||
## Library
|
||||
|
||||
Library translation takes caller-owned scratch space. Use a unique directory for concurrent calls
|
||||
and remove it when the operation finishes:
|
||||
|
||||
```rust
|
||||
use metal2vulkan::passes::Stage;
|
||||
use std::path::Path;
|
||||
|
||||
fn translate_ll(sanitized_ll: &str) -> Result<Vec<u8>, String> {
|
||||
let tmp = std::env::temp_dir().join("m2v-scratch");
|
||||
std::fs::create_dir_all(&tmp).ok();
|
||||
metal2vulkan::translate_sanitized_native(sanitized_ll, Stage::Kernel, Path::new(&tmp))
|
||||
fn translate_kernel(sanitized_ll: &str, scratch: &Path) -> Result<Vec<u8>, String> {
|
||||
metal2vulkan::translate_sanitized_native(sanitized_ll, Stage::Kernel, scratch)
|
||||
}
|
||||
```
|
||||
|
||||
See crate docs (`cargo doc --open`), [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) for the
|
||||
pipeline, and [`docs/REFLECTION.md`](docs/REFLECTION.md) for how consumers read binding metadata
|
||||
after a convert. Repository layout and the developer loop are in
|
||||
[CONTRIBUTING.md](CONTRIBUTING.md). How to stay confident while refactoring (harvest, hash ledgers,
|
||||
A/B) is in [`docs/VALIDATION.md`](docs/VALIDATION.md).
|
||||
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:
|
||||
|
||||
```sh
|
||||
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](docs/HOWTO.md) | You want an end-to-end CLI or Rust integration recipe |
|
||||
| [Shader reflection](docs/REFLECTION.md) | You need the complete reflection schema and binding contract |
|
||||
| [Architecture](docs/ARCHITECTURE.md) | You are changing the emitter, retained module, passes, or retries |
|
||||
| [Validation playbook](docs/VALIDATION.md) | You are checking byte stability or authored semantic behavior |
|
||||
| [Contributing](CONTRIBUTING.md) | You need the repository layout and required development gates |
|
||||
| [Validation crate](validation/README.md) | You are operating the unpublished corpus tooling |
|
||||
| [Changelog](CHANGELOG.md) | 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 **synthetic** Rust tests. This repository does not
|
||||
ship third-party captured shaders. Prefer reduced `.ll` fixtures that name structural properties.
|
||||
Optional private system-metallib harvest and hash-only drift pins are documented in
|
||||
[`docs/VALIDATION.md`](docs/VALIDATION.md).
|
||||
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](docs/VALIDATION.md).
|
||||
|
||||
`spirv-val` coverage is not the same as correct end-to-end pixels.
|
||||
Passing `spirv-val` proves structural validity, not agreement with Metal or correct pixels. Use the
|
||||
authored validation ladder for semantic claims.
|
||||
|
||||
## License
|
||||
|
||||
|
||||
+28
-19
@@ -6,16 +6,15 @@ public tree is the unit/integration suite plus optional local A/B and oracle too
|
||||
|
||||
## The pipeline
|
||||
|
||||
Unlike the legacy `metal2vulkanspirv` path (OpenCL/Kernel SPIR-V backend plus heavy post-rewrite),
|
||||
this crate emits `OpCapability Shader` / `Logical GLSL450` SPIR-V **directly** from sanitized AIR
|
||||
LLVM IR, structured by construction where the CFG admits it.
|
||||
The crate emits `OpCapability Shader` / `Logical GLSL450` SPIR-V directly from sanitized AIR LLVM
|
||||
IR, structured by construction where the CFG admits it.
|
||||
|
||||
```
|
||||
.air|.ll
|
||||
└─ tools::air_to_sanitized_ll llvm-dis (if .air) + sanitize → textual LLVM IR
|
||||
└─ lower_async_copy_if_enabled shared pre-emit AIR rewrites
|
||||
└─ meta::parse_air_{frag,vert,kern} stage interface metadata (bindings, attributes)
|
||||
└─ native emit (tools::llc_vulkan_spirv → native::emit_vulkan_spirv)
|
||||
└─ native emit (tools::emit_vulkan_spirv → native::emit_vulkan_spirv)
|
||||
parse (native/parse.rs, lex.rs) → LlModule
|
||||
typed IR (native/tir/, native/ir/)
|
||||
structured-by-construction emit (native/emitter/**, native/cfg/**)
|
||||
@@ -24,7 +23,8 @@ LLVM IR, structured by construction where the CFG admits it.
|
||||
└─ stage/resource/lowering passes (passes/**)
|
||||
└─ finish_module id canonicalization, portability normalization
|
||||
└─ assemble → SPIR-V words
|
||||
└─ spirv-val (vulkan1.3) [validation gate; not part of the bytes]
|
||||
└─ spirv-val (vulkan1.3) validation/adoption gate; not part of the bytes
|
||||
└─ reflect final buffer footprints reflected entry points only; read-only over adopted bytes
|
||||
```
|
||||
|
||||
`translate_native_no_retry` is this path up to (but not including) spirv-val and the retry cascade.
|
||||
@@ -50,12 +50,15 @@ The production body path is **parse once → typed IR → emit**. There is no mi
|
||||
### Reflection
|
||||
|
||||
Each translation decodes AIR metadata once into a `StageMeta` shared by emission, passes,
|
||||
reflection, and retry re-emissions. Public `translate_*_reflected` entry points return
|
||||
`(Vec<u8>, reflect::ShaderReflection)` with **bytes identical** to the non-reflected call.
|
||||
reflection, and retry re-emissions. After a reflected translation adopts its final validating
|
||||
module, a read-only analyzer derives conservative buffer byte footprints from those exact bytes.
|
||||
Public `translate_*_reflected` entry points return `(Vec<u8>, reflect::ShaderReflection)` with
|
||||
**bytes identical** to the non-reflected call.
|
||||
|
||||
Descriptor ABI bases (buffer = index, texture = 32+n, sampler = 64+n, color = 96+n, set 0) live in
|
||||
`reflect` and are consumed by the resource pass so decorated bindings and reported reflection share
|
||||
one contract. Consumer-oriented guide: [`REFLECTION.md`](REFLECTION.md).
|
||||
one contract. Start with the integration [how-to](HOWTO.md); the complete schema and ABI contract
|
||||
are in [`REFLECTION.md`](REFLECTION.md).
|
||||
|
||||
### Retained module seam
|
||||
|
||||
@@ -85,6 +88,12 @@ The emit sidecar carries Word-id-keyed facts (buffer-address words, local-pointe
|
||||
static/dynamic field loads, AIR struct offsets). Producers append; inlining and resource rewrites
|
||||
remap them. There is no cross-seam `OpName` marker protocol for facts.
|
||||
|
||||
Metal vertex entries carrying `air.patch` metadata finalize as Vulkan tessellation-evaluation
|
||||
entries. The interface pass maps `position_in_patch` to `TessCoord`, `patch_id` to `PrimitiveId`,
|
||||
per-patch arguments to `Patch` inputs, and metadata-described control-point accessors to indexed
|
||||
loads from control-point input arrays. The AIR patch domain and control-point count, never a shader
|
||||
name, determine the execution modes and array extents.
|
||||
|
||||
### Inlining
|
||||
|
||||
Helpers are inlined on the producer side where structural rules allow (one-block and multi-block
|
||||
@@ -103,7 +112,7 @@ Emission is structured-by-construction when possible:
|
||||
`repair_pre_phi_incoming_materializations` relocates illegal in-phi-block access chains.
|
||||
4. **Reject** → function emits with inferred merges unrepaired; the retry cascade’s **relooper**
|
||||
(`native/relooper.rs`) strips merges and rebuilds structured CFG. The relooper is the sole
|
||||
structuring fallback after the old post-hoc repair roster was deleted.
|
||||
general structuring fallback.
|
||||
|
||||
Between reject and relooper, a few specialized constructions may still admit a shape
|
||||
(`structured_plan_divergent_exit`, construct-tree own-arm retry for a narrow class). Adoption of
|
||||
@@ -156,23 +165,23 @@ and default-off measurement substrates only—not product feature gates.
|
||||
|
||||
## Verification
|
||||
|
||||
Match the check to the change. The full developer playbook (harvest → bank hashes → A/B while
|
||||
refactoring, what to commit, recipes by change type) lives in **[`VALIDATION.md`](VALIDATION.md)**.
|
||||
Match the check to the change. The full developer playbook (harvest → author cases → exact A/B →
|
||||
targeted GPU evidence) lives in **[`VALIDATION.md`](VALIDATION.md)**.
|
||||
|
||||
| Check | Command / tool | Catches |
|
||||
|---|---|---|
|
||||
| Lint | `cargo clippy` | style / obvious bugs |
|
||||
| Unit + integration | `cargo test -- --test-threads=1` | translator regressions |
|
||||
| SPIR-V delta class | validation `classify_spirv_delta` | id/order vs semantic drift |
|
||||
| Byte A/B | `scripts/metal2vulkan-ab/` | drift on a local sample |
|
||||
| Translate ledger | `corpus-mint` / `corpus-remint` / `corpus-why` | AIR/SPIR-V sha256 pins |
|
||||
| Execution ledgers | `corpus-run-metal` / `-vulkan` / `-moltenvk` | plan + `output_b64` + digests (JSONL) |
|
||||
| Private corpus (optional) | `validation/corpus/local/` | local shard source for ledgers / A/B |
|
||||
| Metal oracle (optional) | `validation` on macOS | host Metal execution |
|
||||
| Vulkan executor (optional) | `validation` runner | candidate vs oracle bytes |
|
||||
| Byte A/B | validation `corpus-ab` | exact old/new translator drift without a GPU |
|
||||
| Authored cases | `validation/corpus/cases/` | literal semantic inputs and output selection |
|
||||
| Exact observations | `validation/corpus/observations/` | dependency-complete current experiment slots |
|
||||
| Private corpus (optional) | `validation/corpus/local/sources/` | aligned sanitized AIR source shards |
|
||||
| Metal qualification (optional) | validation `corpus-metal` | literal case execution and golden bytes |
|
||||
| Candidate execution (optional) | `corpus-moltenvk` / `corpus-vulkan` | candidate bytes vs exact Metal observation |
|
||||
|
||||
Always rebuild the translator binary before measuring. Default CI is synthetic-only; private
|
||||
metallib harvest is gitignored under `validation/corpus/local/` (see that README).
|
||||
metallib harvest is gitignored under `validation/corpus/local/` (see that README). GPU validation
|
||||
never affects product translation paths and never infers an execution plan from AIR.
|
||||
|
||||
## Hard-won constraints
|
||||
|
||||
|
||||
+227
@@ -0,0 +1,227 @@
|
||||
# How to translate and integrate a shader
|
||||
|
||||
This guide takes one Metal AIR or sanitized LLVM-IR module from input bytes to a validated Vulkan
|
||||
shader and the host state needed to use it. For the complete field-by-field reflection contract, see
|
||||
[Shader reflection for consumers](REFLECTION.md).
|
||||
|
||||
## 1. Install the tools
|
||||
|
||||
Product translation uses two external executables:
|
||||
|
||||
- `llvm-dis` converts AIR bitcode to LLVM IR. It is not needed when the input is already textual
|
||||
`.ll`.
|
||||
- `spirv-val` validates every candidate under the Vulkan 1.3 environment. A retry candidate is
|
||||
adopted only after it validates.
|
||||
|
||||
Put both tools on `PATH`, or set an absolute per-tool override:
|
||||
|
||||
```sh
|
||||
export METAL2VULKAN_LLVM_DIS=/path/to/llvm-dis
|
||||
export METAL2VULKAN_SPIRV_VAL=/path/to/spirv-val
|
||||
```
|
||||
|
||||
Install the CLI with reflection JSON enabled:
|
||||
|
||||
```sh
|
||||
cargo install metal2vulkan --features serde
|
||||
```
|
||||
|
||||
## 2. Translate from the command line
|
||||
|
||||
The default `--stage auto` reads `!air.vertex`, `!air.fragment`, or `!air.kernel` metadata from the
|
||||
module:
|
||||
|
||||
```sh
|
||||
metal2vulkan input.air output.spv --emit-meta reflection.json
|
||||
```
|
||||
|
||||
Successful output contains `PASS`; the process exits `0` after writing validated SPIR-V and schema-
|
||||
versioned reflection. Use an explicit stage only when appropriate:
|
||||
|
||||
```sh
|
||||
metal2vulkan input.ll output.spv --stage vertex
|
||||
metal2vulkan input.ll output.spv --stage fragment
|
||||
metal2vulkan input.ll output.spv --stage kernel
|
||||
metal2vulkan input.ll passthrough.spv --stage passthrough
|
||||
```
|
||||
|
||||
Passthrough generation has no Metal interface metadata, so it cannot be combined with
|
||||
`--emit-meta`. The accepted alias `--stage compute` is equivalent to `kernel`.
|
||||
|
||||
Two options affect pipeline-dependent lowering:
|
||||
|
||||
| Option | Supply it when |
|
||||
|---|---|
|
||||
| `--raster-samples 1|2|4|8|16|32|64` | Fragment AIR calls `air.get_num_samples.i32`; use the exact graphics-pipeline sample count |
|
||||
| `--simd-cluster32` | A caller explicitly needs Metal's 32-lane simdgroup reduction partition on a wider Vulkan subgroup |
|
||||
|
||||
The translator automatically preserves the 32-lane contract for recognized `air.simd_*` modules.
|
||||
Do not use either option as a workaround for an unrelated translation failure.
|
||||
|
||||
## 3. Translate from Rust
|
||||
|
||||
Use `translate_reflected` for an `.air`/`.ll` path and
|
||||
`translate_sanitized_native_reflected` when sanitized LLVM IR is already in memory. All translation
|
||||
entry points require caller-owned scratch space. Give concurrent calls different directories and
|
||||
remove each directory on success or failure.
|
||||
|
||||
The repository includes a complete, compiled example that does this cleanup and writes both output
|
||||
files:
|
||||
|
||||
```sh
|
||||
cargo run --features serde --example translate_reflected -- \
|
||||
input.air output.spv reflection.json auto
|
||||
```
|
||||
|
||||
The core call is:
|
||||
|
||||
```rust
|
||||
use metal2vulkan::passes::{Stage, TransformOptions};
|
||||
use std::path::Path;
|
||||
|
||||
fn translate_ir(
|
||||
sanitized_ll: &str,
|
||||
scratch: &Path,
|
||||
) -> Result<(Vec<u8>, metal2vulkan::reflect::ShaderReflection), String> {
|
||||
metal2vulkan::translate_sanitized_native_reflected(
|
||||
sanitized_ll,
|
||||
Stage::Kernel,
|
||||
scratch,
|
||||
TransformOptions::default(),
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
For path input, call `detect_stage(path, scratch)` and pass the resulting `Stage` to
|
||||
`translate_reflected`. Translation already validates the final module; calling `spirv-val` again is
|
||||
useful only as an independent deployment check or when bytes have changed after translation.
|
||||
|
||||
## 4. Create the descriptor-set layout
|
||||
|
||||
All reflected descriptors use set `0`, but descriptors come from three top-level places. A complete
|
||||
consumer must inspect all three:
|
||||
|
||||
1. `bindings[*].descriptor`
|
||||
2. `implicit_imageblock_attachments[*].binding`
|
||||
3. `fragment_imageblock.members[*].binding` when non-null
|
||||
|
||||
The latter two are single storage-image descriptors in set `0`. For an entry in `bindings`, use
|
||||
`descriptor.set`, `descriptor.binding`, and `descriptor.count` exactly as reported:
|
||||
|
||||
| `ResourceBinding.kind` | Vulkan descriptor type |
|
||||
|---|---|
|
||||
| `Buffer`, `KernelStageInput`, `AccelerationStructureShadow`, `PrimitiveAccelerationStructure`, `BufferAddressTable` | Storage buffer |
|
||||
| `Texture`, `EmbeddedArgBufferTexture` | Sampled image |
|
||||
| `TextureArray` with `access: Sampled` | Sampled-image array |
|
||||
| `TextureArray` with `access: Storage` | Storage-image array |
|
||||
| `StorageImage` | Storage image |
|
||||
| `Sampler`, `StaticSampler` | Sampler |
|
||||
| `ColorInput` | Input attachment |
|
||||
|
||||
`ThreadgroupBuffer`, `EmbeddedArgBufferBuffer`, visible/intersection function tables, and any other
|
||||
entry with `descriptor: null` do not consume a Vulkan descriptor. Do not derive binding numbers
|
||||
from list positions or Metal indices; synthesized resources are deliberately assigned by the
|
||||
translator and reflection is authoritative.
|
||||
|
||||
Static samplers are ordinary Vulkan sampler descriptors whose creation state comes from
|
||||
`static_sampler`. Embedded argument-buffer textures use `embedded_source` to identify their owner,
|
||||
field offset, and Metal argument-encoder index. Embedded buffers use matching entries in
|
||||
`argument_buffer_fields`; write the Vulkan device address into the reflected owner field rather than
|
||||
allocating a separate descriptor.
|
||||
|
||||
## 5. Stage only the buffer bytes the shader can reach
|
||||
|
||||
Successful reflected translation attaches `footprint` to descriptor-backed `Buffer`,
|
||||
`KernelStageInput`, and `AccelerationStructureShadow` resources. It describes accesses in the final
|
||||
SPIR-V module selected by the retry cascade.
|
||||
|
||||
Apply this decision in order:
|
||||
|
||||
1. If `footprint` is null, there is no final-module proof. Retain the complete caller-provided
|
||||
window.
|
||||
2. If `has_unbounded_access` is true, retain the complete window. Static or strided entries remain
|
||||
diagnostic only.
|
||||
3. Otherwise, stage the union of `static_ranges` and every draw/dispatch-bounded
|
||||
`strided_accesses` range. An empty union means the final module does not access the binding.
|
||||
|
||||
Each static item `{ offset, size }` is the half-open interval `[offset, offset + size)`. Each strided
|
||||
item describes accesses of `access_size` bytes at:
|
||||
|
||||
```text
|
||||
base_offset + sum(actual_index_value(source) * stride)
|
||||
```
|
||||
|
||||
Use the exact values generated by the current command, not counts alone. In particular,
|
||||
`VertexIndex`, `InstanceIndex`, and `WorkgroupId` may include nonzero base values. Local invocation
|
||||
IDs range over the pipeline's local size; global invocation IDs range over the dispatched grid. A
|
||||
consumer can enumerate and coalesce the exact accesses, or conservatively copy the interval from
|
||||
the minimum reachable address through the maximum reachable address plus `access_size`.
|
||||
|
||||
All offset, multiply, and end calculations must use checked arithmetic. Overflow means the
|
||||
consumer cannot prove a bound and must retain the complete window. Clip computed ranges to neither
|
||||
`declared_size` nor `extent`: `declared_size` may be only one pointee's size, while an unbounded AIR
|
||||
pointer can legally index beyond it.
|
||||
|
||||
`Object { bytes }` is an independent AIR-metadata guarantee. If a supposedly bounded object's final
|
||||
footprint extends beyond `bytes`, do not hide the inconsistency by clipping it: retain the complete
|
||||
caller window and report the translator/reflection mismatch.
|
||||
|
||||
`access` answers read/write/unused classification when it can be proven. It does not replace the
|
||||
footprint soundness gate. Treat `access: null` conservatively as read-write.
|
||||
|
||||
## 6. Configure the stage interface
|
||||
|
||||
- Create the Vulkan pipeline with entry point `"main"`; `entry_point` contains the original Metal
|
||||
function name for identity and diagnostics.
|
||||
- Vertex stages use `vertex_attributes`, `varyings`, and `vertex_builtins`.
|
||||
- A reflected `TessellationEvaluation` stage also uses `tessellation`; its control-point locations
|
||||
are arrays and its other listed locations carry patch data.
|
||||
- Fragment stages use `varyings`, `render_targets`, `depth_members`, `stencil_members`, and
|
||||
`depth_qualifier`.
|
||||
- Kernel stages use `local_size`. `imageblock_layouts` and threadgroup bindings describe Workgroup
|
||||
storage rather than descriptors.
|
||||
- Use `function_constants` to discover exact indices and Metal ABI type encodings. Specialize IR
|
||||
with `specialize_function_constant_bytes` when exact scalar or vector payloads are required.
|
||||
|
||||
## 7. Cache outputs safely
|
||||
|
||||
Cache SPIR-V and reflection as one atomic result. A practical cache key includes:
|
||||
|
||||
- the exact input bytes;
|
||||
- stage and every `TransformOptions` value;
|
||||
- the metal2vulkan crate/binary version; and
|
||||
- `reflection_version`.
|
||||
|
||||
Invalidate both artifacts together when any key changes. Reflection is byte-neutral, but it is tied
|
||||
to the exact final module returned by the same call. Metadata-only `reflect_sanitized` deliberately
|
||||
has no final-module footprint and is not a substitute for reflected translation in a staging path.
|
||||
|
||||
## 8. Handle failures
|
||||
|
||||
The Rust API returns `Err(String)`. The CLI prints `FALLBACK`, exits nonzero, and writes a self-
|
||||
contained repro bundle under `$TMPDIR/metal2vulkan-repros` unless `METAL2VULKAN_REPRO_DIR` overrides
|
||||
the base directory. Unsupported input must remain a fallback; do not continue with partial metadata
|
||||
or a rejected retry candidate.
|
||||
|
||||
For local diagnosis:
|
||||
|
||||
```sh
|
||||
METAL2VULKAN_RETRY_DEBUG=1 metal2vulkan input.air output.spv
|
||||
METAL2VULKAN_WHY=1 metal2vulkan input.air output.spv
|
||||
```
|
||||
|
||||
The first command shows retry-tier attempts. The second reports structured-CFG admission decisions.
|
||||
These diagnostics do not authorize a different product translation path.
|
||||
|
||||
## 9. Verify the integration
|
||||
|
||||
At minimum:
|
||||
|
||||
```sh
|
||||
spirv-val --target-env vulkan1.3 output.spv
|
||||
cargo test -p metal2vulkan -- --test-threads=1
|
||||
```
|
||||
|
||||
`spirv-val` checks structural validity, not Metal equivalence. For a semantic claim, follow the
|
||||
[validation playbook](VALIDATION.md): use an owned synthetic regression, exact byte A/B where
|
||||
appropriate, and an authored Metal/Vulkan case when output behavior changes.
|
||||
+164
-43
@@ -1,13 +1,17 @@
|
||||
# Shader reflection for consumers
|
||||
|
||||
When you translate a Metal AIR / sanitized LLVM IR module with metal2vulkan, the crate already
|
||||
knows how the **stage interface** was mapped into Vulkan: descriptor set/binding numbers, Metal
|
||||
resource indices, vertex attributes, varyings, render targets, and more. That knowledge is exposed
|
||||
as [`ShaderReflection`](../src/reflect/mod.rs) so a host (engine, executor, cache) does **not** have
|
||||
to re-walk the emitted SPIR-V or re-encode the ABI.
|
||||
When metal2vulkan translates Metal AIR or sanitized LLVM IR, it has two authoritative sources of
|
||||
consumer information:
|
||||
|
||||
Reflection is a pure re-shaping of AIR metadata the translator already parsed. It is **byte-neutral**:
|
||||
`translate_reflected` produces the same SPIR-V as `translate` for the same inputs.
|
||||
- AIR metadata plus the translator's shared descriptor ABI define resources and stage interfaces.
|
||||
- Read-only analysis of the final adopted SPIR-V defines conservative buffer byte footprints.
|
||||
|
||||
Both are exposed as [`ShaderReflection`](../src/reflect/mod.rs), so a host does not need to reparse
|
||||
AIR or build a second general-purpose SPIR-V reflection path. Reflection remains **byte-neutral**:
|
||||
`translate_reflected` produces the same SPIR-V bytes as `translate` for identical input, stage, and
|
||||
options.
|
||||
|
||||
For an end-to-end integration recipe, start with [How to translate and integrate a shader](HOWTO.md).
|
||||
|
||||
## Getting reflection
|
||||
|
||||
@@ -18,10 +22,15 @@ use metal2vulkan::passes::Stage;
|
||||
use metal2vulkan::reflect::ShaderReflection;
|
||||
use std::path::Path;
|
||||
|
||||
fn convert(air_or_ll_path: &str) -> Result<(Vec<u8>, ShaderReflection), String> {
|
||||
let tmp = std::env::temp_dir().join("m2v-scratch");
|
||||
std::fs::create_dir_all(&tmp).ok();
|
||||
metal2vulkan::translate_reflected(air_or_ll_path, Stage::Kernel, Path::new(&tmp))
|
||||
fn convert(
|
||||
air_or_ll_path: &str,
|
||||
caller_owned_scratch: &Path,
|
||||
) -> Result<(Vec<u8>, ShaderReflection), String> {
|
||||
metal2vulkan::translate_reflected(
|
||||
air_or_ll_path,
|
||||
Stage::Kernel,
|
||||
caller_owned_scratch,
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
@@ -30,10 +39,15 @@ Other entry points:
|
||||
| API | Use when |
|
||||
|---|---|
|
||||
| `translate_reflected` / `translate_reflected_with_options` | Path to `.air` or `.ll` + stage |
|
||||
| `translate_sanitized_native_reflected` | You already have sanitized LLVM IR text |
|
||||
| `ShaderReflection::from_{fragment,vertex,kernel}` | You already have `meta::{Frag,Vert,Kern}Meta` |
|
||||
| `translate_sanitized_native_reflected` | You already have sanitized LLVM IR text and `TransformOptions` |
|
||||
| `reflect_sanitized` | You need metadata for link-time tooling even when executable translation is not yet possible; buffer footprints remain absent |
|
||||
| `ShaderReflection::from_{fragment,vertex,kernel}` | You already have `meta::{Frag,Vert,Kern}Meta`; IR-derived fields and buffer footprints remain absent |
|
||||
|
||||
Optional transforms (e.g. `--simd-cluster32` / `TransformOptions`) go through `*_with_options`.
|
||||
Path-based optional transforms use `translate_reflected_with_options`. The sanitized reflected
|
||||
entry point takes `TransformOptions` directly.
|
||||
|
||||
Scratch space belongs to the caller. Give concurrent translations separate directories and remove
|
||||
them on all return paths. The compiled `translate_reflected` example demonstrates that lifecycle.
|
||||
|
||||
### CLI JSON dump
|
||||
|
||||
@@ -46,7 +60,7 @@ metal2vulkan in.ll out.spv --stage kernel --emit-meta out.json
|
||||
|
||||
`--emit-meta` is not supported for `--stage passthrough` (no Metal interface metadata).
|
||||
|
||||
`out.json` is a pretty-printed `ShaderReflection` (schema version in `reflection_version`).
|
||||
`out.json` is a pretty-printed `ShaderReflection` with its schema version in `reflection_version`.
|
||||
|
||||
### Persist with `serde`
|
||||
|
||||
@@ -54,25 +68,38 @@ metal2vulkan in.ll out.spv --stage kernel --emit-meta out.json
|
||||
metal2vulkan = { version = "0.1", features = ["serde"] }
|
||||
```
|
||||
|
||||
`ShaderReflection` and its nested types derive `Serialize`/`Deserialize` under that feature.
|
||||
Bump-aware field: `reflection_version` (`REFLECTION_VERSION`, currently `4`). Invalidate any
|
||||
on-disk cache when that constant changes.
|
||||
`ShaderReflection` and its nested types derive `Serialize`/`Deserialize` under that feature. The
|
||||
current `REFLECTION_VERSION` is `21`. Serialized Rust enums use serde's externally tagged default:
|
||||
unit variants are strings (for example `"Unbounded"`), while data variants are objects (for example
|
||||
`{ "Object": { "bytes": 288 } }`). Optional fields serialize as `null`.
|
||||
|
||||
Persist SPIR-V and reflection together. Invalidate both when `reflection_version` changes. If a
|
||||
cache may contain older schemas, inspect `reflection_version` as generic JSON—or store it in the
|
||||
cache envelope—before deserializing the strongly typed current structure, because a newly required
|
||||
field can make old JSON fail deserialization.
|
||||
|
||||
## Descriptor ABI (binding map)
|
||||
|
||||
Every Metal-facing resource is decorated in **descriptor set 0** (`RESOURCE_DESCRIPTOR_SET`).
|
||||
Bindings are a fixed base plus the Metal resource index `n`:
|
||||
Every descriptor-backed Metal-facing resource uses **descriptor set 0**
|
||||
(`RESOURCE_DESCRIPTOR_SET`). Most bindings are a fixed base plus Metal resource index `n`:
|
||||
|
||||
| Metal resource | Kind | SPIR-V binding |
|
||||
|---|---|---|
|
||||
| `[[buffer(n)]]` (device / constant) | `Buffer` | `BUFFER_BINDING_BASE + n` → **`n`** (`0..32`) |
|
||||
| `[[buffer(n)]]` (device / constant) | `Buffer` | `BUFFER_BINDING_BASE + n` → **`n`** (buffer band `0`–`31`) |
|
||||
| `[[buffer(n)]]` (threadgroup) | `ThreadgroupBuffer` | **no descriptor** (`descriptor: None`) |
|
||||
| Kernel `[[stage_in]]` attribute | `KernelStageInput` | first free buffer binding; AIR location is `stage_input_location` |
|
||||
| `[[texture(n)]]` | `Texture` / `StorageImage` / `TextureArray` (`access` distinguishes sampled vs storage arrays) | `TEXTURE_BINDING_BASE + n` → **`32 + n`** |
|
||||
| `[[sampler(n)]]` | `Sampler` | `SAMPLER_BINDING_BASE + n` → **`64 + n`** |
|
||||
| AIR `constexpr sampler` | `StaticSampler` | first free binding in **`64..96`** |
|
||||
| `[[color(n)]]` (framebuffer fetch) | `ColorInput` | `COLOR_INPUT_BINDING_BASE + n` → **`96 + n`** |
|
||||
| Implicit imageblock attachment `n`, data rate `r` | `implicit_imageblock_attachments` | `IMAGEBLOCK_BINDING_BASE + 3*n + r` → **`128 + 3*n + r`** |
|
||||
| Custom fragment imageblock master member `n` | `fragment_imageblock.members[n]` | `FRAGMENT_IMAGEBLOCK_BINDING_BASE + n` → **`160 + n`** when projected |
|
||||
| Acceleration-structure shadow buffer | `AccelerationStructureShadow` | Metal buffer index `n` (set 0) |
|
||||
| Primitive acceleration structure | `PrimitiveAccelerationStructure` | Metal buffer index `n` (set 0); descriptor only when AIR intersection lowering consumes its geometry shadow |
|
||||
| Authored visible/intersection function table | `VisibleFunctionTable` / `IntersectionFunctionTable` | **no descriptor** (`descriptor: None`); `metal_index` and `param_index` identify static linkage |
|
||||
| Texture embedded in argument buffer | `EmbeddedArgBufferTexture` | `32 + synthetic_index` |
|
||||
| Device buffer embedded in argument buffer | `EmbeddedArgBufferBuffer` | **no descriptor**; owner field contains its Vulkan device address |
|
||||
| Synthesized direct-buffer address table | `BufferAddressTable` | translator-selected free binding; one `u64` address per Metal buffer slot |
|
||||
|
||||
Constants live in `metal2vulkan::reflect`:
|
||||
|
||||
@@ -82,15 +109,35 @@ BUFFER_BINDING_BASE = 0
|
||||
TEXTURE_BINDING_BASE = 32
|
||||
SAMPLER_BINDING_BASE = 64
|
||||
COLOR_INPUT_BINDING_BASE = 96
|
||||
IMAGEBLOCK_BINDING_BASE = 128
|
||||
IMAGEBLOCK_DATA_RATE_STRIDE = 3
|
||||
FRAGMENT_IMAGEBLOCK_BINDING_BASE = 160
|
||||
```
|
||||
|
||||
The stage-input / stage-output passes decorate the module with **exactly these** numbers. Use
|
||||
reflection to allocate descriptor sets / write descriptor updates without disassembling SPIR-V.
|
||||
reflection—not list positions or recomputed synthetic indices—to allocate descriptor sets and write
|
||||
descriptor updates.
|
||||
|
||||
Descriptor types for `bindings`:
|
||||
|
||||
| Kind | Vulkan descriptor type |
|
||||
|---|---|
|
||||
| `Buffer`, `KernelStageInput`, `AccelerationStructureShadow`, `PrimitiveAccelerationStructure`, `BufferAddressTable` | Storage buffer |
|
||||
| `Texture`, `EmbeddedArgBufferTexture` | Sampled image |
|
||||
| `TextureArray` | Sampled-image or storage-image array according to `access` |
|
||||
| `StorageImage` | Storage image |
|
||||
| `Sampler`, `StaticSampler` | Sampler |
|
||||
| `ColorInput` | Input attachment |
|
||||
|
||||
`implicit_imageblock_attachments` and projected `fragment_imageblock.members` are additional
|
||||
single storage-image descriptors in set 0; they are not duplicated in `bindings`. Entries whose
|
||||
`descriptor` is `None` consume no descriptor.
|
||||
|
||||
AIR address spaces (on buffer bindings when present):
|
||||
|
||||
| Value | Meaning |
|
||||
|---|---|
|
||||
| `ADDRESS_SPACE_DEVICE` (1) | Device memory — descriptor-backed storage buffer |
|
||||
| `ADDRESS_SPACE_CONSTANT` (2) | Constant / `const device` — typically read-only |
|
||||
| `ADDRESS_SPACE_THREADGROUP` (3) | Threadgroup — Workgroup variable, no descriptor |
|
||||
|
||||
@@ -101,32 +148,55 @@ Top-level fields:
|
||||
| Field | Meaning |
|
||||
|---|---|
|
||||
| `reflection_version` | Schema version for cache invalidation |
|
||||
| `stage` | `Vertex` / `Fragment` / `Kernel` |
|
||||
| `stage` | `Vertex`, `TessellationEvaluation`, `Fragment`, or `Kernel` |
|
||||
| `entry_point` | **Original Metal entry name** (SPIR-V `OpEntryPoint` is always `"main"`) |
|
||||
| `bindings` | Resources in entry-parameter order (synthesized arg-buffer textures last) |
|
||||
| `bindings` | AIR entry resources followed by translator-synthesized resources |
|
||||
| `argument_buffer_fields` | Resource-handle fields inside argument buffers, with owner and Metal argument-encoder coordinates |
|
||||
| `vertex_attributes` | Vertex `[[attribute(n)]]` / stage-in locations |
|
||||
| `varyings` | Fragment stage-in or vertex user varyings (location, type, semantic) |
|
||||
| `varyings` | Fragment stage-in or vertex user varyings (location, AIR type, field name, linker semantic) |
|
||||
| `render_targets` | Fragment color attachments (member index + location + type name) |
|
||||
| `depth_members` / `stencil_members` | Fragment return members tagged depth/stencil |
|
||||
| `depth_qualifier` | Fragment depth comparison contract (`Any`, `Less`, or `Greater`) |
|
||||
| `local_size` | Kernel GLCompute local size `[x,y,z]` when known |
|
||||
| `vertex_builtins` | Whether vertex uses `VertexIndex` / `InstanceIndex` / writes `Position` |
|
||||
| `tessellation` | Post-tessellation patch domain, control-point count, locations, and synthesized system-value carriers |
|
||||
| `imageblock_layouts` | Kernel `[[imageblock]]` tiles (param index + AIR struct layout; no descriptor) |
|
||||
| `datalayout` | Source LLVM `target datalayout` string when translate started from unsanitized IR |
|
||||
| `function_constants` | `[[function_constant(N)]]` inventory (index / name / LLVM type) |
|
||||
| `implicit_imageblock_attachments` | Attachment/data-rate plane, maximum referenced index, format, access, and descriptor binding for implicit imageblock load/store calls |
|
||||
| `fragment_imageblock` | Custom fragment `[[imageblock_data]]` sample size, exact master fields (offset/type/semantic/raster-order group/access/binding), and semantic-matched input/output projections |
|
||||
| `datalayout` | Source LLVM `target datalayout` when path-based translation captured it before sanitization |
|
||||
| `function_constants` | `[[function_constant(N)]]` index, name, LLVM type, and exact Metal ABI type encoding |
|
||||
|
||||
Custom fragment imageblock fields currently lower exactly as `half` → R16f, `half4` → RGBA16f,
|
||||
`uchar4` → RGBA8ui, and `ushort` → R16ui storage planes. AIR may provide either an explicit
|
||||
`air.imageblock_master` for narrow projections or a direct full `air.imageblock_data` struct layout;
|
||||
both forms preserve the same reflected member contract. Other field types remain an honest fallback.
|
||||
|
||||
Each `argument_buffer_fields` entry records the owning entry parameter and Metal buffer index plus
|
||||
its struct-member ordinal, byte offset, and Metal argument index. A nested buffer additionally
|
||||
carries `resource_buffer_index`; consumers encode the native Metal buffer through
|
||||
`MTLArgumentEncoder` and write its Vulkan device address into the same owner byte offset. Embedded
|
||||
textures, buffers, and authored function tables share this coordinate, so consumers do not need to
|
||||
reparse `air.struct_type_info`.
|
||||
|
||||
Metal post-tessellation vertex entries use `ShaderStage::TessellationEvaluation`. Their
|
||||
control-point locations are arrays of `control_point_count` values; other listed locations carry
|
||||
the `Patch` decoration. Hosts connect these values from a tessellation-control stage rather than
|
||||
binding them as ordinary vertex attributes.
|
||||
|
||||
### Per-binding: `ResourceBinding`
|
||||
|
||||
| Field | Use for |
|
||||
|---|---|
|
||||
| `kind` | Choose descriptor type (UBO/SSBO/sampled image/storage image/sampler/input attachment) |
|
||||
| `kind` | Choose descriptor type using the mapping above |
|
||||
| `metal_index` | Guest Metal slot `n`, or synthetic index for embedded textures |
|
||||
| `descriptor` | `{ set, binding }` or `None` if no descriptor (threadgroup / some locals) |
|
||||
| `descriptor` | `{ set, binding, count }` or `None` if no descriptor (threadgroup / some locals) |
|
||||
| `param_index` | SPIR-V `OpFunctionParameter` order, if any |
|
||||
| `address_space` / `declared_size` / `type_layout` | Buffer address space, argument/pointee size, and aggregate layout |
|
||||
| `extent` | Buffer reachability: `Object { bytes }`, `Unbounded`, or `Unknown` |
|
||||
| `footprint` | Final-module static byte ranges, invocation-strided accesses, and an explicit unbounded-access flag |
|
||||
| `type_name` | AIR type string when metadata carried it |
|
||||
| `texture_shape` | Dim / arrayed / MS / component / writable / storage format (decoded) |
|
||||
| `embedded_source` | For arg-buffer textures: owning buffer index + field byte offset |
|
||||
| `texture_shape` | Dim / arrayed / MS / component / writable / storage format, plus fixed handle-array length when present |
|
||||
| `embedded_source` | For arg-buffer textures: owning buffer index, field byte offset, and Metal `[[id(n)]]` argument-encoder index |
|
||||
| `access` | When known: `Unused` / `ReadOnly` / `WriteOnly` / `ReadWrite` / `Sampled` / `Storage` |
|
||||
| `static_sampler` | Decoded immutable state for `StaticSampler`; `None` for other kinds |
|
||||
|
||||
@@ -151,6 +221,45 @@ an unused parameter becomes `Unused`, while sound `readonly` and `writeonly` par
|
||||
become `ReadOnly` and `WriteOnly`. When neither source proves a narrower result, the broader AIR
|
||||
classification is retained.
|
||||
|
||||
### Buffer byte footprints
|
||||
|
||||
Successful reflected translation derives each supported descriptor-backed buffer's `footprint` from the
|
||||
**final adopted SPIR-V module**. This is intentionally later than AIR metadata reflection: if the
|
||||
validator selects a raw-buffer, pointer-value, or CFG retry tier, the footprint describes the bytes
|
||||
that tier actually executes. Metadata-only `reflect_sanitized` leaves `footprint: null` because no
|
||||
executable module exists to audit.
|
||||
|
||||
Footprints are populated for `Buffer`, `KernelStageInput`, and `AccelerationStructureShadow` when
|
||||
they have a descriptor. Other resource kinds leave the field null.
|
||||
|
||||
`static_ranges` is a sorted, coalesced list of half-open byte intervals. Each item is serialized as
|
||||
`{ "offset": N, "size": M }` and denotes `[N, N + M)`. Loads, stores, atomics, and memory copies all
|
||||
contribute their complete access width; adjacent and overlapping intervals are merged.
|
||||
|
||||
`strided_accesses` represents an address of the form:
|
||||
|
||||
```text
|
||||
base_offset + sum(index_source * stride), spanning access_size bytes
|
||||
```
|
||||
|
||||
`index_source` is one stable draw/dispatch domain: `VertexIndex`, `InstanceIndex`, an X/Y/Z component
|
||||
of `GlobalInvocationId`, `LocalInvocationId`, or `WorkgroupId`, or `LocalInvocationIndex`. Terms are
|
||||
sorted and repeated sources are combined. A consumer supplies the invocation bounds from its draw or
|
||||
dispatch and unions the resulting ranges with `static_ranges`. Bound calculations must use checked
|
||||
arithmetic; overflow has the same meaning as an unbounded access and requires the complete window.
|
||||
|
||||
`has_unbounded_access` is the soundness gate. It becomes true for data-dependent runtime-array
|
||||
indices, pointer/integer escapes, unsupported aggregate transfer widths, arithmetic overflow, or any
|
||||
other rooted dereference the affine schema cannot prove. When true, consumers must retain the whole
|
||||
caller-provided window; the other entries remain useful diagnostics but do not authorize narrowing.
|
||||
When false, the union of the static and bounded strided ranges is a conservative staging footprint.
|
||||
|
||||
Pointer-select/phi alternatives are analyzed structurally across every descriptor arm. To preserve
|
||||
the per-translation memory bound, an adversarial expression with more than 4096 address alternatives
|
||||
is compressed to one unbounded result per affected binding rather than allowed to grow
|
||||
exponentially. A binding with more than 16,384 distinct pre-coalescing footprint records likewise
|
||||
becomes unbounded instead of allowing reflection size to grow without limit.
|
||||
|
||||
**Gaps consumers should expect:**
|
||||
|
||||
- **Device buffer R/W:** ambiguous parameters retain their conservative AIR declaration; malformed
|
||||
@@ -160,25 +269,34 @@ classification is retained.
|
||||
`function_constants` empty; populate via the reflected translate paths (they scan sanitized IR).
|
||||
- **Datalayout:** only filled when translating from unsanitized `.air`/`.ll` via
|
||||
`translate_reflected*` (sanitization strips the line; the reflected path captures it first).
|
||||
- **Static samplers:** only reflected by translated entry points because they require the sanitized
|
||||
module's `!air.sampler_states` metadata. The state includes typed filter, address, coordinate,
|
||||
compare, anisotropy, LOD, border, and reduction fields plus the original two AIR words.
|
||||
- **Static samplers:** reflected translate paths and `reflect_sanitized` scan
|
||||
`!air.sampler_states`; direct `from_*` builders do not. The state includes typed filter, address,
|
||||
coordinate, compare, anisotropy, LOD, border, and reduction fields plus the original two AIR
|
||||
words.
|
||||
|
||||
## Typical consumer flow
|
||||
|
||||
1. Call `translate_reflected` (or CLI with `--emit-meta` + `serde`).
|
||||
1. Call `translate_reflected` (or a serde-enabled CLI with `--emit-meta`).
|
||||
2. Cache `(spv_bytes, reflection)` keyed by input hash + `reflection_version` + translator version.
|
||||
3. Create a Vulkan pipeline with entry point `"main"`.
|
||||
4. For each `bindings` entry with `Some(descriptor)`:
|
||||
4. Build the ordinary portion of set 0 from every `bindings` entry with `Some(descriptor)`:
|
||||
- Map `kind` → descriptor type.
|
||||
- Write `set` / `binding` from `descriptor`.
|
||||
- Use `metal_index` to pick the host resource that was bound as Metal slot `n`.
|
||||
5. For `ThreadgroupBuffer` / `imageblock_layouts`, allocate Workgroup / tile storage from
|
||||
- For buffers, narrow staging from `footprint` only when `has_unbounded_access` is false; bound
|
||||
every strided term from the current draw/dispatch before taking the union.
|
||||
5. Add one set-0 storage-image descriptor for every `implicit_imageblock_attachments` entry and
|
||||
every projected `fragment_imageblock` member, using their reported `binding` values.
|
||||
6. Populate static samplers and argument-buffer fields from their reflected state/coordinates;
|
||||
resources with `descriptor: None` require no descriptor write.
|
||||
7. For `ThreadgroupBuffer` / `imageblock_layouts`, allocate Workgroup / tile storage from
|
||||
`declared_size` / `type_layout` (no descriptor write).
|
||||
6. For vertex: bind attributes from `vertex_attributes` and respect `vertex_builtins`.
|
||||
7. For fragment: attach color targets from `render_targets`; handle depth/stencil member lists.
|
||||
8. For kernels: set local size from `local_size` when present; specialize function constants if
|
||||
the host supplies values (see `specialize_function_constants` / AIR FC ABI).
|
||||
8. For vertex: bind attributes from `vertex_attributes` and respect `vertex_builtins`.
|
||||
9. For fragment: attach color targets from `render_targets`; attach the reflected depth/stencil
|
||||
aspects and derive depth comparison from `depth_qualifier`.
|
||||
10. For kernels: set local size from `local_size` when present; specialize function constants if
|
||||
the host supplies values. Use `specialize_function_constant_bytes` for exact scalar/vector
|
||||
payloads; the `u64`-only helper cannot carry vectors wider than eight bytes.
|
||||
|
||||
## Related APIs
|
||||
|
||||
@@ -188,11 +306,14 @@ classification is retained.
|
||||
| `metal2vulkan::meta` | Lower-level AIR metadata parsers (`FragMeta` / `VertMeta` / `KernMeta`) |
|
||||
| `metal2vulkan::passes::Stage` | Stage enum for translate |
|
||||
| `metal2vulkan::specialize_function_constants` | Specialize FC values on sanitized IR (when needed) |
|
||||
| `metal2vulkan::specialize_function_constant_bytes` | Specialize exact-width scalar/vector FC payloads |
|
||||
|
||||
Unit coverage for binding numbers lives in `src/reflect/tests.rs` (ABI contract: set 0, bases 0/32/64/96).
|
||||
Unit coverage for binding numbers lives in `src/reflect/tests.rs` (ABI contract: set 0, bases
|
||||
0/32/64/96/128/160).
|
||||
|
||||
## What reflection is *not*
|
||||
|
||||
- Not a full SPIR-V reflector (no walk of every `OpDecorate` / CFG).
|
||||
- Not a general-purpose SPIR-V reflector. Final-module inspection is deliberately limited to the
|
||||
descriptor/type/value graph required for conservative buffer footprints.
|
||||
- Not a substitute for `spirv-val` or runtime pipeline creation.
|
||||
- Not populated for passthrough vertex generation (`translate_passthrough`).
|
||||
+338
-474
@@ -1,534 +1,398 @@
|
||||
# Validation workflow — how not to ship a broken translator
|
||||
# Validation playbook
|
||||
|
||||
This is the developer playbook for **staying confident while you change the emitter**. It is
|
||||
written for people who will refactor, not for people who only want a green CI badge.
|
||||
Validation has two independent contracts: translator byte stability and authored-case semantic
|
||||
correctness. Neither SPIR-V validity nor a delta category proves agreement with Metal.
|
||||
|
||||
CI on a clean clone is deliberately **synthetic-only**: unit tests, small owned fixtures, no Apple
|
||||
system metallibs. That keeps the public tree legal and fast. Everything else below is optional
|
||||
**local power** — private harvest, hash ledgers, A/B binaries, oracle/executor probes — that you
|
||||
turn on when the change is large enough that synthetic tests alone would lie to you.
|
||||
Choose the smallest route that proves the claim being made:
|
||||
|
||||
Related:
|
||||
|
||||
| Doc / tree | Role |
|
||||
| Goal | Required starting point |
|
||||
|---|---|
|
||||
| [`ARCHITECTURE.md`](ARCHITECTURE.md) | How the translator is built |
|
||||
| [`REFLECTION.md`](REFLECTION.md) | Consumer binding metadata |
|
||||
| [`../CONTRIBUTING.md`](../CONTRIBUTING.md) | Day-to-day build loop |
|
||||
| [`../validation/`](../validation/) | Optional oracle / executor crate |
|
||||
| [`../validation/corpus/`](../validation/corpus/) | Translate/execution ledgers + private corpus layout |
|
||||
| Ordinary code change | Format, clippy, and serial product/validation tests |
|
||||
| Behavior-preserving translator refactor | Ordinary gate plus exact old/new `corpus-ab` over the structurally affected selection |
|
||||
| Intentional shader behavior change | Synthetic regression, reviewed byte drift, and affected authored Metal/candidate evidence |
|
||||
| Corpus-wide support or performance claim | Resumable indexed `corpus-triage` audit with its completion/read/time summaries |
|
||||
|
||||
---
|
||||
## Ordinary gate
|
||||
|
||||
## The mental model: ladders, not a single gate
|
||||
|
||||
Think in **layers of evidence**. Climb as far as the risk of your change warrants.
|
||||
|
||||
```text
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ E Execution (optional) │
|
||||
│ Metal oracle / Vulkan runner — “bytes match a golden” │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ D Private real AIR (gitignored) │
|
||||
│ system harvest → translate smokes / local corpus tests │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ C Hash ledger (public or private fingerprints) │
|
||||
│ sha256(AIR) → sha256(SPIR-V) — “this module still emits │
|
||||
│ the same bytes” without shipping shader bodies │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ B Byte A/B of two translator binaries │
|
||||
│ old binary vs new on the same sample set │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ A Synthetic tests (always) │
|
||||
│ cargo test — owned .ll / unit cases, CI default │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
| Layer | Cost | What it proves | What it does *not* prove |
|
||||
|---|---|---|---|
|
||||
| **A** Synthetic | seconds | structural regressions you already encoded | real system-shader surface |
|
||||
| **B** Binary A/B | minutes | your refactor did not move SPIR-V on a sample | that the sample is complete |
|
||||
| **C** Hash ledger | minutes | banked AIR still maps to banked SPIR-V | semantic correctness vs Metal |
|
||||
| **D** Harvest corpus | tens of min (first time) | stage-marked system shaders still translate / val | full binding/oracle fidelity |
|
||||
| **E** Execution | machine-specific | candidate matches oracle (or known tolerance) | every metallib on every OS |
|
||||
|
||||
A pure formatting or clippy-only change can stop at **A**. A structurizer or pointer rewrite
|
||||
should climb at least to **B**, and preferably **C**/**D** if you have a local harvest.
|
||||
|
||||
---
|
||||
|
||||
## What “good” looks like after a refactor
|
||||
|
||||
You want all of these to be true for the scope you claimed:
|
||||
|
||||
1. **Synthetic suite still green** — `cargo test -p metal2vulkan -- --test-threads=1`.
|
||||
2. **No accidental SPIR-V churn** on banked cases — A/B clean, ledger remint clean, *or* an
|
||||
intentional re-mint with a clear commit message.
|
||||
3. **No silent FALLBACK explosion** — cases that used to emit still emit (or are honestly marked
|
||||
broken / fallback in the ledger).
|
||||
4. **No name-keyed “fixes”** — you did not special-case a function name from the harvest to green
|
||||
a test (see design rules). Failures get a structural fix or an honest skip.
|
||||
|
||||
If you only have (1), you have CI confidence. If you have (1)+(2)+(3) on a fat private sample,
|
||||
you have **refactor confidence**.
|
||||
|
||||
---
|
||||
|
||||
## One-time setup (do this once per machine)
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Rust (see `rust-version` in `Cargo.toml`)
|
||||
- `llvm-dis`, `spirv-val` on `PATH` (Homebrew LLVM on macOS is fine)
|
||||
- macOS if you want **system** metallib harvest; Linux can still mint public fixtures and
|
||||
`--metallib` paths you already have
|
||||
|
||||
```sh
|
||||
export PATH="/opt/homebrew/opt/llvm/bin:$PATH" # if needed
|
||||
cargo build --release --bin metal2vulkan
|
||||
cargo test -p metal2vulkan -- --test-threads=1
|
||||
```
|
||||
|
||||
### Optional: seed a private real-AIR bank (macOS)
|
||||
|
||||
This is the “I refuse to trust only toy shaders” path. Output is **gitignored** — never commit it.
|
||||
|
||||
```sh
|
||||
# Scan prioritized system metallibs → validation/corpus/local/shards/
|
||||
# No default --limit: processes the full prioritized list (long first run).
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-harvest
|
||||
|
||||
# Optional: bank private hashes into the committed ledger as kind=private
|
||||
# (fingerprints only — still no shader bodies in git)
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-mint
|
||||
```
|
||||
|
||||
What harvest keeps:
|
||||
|
||||
- Real **Kernel / Vertex / Fragment** entries with `!air.*` stage metadata → JSONL shard rows
|
||||
- Drops metallib-embedded **helpers** without stage meta (stdlib / libcall / MPS stitching)
|
||||
so they never land in ledgers or A/B samples
|
||||
- Skips AIR larger than the configured size cap
|
||||
- Stores sanitized `air_ll`, optional `blob_b64`, source metallib path/hash, and shard name in JSONL
|
||||
|
||||
Details: [`validation/corpus/README.md`](../validation/corpus/README.md).
|
||||
|
||||
---
|
||||
|
||||
## The everyday refactor loop
|
||||
|
||||
### 0. Know what you are claiming
|
||||
|
||||
Before you start:
|
||||
|
||||
- **Byte-stable refactor** (“must not change SPIR-V on the sample”) → bank ledger / A/B *before*
|
||||
editing, demand clean after.
|
||||
- **Intentional SPIR-V change** (“emitter is allowed to move”) → re-mint is expected; still run
|
||||
translate smokes and unit tests; explain the delta class if you can (`spirv_delta`).
|
||||
|
||||
### 1. Capture “before” (when you care about byte stability)
|
||||
|
||||
```sh
|
||||
cargo build --release --bin metal2vulkan
|
||||
cp target/release/metal2vulkan ./m2v-old # gitignored name pattern; fine locally
|
||||
```
|
||||
|
||||
Optional: ensure the public + local ledgers are current *before* the change:
|
||||
|
||||
```sh
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-mint
|
||||
```
|
||||
|
||||
### 2. Make the change
|
||||
|
||||
Work as usual. Prefer structural tests in `src/**/tests` for any new bug class you fix — those
|
||||
are the only regressions CI will guard for strangers.
|
||||
|
||||
### 3. Cheap gates (every save cycle)
|
||||
Always run Rust tests serially:
|
||||
|
||||
```sh
|
||||
cargo fmt --all
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo test -p metal2vulkan -- --test-threads=1
|
||||
cargo test -p metal2vulkan-validation -- --test-threads=1
|
||||
```
|
||||
|
||||
### 4. Byte A/B against the saved binary
|
||||
CI uses owned synthetic fixtures. Private AIR and machine-specific GPU execution are optional.
|
||||
|
||||
## Private corpus and authored evidence
|
||||
|
||||
### Harvest and incrementally index
|
||||
|
||||
Harvesting only creates private sources; it never creates execution obligations or manifests.
|
||||
|
||||
```sh
|
||||
cargo build --release --bin metal2vulkan
|
||||
scripts/metal2vulkan-ab/metal2vulkan-ab.sh --old ./m2v-old
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-harvest
|
||||
cargo run -p metal2vulkan-validation --bin corpus-index
|
||||
cargo run -p metal2vulkan-validation --bin corpus-next -- --limit 1
|
||||
```
|
||||
|
||||
A/B walks (when present):
|
||||
Ordinary `corpus-index` runs are incremental: unchanged multi-gigabyte AIR source shards are not
|
||||
opened. Use `corpus-index -- --rebuild` only for explicit recovery; `--check` verifies a cloned,
|
||||
incrementally synchronized snapshot without performing a second full rebuild. Upgrading a legacy
|
||||
index installs shard stamps from file metadata without reading source bodies. Its first lookup of a
|
||||
row without a byte location scans only that hash's one aligned shard, records every row location in
|
||||
that shard, and then uses direct seeks.
|
||||
|
||||
- `tests/fixtures/**` (private, gitignored)
|
||||
- `validation/fixtures/public/**` (committed synthetic)
|
||||
- `validation/corpus/local/shards/*.jsonl` (private harvest; temp `.ll` materialized only while A/B runs)
|
||||
Harvest is shard-local too. A batch is deduplicated in memory, then merged only into buckets that
|
||||
received a hash; unrelated source shards are neither opened nor rewritten. The harvest summary
|
||||
reports `affected_shards`, and index synchronization reports `source_shards_scanned` and
|
||||
`source_bytes_scanned`, so an accidental corpus-wide traversal is visible immediately. A changed
|
||||
bucket's compact identities and byte locations are published to SQLite while the merger still has
|
||||
them in memory; the following index sync therefore reads zero AIR bytes. If publication is
|
||||
interrupted, the unmatched file stamp makes the next sync repair only that bucket. Sanitization
|
||||
also removes llvm-dis's input-path `ModuleID` comment, so a scratch-directory name cannot turn an
|
||||
identical AIR module into a new content identity.
|
||||
|
||||
Shard rows use the embedded sanitized `air_ll`; no retained `local/air` mirror is required.
|
||||
### Audit authoring capabilities
|
||||
|
||||
Exit 0 means no `DIFFERS` / asymmetric produce-vs-fail on that sample. `BOTH-FAIL` is not a
|
||||
regression (both sides FALLBACK).
|
||||
`corpus-triage` stores analyzer-versioned structural facts in the disposable index. Its first audit
|
||||
reads only selected indexed rows and skips retained blob decoding; repeated audits reuse those facts.
|
||||
A newly harvested content hash has no cached facts, so only that new row is analyzed.
|
||||
|
||||
### 5. Hash ledger mint / remint (no need to keep two binaries forever)
|
||||
The authoring-capability audit covers every indexed source, including rows that already have an
|
||||
authored case. It selects uncached identities in SQLite, reads only their indexed source slices,
|
||||
and fails when a complete census contains a structural requirement that the authored schema and
|
||||
executors cannot represent. The shared check consumes reflection—not source names—and covers both
|
||||
resource kinds and executable shape/state facts such as texture dimensionality and storage format,
|
||||
static-sampler state, depth/stencil outputs, and tessellation interfaces.
|
||||
|
||||
Bank AIR/SPIR-V content hashes in `validation/corpus/metal2vulkan-ledger.jsonl` (no shader bodies).
|
||||
Use byte A/B (`metal2vulkan-ab`) when you need a before/after binary compare on a live sample.
|
||||
|
||||
After an intentional emit change (or to bank **new** hashes only):
|
||||
The same census also inventories every called `air.*` ABI symbol through the product crate's
|
||||
canonical intrinsic-family contract. A call outside that contract adds the typed
|
||||
`unrecognized-air-intrinsic` product-support gap, with the exact symbol and aggregate call count.
|
||||
Declarations alone are not uses. Product-support gaps are tracked separately from authored-tooling
|
||||
requirements, so adding a schema or executor feature cannot make one disappear: the product's
|
||||
family contract must gain an intentional lowering or exact static-linkage path, and the lowering
|
||||
remains responsible for validating operand and result shapes.
|
||||
|
||||
```sh
|
||||
# additive: only air_sha256 not already in the ledger (public + local)
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-mint
|
||||
# review the ledger diff; commit only hash rows you mean to bank
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-triage -- \
|
||||
--audit authoring-capabilities --limit 100000
|
||||
```
|
||||
|
||||
To re-bank existing ledger pins after a translator fix (or a full intentional re-emit):
|
||||
After changing only the product's AIR-intrinsic recognition/lowering contract, add
|
||||
`--reclassify-all`. It recomputes the product disposition for every current analyzer row directly
|
||||
from the cached exact `air_calls` inventory. The operation ignores the ordinary `--limit`, uses
|
||||
bounded keyset batches, and opens zero AIR source shards. Changes to source-derived structural
|
||||
analysis instead require an analyzer ABI bump; the ordinary incremental audit then reads and caches
|
||||
each row once under the new ABI.
|
||||
|
||||
The summary exposes classified and remaining counts plus exact shard bytes read, so both an
|
||||
incomplete support claim and an accidental corpus rescan are visible. Classification defaults to
|
||||
all logical CPU cores. Only one parsed source may wait outside the workers (individual rows can be
|
||||
tens of MiB), result channels are bounded, and cache writes are committed in fixed-size batches, so
|
||||
a full recomputation does not retain the corpus in memory; use `--jobs N` to lower the aggregate
|
||||
working set.
|
||||
|
||||
### Run the bounded translation census
|
||||
|
||||
The translation census is resumable and uses the same indexed source locations. Discovery skips any
|
||||
hash that has already translated (or has been classified as requiring authored linkage), while
|
||||
`--current-fingerprint` performs a fresh regression sweep after product changes. A validation-harness
|
||||
fix can re-run only failures recorded for the current product with `--retry-failures`:
|
||||
|
||||
For a targeted regression set, `--hash-file PATH` reads the lowercase SHA-256 in the first
|
||||
whitespace-delimited field of each non-empty line. It audits exactly those identities through their
|
||||
indexed byte ranges, so a saved structural manifest never requires a shard or corpus rescan.
|
||||
|
||||
Translation workers default to all available logical CPU cores. Each row is decoded from its indexed
|
||||
shard slice and translated in an independent child with the per-translation limits below; use
|
||||
`--jobs N` to reduce aggregate memory pressure. The summary reports source-read time separately from
|
||||
translate/validate time so serial decode overhead stays visible. To prevent CPU contention from
|
||||
turning into false wall-time failures, at most four AIR sources of 1 MiB or larger run concurrently;
|
||||
the remaining workers consume the small-source lane, and large-lane workers steal small work after
|
||||
their lane drains.
|
||||
|
||||
```sh
|
||||
# remint every banked hash still present in public fixtures or local shards
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-remint -- --dry-run
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-remint
|
||||
|
||||
# only status != ok (fallback / timeout / …)
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-remint -- --failed-only
|
||||
|
||||
# bounded timeout-row cleanup; each row runs in a killable subprocess
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-remint -- --status timeout --skip 50 --limit 50 --case-timeout-secs 60
|
||||
cargo run --release -p metal2vulkan-validation --bin corpus-triage -- \
|
||||
--audit translation --limit 500 --summary-only
|
||||
cargo run --release -p metal2vulkan-validation --bin corpus-triage -- \
|
||||
--audit translation --retry-failures --limit 500 --summary-only
|
||||
cargo run --release -p metal2vulkan-validation --bin corpus-triage -- \
|
||||
--audit translation --hash-file imageblock-sources.txt --summary-only
|
||||
```
|
||||
|
||||
Rows without a matching public fixture or shard row are left alone. Prefer `--dry-run` first.
|
||||
The 500-row checkpoint is the measured default for the current 88,819-row corpus: unlike a
|
||||
1,000-row checkpoint containing several of its largest modules, it retained comfortable margin
|
||||
under the repository's 30-second workflow ceiling while still persisting every ten completions.
|
||||
Jobs default to the host's available logical cores; increasing that value beyond the available
|
||||
cores can starve individual workers and create false timeouts.
|
||||
|
||||
### 6. Execution ledgers (when translate-green is not enough)
|
||||
The translation audit supplies the validation graphics executor's single-sample pipeline contract
|
||||
when lowering `air.get_num_samples.i32`; authored candidate execution uses that same value. This is
|
||||
not a product default: general callers provide their exact raster sample count through
|
||||
`TransformOptions` or the CLI.
|
||||
|
||||
Execution builds on the translate ledger and up to three backend ledgers:
|
||||
Each translation runs in a killable child with a 30-second / 512-MiB ceiling. The parent owns the
|
||||
child's scratch subtree, so success, failure, timeout, and memory termination all have the same
|
||||
deterministic cleanup path; a killed child never strands a PID-named directory.
|
||||
|
||||
### Run focused structural audits
|
||||
|
||||
Visible-function-table lowering can be audited in deterministic bounded batches without traversing
|
||||
the corpus. The summary names the first and last hash; pass the last hash back as `--after` to read
|
||||
the next batch:
|
||||
|
||||
```sh
|
||||
cargo run -p metal2vulkan-validation --bin corpus-triage -- \
|
||||
--audit visible-function-tables --limit 200 --summary-only
|
||||
cargo run -p metal2vulkan-validation --bin corpus-triage -- \
|
||||
--audit visible-function-tables --after LAST_SHA256 --limit 200 --summary-only
|
||||
```
|
||||
|
||||
The audit distinguishes direct/cast calls, internal-helper parameter threading, authored slot
|
||||
nullness checks, and unsupported pointer escapes. Dynamic dispatchers contain only linked functions
|
||||
whose LLVM signature matches the call site, allowing one authored table to hold heterogeneous
|
||||
visible-function types. AIR's exact `ptrtoint` / truncate / compare-with-`1` opaque-intersection
|
||||
sentinel probe is folded to false for authored visible tables, whose slots are strictly linked
|
||||
functions or null; other pointer-integer observations remain unsupported.
|
||||
|
||||
Ray-intersection families use the same indexed cursor workflow:
|
||||
|
||||
```sh
|
||||
cargo run -p metal2vulkan-validation --bin corpus-triage -- \
|
||||
--audit ray-intersections --limit 200 --summary-only
|
||||
cargo run -p metal2vulkan-validation --bin corpus-triage -- \
|
||||
--audit ray-intersections --after LAST_SHA256 --limit 200 --summary-only
|
||||
```
|
||||
|
||||
The product crate owns the compositional `air.intersect.*` family descriptor. The audit checks each
|
||||
callee's exact return aggregate and argument count against that descriptor, so validation and
|
||||
translation cannot drift into separate whole-symbol allowlists.
|
||||
|
||||
Focused audits select cached structural facts, not unsupported-requirement rows. A feature therefore
|
||||
remains auditable after it becomes fully supported. Device-address captures use the same cursor and
|
||||
the same killable 30-second / 512-MiB translation worker as the full census:
|
||||
|
||||
```sh
|
||||
cargo run --release -p metal2vulkan-validation --bin corpus-triage -- \
|
||||
--audit device-address-hierarchy --limit 200 --summary-only
|
||||
cargo run --release -p metal2vulkan-validation --bin corpus-triage -- \
|
||||
--audit device-address-hierarchy --after LAST_SHA256 --limit 200 --summary-only
|
||||
```
|
||||
|
||||
### Author an executable case
|
||||
|
||||
Authored fragment cases are executable, not review-only: `render_targets`, `depth_stencil`, and
|
||||
`draw` feed real Metal and Vulkan render pipelines. Depth outputs preserve the reflected AIR
|
||||
`any`/`less`/`greater` qualifier, while stencil outputs use the native fragment stencil-export
|
||||
contract. Each runner derives the same fullscreen vertex inputs from the
|
||||
fragment AIR interface, and the candidate dependency hash covers both generated vertex SPIR-V and
|
||||
translated fragment SPIR-V.
|
||||
|
||||
Custom fragment `[[imageblock_data]]` is authored separately as `fragment_imageblock`: one
|
||||
tightly-packed plane per accessed AIR user semantic, with an explicit `half`, `half4`, `uchar4`, or
|
||||
`ushort` format and the same input/output/inout byte rules as other resources. `half` remains the
|
||||
omittable default. Metal initializes and resolves those exact types with generated fragment helpers
|
||||
in the same render pass; Vulkan binds the corresponding storage-image formats under ordered pixel
|
||||
interlock. `output.kind: fragment_imageblock` selects a semantic and 2D region for comparison.
|
||||
|
||||
Framebuffer-fetch inputs reuse the authored render target at the same attachment index. Metal
|
||||
loads that attachment natively; Vulkan binds the same initialized image as both a color attachment
|
||||
and subpass input in `GENERAL` layout with a by-region self-dependency, preserving the single-pass
|
||||
read/modify/write contract. These cases use the ordinary one-instance fullscreen triangle so each
|
||||
sample has one fragment invocation; manifests that request intra-draw overlapping framebuffer
|
||||
fetches are rejected instead of assuming an unavailable raster-order attachment extension.
|
||||
|
||||
Kernel functions with implicit imageblock attachments execute as Metal tile pipelines and Vulkan
|
||||
storage-image attachment planes. Their render-target bytes are the shared initial pixel values.
|
||||
The exact scalar/vector plane format is reflected for `half`, `half2`, `half4`, `float`, and
|
||||
32-bit integer AIR imageblock calls rather than padding narrow planes to four channels.
|
||||
`imageblock.implicit_coverage: full_single_sample` explicitly requests the fullscreen,
|
||||
color-write-disabled Metal coverage prepass needed for ordinary implicit imageblock writes to
|
||||
persist through the render-pass store action.
|
||||
|
||||
Authored vertex cases use the same graphics executor with literal vertex attributes and an explicit
|
||||
`vertex_observation`. Product reflection carries vertex-output type, field name, and linker semantic;
|
||||
the generated fragment companion observes that exact interface and writes attachment zero.
|
||||
|
||||
Inspect the selected sanitized AIR. Write one meaningful manifest with exact resources, bytes,
|
||||
function constants, dispatch/draw parameters, output region, exact comparison, and rationale. Then:
|
||||
|
||||
For an AIR instance acceleration structure, declare `acceleration_structures` with its Metal
|
||||
binding and explicit `child_references`. The oracle constructs identity instances of a canonical
|
||||
triangle; candidates serialize the count and host-defined child payloads using the product shadow
|
||||
ABI. Do not compare raw child-pointer identities across Metal and Vulkan.
|
||||
|
||||
For an AIR primitive acceleration structure, set `kind` to `primitive` and provide
|
||||
`primitive_triangles_b64`: tightly packed little-endian triangle vertices (nine `f32` values per
|
||||
triangle). Metal builds a primitive AS from those exact vertices. Vulkan consumes the same bytes
|
||||
through the reflected geometry shadow when AIR intersection lowering requires it; an unused native
|
||||
handle correctly has no Vulkan descriptor.
|
||||
|
||||
```sh
|
||||
cargo run -p metal2vulkan-validation --bin corpus-case-check -- \
|
||||
--manifest /path/to/case.json --install
|
||||
cargo run -p metal2vulkan-validation --bin corpus-index
|
||||
cargo run -p metal2vulkan-validation --bin corpus-index -- --check
|
||||
cargo run -p metal2vulkan-validation --bin corpus-status
|
||||
```
|
||||
|
||||
If the AIR cannot yet be authored safely, record why without creating a case or evidence row:
|
||||
|
||||
```sh
|
||||
cargo run -p metal2vulkan-validation --bin corpus-next -- \
|
||||
--review-air AIR_SHA256 --reason "explicit unsupported requirement" --reviewed-by ID
|
||||
```
|
||||
|
||||
The aligned review note remains an `unplanned` queue annotation and survives index rebuilds. It is
|
||||
removed when a case for that AIR is installed.
|
||||
|
||||
### Optional model proposals
|
||||
|
||||
For large private corpora, `corpus-openrouter-propose` may be used as an optional
|
||||
offline proposal source. It sends sanitized AIR to the configured OpenRouter model, so live use
|
||||
requires an explicit private-upload acknowledgement and an API key supplied only through
|
||||
`OPENROUTER_API_KEY`. Responses remain gitignored under `validation/corpus/local/proposals/` and
|
||||
are not cases or evidence. Every proposed manifest still requires AIR-specific review, mechanical
|
||||
checking, installation, and Metal qualification through the commands below; the script performs
|
||||
none of those acceptance steps.
|
||||
|
||||
The checker recomputes identities, verifies source hash and AIR metadata, rejects malformed or
|
||||
duplicate resources, and validates output bounds and product reflection. A cyclic module must use
|
||||
`execution_safety: authored_bounded` and explain which literal input or function constant gives
|
||||
every reachable loop a finite bound; `loop_free` remains mechanically checked. It never supplies
|
||||
missing facts.
|
||||
|
||||
Replacing an installed `(air_sha256, name)` slot is atomic. To remove one explicitly, including
|
||||
only that identity's observations:
|
||||
|
||||
```sh
|
||||
cargo run -p metal2vulkan-validation --bin corpus-case-check -- \
|
||||
--delete-air AIR_SHA256 --delete-name CASE_NAME
|
||||
```
|
||||
|
||||
## Contract 1: emitter stability
|
||||
|
||||
Preserve the old translator binary, build the new one, and use the smallest useful explicit
|
||||
selection:
|
||||
|
||||
```text
|
||||
metal2vulkan-ledger.jsonl # translate pins: AIR hash -> SPIR-V hash/status
|
||||
metal2vulkan-ledger-metal.jsonl # Metal oracle: plan + golden output_b64
|
||||
metal2vulkan-ledger-moltenvk.jsonl # MoltenVK candidate vs Metal golden
|
||||
metal2vulkan-ledger-vulkan.jsonl # Linux Vulkan candidate vs Metal golden, when produced
|
||||
single reproducer
|
||||
-> owned synthetic canary
|
||||
-> structurally affected private shards
|
||||
-> full background corpus
|
||||
```
|
||||
|
||||
Metal is the source of truth. Candidate runners reuse the Metal row's plan and compare their bytes
|
||||
against the Metal row's `output_b64` / `output_sha256`. A candidate cannot establish its own plan
|
||||
or golden.
|
||||
|
||||
```sh
|
||||
# macOS: establish or refresh the oracle row
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-run-metal -- \
|
||||
--air-sha256 <hash> --force --jobs 1
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-ab -- \
|
||||
--old ./m2v-old --new target/release/metal2vulkan \
|
||||
--canary --expect-no-change
|
||||
|
||||
# macOS: rerun one MoltenVK candidate row
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-run-moltenvk -- \
|
||||
--air-sha256 <hash> --force --jobs 1
|
||||
|
||||
# Linux: rerun one native Vulkan candidate row
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-run-vulkan -- \
|
||||
--air-sha256 <hash> --force --jobs 1
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-ab -- \
|
||||
--old ./m2v-old --new target/release/metal2vulkan \
|
||||
--air-list affected.txt --fail-on-unlisted-change \
|
||||
--allow-spv-change intentional.txt \
|
||||
--allow-fallback-to-success expected-new-support.txt
|
||||
```
|
||||
|
||||
For a batch over existing bad execution rows, prefer a targeted filter from `corpus-triage`:
|
||||
Selections are `--air-sha256`, `--air-list`, `--shard`, and `--canary`. Reports distinguish
|
||||
unchanged/changed SPIR-V, fallback-to-success, success-to-fallback, valid-to-invalid, and tool or
|
||||
timeout failure. Cache reuse includes the AIR hash, translator binary hash, exact options, stage,
|
||||
external validator identity, and relevant `METAL2VULKAN_*` translator environment.
|
||||
|
||||
For a behavior-preserving refactor, `--expect-no-change` is the hard gate. For intentional work,
|
||||
`--fail-on-unlisted-change` makes any drift outside the reviewed hash lists fail.
|
||||
|
||||
## Contract 2: semantic correctness
|
||||
|
||||
GPU runners accept explicit case IDs only. Metal qualification is first:
|
||||
|
||||
```sh
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-run-moltenvk -- \
|
||||
--status fallback --bucket "create compute pipeline" --jobs 1
|
||||
|
||||
# Full non-success sweep; useful late, but broad.
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-run-moltenvk -- \
|
||||
--failed-only --dry-run
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-metal -- \
|
||||
--case-id CASE --environment-id METAL_ENV
|
||||
```
|
||||
|
||||
Runners skip hashes already present in that backend ledger unless `--force` or an existing-row
|
||||
filter is set (`--failed-only`, `--status`, `--bucket`, `--contains`). `--dry-run` lists what would
|
||||
run. The parent writes a per-run delta under the OS temp dir and then rewrites the backend ledger
|
||||
once with `air_sha256` dedupe; the last row for a hash wins.
|
||||
Qualification executes the literal manifest three times. The selected bytes must be identical on
|
||||
all runs and must differ from the exact initial poison bytes throughout the selected region. The
|
||||
accepted row records case/AIR/input/output hashes, output bytes, environment identity, and exact
|
||||
oracle ABI.
|
||||
|
||||
Candidate statuses:
|
||||
|
||||
| Status | Meaning | Agent action |
|
||||
|---|---|---|
|
||||
| `ok` | exact byte match | leave it alone |
|
||||
| `tolerance` | float-like output is within recorded tolerance | accepted; leave it alone unless the policy is wrong |
|
||||
| `smoke` | legacy candidate row derived from a Metal `compare=none` bounded-smoke row | non-semantic; quarantine it and rebank Metal before candidate execution |
|
||||
| `failure` | candidate ran and produced bytes, but they do not match / exceed tolerance | inspect output class; reduce to a synthetic test when possible |
|
||||
| `fallback` | translate, bind, pipeline creation, dispatch, readback, or harness panic before comparable bytes | inspect `error`; usually a harness or executor gap |
|
||||
| `missing` | no usable Metal golden for this hash | rerun/fix `corpus-run-metal` first |
|
||||
| `quarantine` | no safe semantic Metal oracle (including loop-guarded, transformed, or historic `compare=none` work) | do not force GPU execution; improve the proof/harness or accept quarantine |
|
||||
| `timeout` | worker process exceeded `METAL2VULKAN_CORPUS_TIMEOUT_SECS` | rerun single-case with `--jobs 1`; treat persistent timeouts as harness/tool hangs |
|
||||
|
||||
Use `corpus-triage` to see the current queue:
|
||||
Candidates require a matching Metal slot and run independently:
|
||||
|
||||
```sh
|
||||
# summarize all ledgers and list the first non-success rows
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-triage
|
||||
|
||||
# group/list MoltenVK failures and print reproduction commands
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-triage -- \
|
||||
--backend moltenvk --status fallback --contains pipeline --commands
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-moltenvk -- \
|
||||
--case-id CASE --metal-environment-id METAL_ENV --environment-id MOLTENVK_ENV
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-vulkan -- \
|
||||
--case-id CASE --metal-environment-id METAL_ENV --environment-id VULKAN_ENV
|
||||
```
|
||||
|
||||
On macOS, validation's Metal oracle and MoltenVK-backed runner are machine-specific. On Linux, use
|
||||
a native Vulkan ICD. Treat execution as **layer E**, not the daily default.
|
||||
Each candidate row records the exact input, Metal output, emitted SPIR-V, backend environment, and
|
||||
executor ABI dependencies. The runner compares selected candidate bytes only with the recorded
|
||||
Metal bytes for the same case. `corpus-moltenvk` is a macOS runner; `corpus-vulkan` requires a
|
||||
native Vulkan host (currently Linux) and rejects macOS rather than relabeling MoltenVK evidence.
|
||||
|
||||
Only a Metal `status=ok`, `compare=full` row with captured output bytes is a semantic oracle.
|
||||
Bounded loop instrumentation and implicit imageblock substitution remain useful compile-only
|
||||
preflights, but the Metal runner quarantines them instead of submitting transformed work or banking
|
||||
its bytes. Candidate runners propagate that quarantine without GPU submission; they never treat a
|
||||
historic `compare=none` row as exact, tolerance, or smoke evidence.
|
||||
Direct visible-function references and function-table cases use the same commands. A direct
|
||||
reference under `visible_function_references` names the logical symbol from AIR's
|
||||
`!air.visible_function_references` metadata and the exact harvested module that defines it. Direct
|
||||
dependencies may come from a separate explicitly harvested Metal library, matching Metal's linked
|
||||
functions API. The Vulkan path recursively closes their dependency metadata, replaces every
|
||||
`.MTL_VISIBLE_FN_REF` stub with a direct call, and rejects an unresolved symbol. The checker also
|
||||
resolves each authored table slot from the hash-derived private library-module shard and proves
|
||||
same-metallib provenance before either runner starts. Metal receives all referenced `MTLFunction`
|
||||
handles through one `MTLLinkedFunctions` descriptor and creates native function tables. Intersection
|
||||
entries may instead author Metal's explicit opaque-triangle sentinel and its sorted signature
|
||||
flags; that entry uses the dedicated native opaque-triangle API and needs no library module.
|
||||
Vulkan translation specializes visible-table calls to the exact linked AIR definitions; constant
|
||||
slots become direct calls and dynamic slots become a switch over the authored population. A
|
||||
callback-bearing ray query becomes callback-free only when every possible table slot is explicitly
|
||||
opaque triangle and has the exact compositional AIR-family signature. Null slots, linked callbacks,
|
||||
and mismatches remain unsupported rather than silently losing callback semantics.
|
||||
|
||||
After a candidate audit, reconcile Metal rows that MoltenVK classified as non-comparable (or that
|
||||
have a historic candidate timeout) without resolving sources or touching the GPU:
|
||||
An intersection table nested in an AIR argument buffer is authored separately under
|
||||
`argument_buffer_intersection_function_tables` by owner buffer binding and field byte offset. The
|
||||
checker resolves that pair through product reflection; Metal writes the native table with the
|
||||
entry function's `MTLArgumentEncoder`, while Vulkan traces the corresponding constant struct-member
|
||||
load from the owner entry parameter before applying the same opaque-table specialization.
|
||||
|
||||
```sh
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-run-metal -- \
|
||||
--force --quarantine-invalid-oracles
|
||||
```
|
||||
A device buffer nested in an AIR argument buffer is authored under `argument_buffer_buffers` by
|
||||
the same owner-buffer binding and field byte offset, with ordinary input/output literal bytes. Metal
|
||||
encodes the native buffer at the reflected argument index. Vulkan allocates it with device-address
|
||||
support and writes that address into the reflected owner field; the BDA lowering then dereferences
|
||||
the identical logical resource. `argument_buffer_buffer` output selection observes writable nested
|
||||
buffers directly.
|
||||
|
||||
This is deliberately ledger-only. A later targeted preflight and remint may promote a corrected
|
||||
row; a timeout is never resubmitted merely to change its ledger status.
|
||||
Every function table declares `size` separately from `entries`. The size is the native table
|
||||
capacity; omitted indices are authored null slots, so `entries: []` honestly represents an all-null
|
||||
table without inventing a linked function. Entry indices must be unique, sorted, and smaller than
|
||||
the declared size. This distinction is semantic: AIR table-size and null-slot queries observe it.
|
||||
|
||||
Function-constant oracle rows also record the exact specialization contract. In value mode the
|
||||
Metal oracle defines only the listed FC indices and leaves every unlisted FC undefined, matching
|
||||
the candidate specialization helper and `air.is_function_constant_defined`. Required constants
|
||||
marked by the final `i1 true` in `!air.function_constants` are listed explicitly at zero unless a
|
||||
bounded-work input rule selects another value. This avoids activating optional, mutually exclusive
|
||||
AIR interface members merely because their storage value defaults to zero.
|
||||
Dependency consequences are deliberately narrow:
|
||||
|
||||
Targeted recovery of historic `compare=none` rows is deliberately two-step:
|
||||
- unchanged SPIR-V and matching dependencies reuse candidate evidence;
|
||||
- changed SPIR-V reuses matching Metal evidence and reruns affected candidates;
|
||||
- replacing a named case deletes only the old identity's observations, then requires Metal again;
|
||||
- changed Metal ABI removes only incompatible Metal slots and their downstream usability;
|
||||
- changed candidate ABI or backend environment reruns only that backend/environment slot.
|
||||
|
||||
```sh
|
||||
# Compile through Metal PSO creation without creating/submitting a command buffer. The ledger is
|
||||
# unchanged; the output list contains only structurally semantic, successfully compiled rows.
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-run-metal -- \
|
||||
--air-list selected-hashes.txt --force --preflight-only \
|
||||
--preflight-safe-list preflight-safe.txt
|
||||
## Product bug loop
|
||||
|
||||
# Only an explicit hash/list may opt historic compare=none rows into semantic reminting.
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-run-metal -- \
|
||||
--air-list preflight-safe.txt --force --remint-compare-none
|
||||
```
|
||||
1. State whether SPIR-V should change and identify the structural feature.
|
||||
2. Reproduce with one AIR or owned synthetic fixture.
|
||||
3. Add a structural synthetic regression when practical.
|
||||
4. Fix product behavior without corpus names or environment gates.
|
||||
5. Run format, clippy, and serial product tests.
|
||||
6. Run narrow A/B with unlisted drift failing, then expand to related canaries/shards.
|
||||
7. For intentional changed SPIR-V with authored cases, reuse matching Metal and rerun only affected
|
||||
candidates.
|
||||
8. Report exactly which scope was executed and which remains unaudited.
|
||||
|
||||
The preflight source gate rejects unsupported standalone ABIs, unsafe synthetic input
|
||||
configurations, CFG-analysis refusals, recursion, workgroup barriers in cyclic modules, unproven
|
||||
loops, modules with more than 64 branch terminators, and work whose conservative aggregate bound
|
||||
exceeds 50 million source-instruction visits. The branch ceiling prevents quadratic CFG analysis
|
||||
from exhausting the host before any Apple tool or GPU work is reached.
|
||||
For a proven loop it expands the reachable static call graph, applies a 257x factor per reachable
|
||||
backedge (initial visit plus at most 256 trips), and multiplies by the dispatch grid. The Metal
|
||||
oracle repeats this check against the Apple-side analysis IR immediately before command-buffer
|
||||
creation. For large private corpora, split the hash list by its existing corpus shards so each
|
||||
source-analysis process releases parser memory before the next shard; do not run several
|
||||
shard-wide Metal preflights concurrently on a memory-constrained host.
|
||||
The live corpus contains only current cases and current experiment slots. Git history, not active
|
||||
superseded rows or mutable append-only rows, preserves replacements.
|
||||
|
||||
### 7. Agent loop over ledger failures
|
||||
## Package and privacy boundary
|
||||
|
||||
An agent should not start by rerunning the whole corpus. The useful loop is:
|
||||
|
||||
1. **Pick a bucket, not a random row.**
|
||||
|
||||
```sh
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-triage -- \
|
||||
--backend moltenvk --limit 0
|
||||
```
|
||||
|
||||
Work the largest actionable bucket first: pipeline creation panics, missing Metal rows, output
|
||||
mismatches, timeouts, etc. Quarantines are a loop-budget project, not a candidate rerun project.
|
||||
|
||||
2. **Pull one reproducible hash with commands.**
|
||||
|
||||
```sh
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-triage -- \
|
||||
--backend moltenvk --status fallback --contains "create vertex validation pipeline" --commands
|
||||
```
|
||||
|
||||
3. **Diagnose translate separately from execution.**
|
||||
|
||||
```sh
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-why -- <hash>
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-run-moltenvk -- \
|
||||
--air-sha256 <hash> --force --jobs 1
|
||||
```
|
||||
|
||||
If the Metal row is missing, stale, or not `status=ok`, fix/rerun Metal before touching the
|
||||
candidate path.
|
||||
|
||||
4. **Classify the bug before editing.**
|
||||
|
||||
| Observation | Likely owner |
|
||||
|---|---|
|
||||
| `corpus-why` FALLBACKs | product translator / stage detect |
|
||||
| Metal `fallback` with oracle error | Metal harness / oracle limitation |
|
||||
| Candidate `fallback` with `vulkan execute panicked` | Vulkan/MoltenVK executor harness |
|
||||
| Candidate `failure` with output bytes | product semantics, plan mismatch, or tolerance policy |
|
||||
| Candidate `missing` | Metal ledger is absent or stale |
|
||||
| Persistent `timeout` | harness/tool hang; rerun single-case before broad changes |
|
||||
|
||||
5. **Make the smallest structural fix and add a synthetic test when it is a translator class.**
|
||||
Execution-ledger rows are evidence; CI protection still comes from owned fixtures/tests.
|
||||
|
||||
6. **Rerun the same hash, then the bucket.**
|
||||
|
||||
```sh
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-run-moltenvk -- \
|
||||
--air-sha256 <hash> --force --jobs 1
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-run-moltenvk -- \
|
||||
--status fallback --bucket "create vertex validation pipeline" --jobs 1
|
||||
```
|
||||
|
||||
`--failed-only` is the whole existing non-success queue; use it as a dry-run or late sweep, not
|
||||
as the first bucket loop.
|
||||
|
||||
7. **Commit only intentional ledger movement.**
|
||||
A single forced rerun rewrites the row for that `air_sha256` during delta merge. Review the JSONL
|
||||
diff: `fallback -> ok`, `failure -> ok`, or `failure -> tolerance` are meaningful; a changed
|
||||
`output_b64` without an explanation is not.
|
||||
|
||||
For risky reruns, work against copied ledgers:
|
||||
|
||||
```sh
|
||||
mkdir -p /tmp/m2v-ledgers
|
||||
cp validation/corpus/metal2vulkan-ledger.jsonl /tmp/m2v-ledgers/
|
||||
cp validation/corpus/metal2vulkan-ledger-metal.jsonl /tmp/m2v-ledgers/
|
||||
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-run-moltenvk -- \
|
||||
--ledger-dir /tmp/m2v-ledgers --air-sha256 <hash> --force --jobs 1
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Recipes by change type
|
||||
|
||||
### “I’m restructuring the structurizer / CFG / emitter”
|
||||
|
||||
1. Synthetic tests (**A**).
|
||||
2. Save `m2v-old`, implement, A/B (**B**).
|
||||
3. `corpus-remint --dry-run` / `corpus-remint` on public + any local pins (**C**).
|
||||
4. If you harvest: `corpus-mint` for new rows and `corpus-triage` for execution queues (**D/E**).
|
||||
5. Re-mint only if you *meant* SPIR-V to move, and say so in the commit.
|
||||
|
||||
### “I fixed one FALLBACK class”
|
||||
|
||||
1. Add a **synthetic** regression that would have failed before (so CI owns the class).
|
||||
2. Confirm the real metallib case (if you have it in a local shard) translates.
|
||||
3. Optionally bank its hashes so the fix cannot silently reverse.
|
||||
|
||||
### “I only touched docs / scripts / validation helpers”
|
||||
|
||||
Stay on **A** for the product crate; run validation package tests if you edited that crate.
|
||||
|
||||
### “I need a new public sample everyone can run”
|
||||
|
||||
1. Author a **small owned** `.ll` under `validation/fixtures/public/` (no third-party capture).
|
||||
2. Run `corpus-mint` and commit the fixture + the new `kind=synthetic` translate-ledger row.
|
||||
3. Never paste system-metallib AIR into the public tree.
|
||||
|
||||
### “Harvest is huge / slow”
|
||||
|
||||
- Full harvest is expensive because it re-carves and rewrites shard JSONL.
|
||||
- Use `--limit` / `--offset` only when batching deliberately.
|
||||
- A/B and corpus ledger tools materialize temporary `.ll` files from shard `air_ll` rows.
|
||||
|
||||
---
|
||||
|
||||
## What lives in git vs on your disk vs crates.io
|
||||
|
||||
| Artifact | Git? | crates.io? | Notes |
|
||||
|---|---|---|---|
|
||||
| Unit / synthetic tests | yes | yes (product crate) | CI backbone |
|
||||
| `src/`, `tests/` (product) | yes | yes | Published package |
|
||||
| `validation/` workspace member | yes | **no** | `publish = false` + root `exclude` |
|
||||
| `validation/fixtures/public/*.ll` | yes | **no** | Repo-only owned samples |
|
||||
| `validation/corpus/metal2vulkan-ledger.jsonl` | yes | **no** | Translate hashes only |
|
||||
| `validation/corpus/metal2vulkan-ledger-*.jsonl` | optional | **no** | Execution plans + deterministic input/output digests + `output_b64`; hash-identified, no AIR bodies |
|
||||
| `validation/corpus/local/**` | **no** | **no** | Private shard JSONL (`air_ll` + optional AIR blob) |
|
||||
| `scripts/`, `docs/` | yes | **no** | Root package `exclude` |
|
||||
| `m2v-old`, `*.spv` dumps | **no** | **no** | Local experiment debris |
|
||||
|
||||
**Rule of thumb:** if it contains Apple or app shader bodies, it stays private. Hash-identified
|
||||
translate and execution ledgers may be public **in the git repo** for reproducibility, but still are
|
||||
**not** shipped inside the `metal2vulkan` crates.io tarball (validation is a separate, non-published
|
||||
package).
|
||||
|
||||
Verify before a release:
|
||||
|
||||
```sh
|
||||
cargo package --list
|
||||
# must not list validation/, docs/, scripts/, private corpus rows, *.air, *.spv, etc.
|
||||
cargo publish --dry-run
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Tool map (where to click)
|
||||
|
||||
| Tool | Path | One-liner |
|
||||
|---|---|---|
|
||||
| Unit tests | `cargo test -p metal2vulkan` | Synthetic regressions |
|
||||
| Harvest | `corpus-harvest` | System metallib → shard JSONL |
|
||||
| `corpus-mint` | validation bin | Append new translate `air_sha256` pins |
|
||||
| `corpus-remint` | validation bin | Re-translate existing pins (`--failed-only`) |
|
||||
| `corpus-why` | validation bin | One `air_sha256` → translate error string |
|
||||
| `corpus-run-metal` | validation bin | Metal oracle → plan + golden `output_b64` + digests |
|
||||
| `corpus-run-vulkan` | validation bin | Linux Vulkan vs metal golden |
|
||||
| `corpus-run-moltenvk` | validation bin | MoltenVK vs metal golden |
|
||||
| `corpus-triage` | validation bin | Summarize ledgers and print failure rerun commands |
|
||||
| Byte A/B | `scripts/metal2vulkan-ab/` | Two binaries, one sample |
|
||||
| AIR carve | `scripts/mtlb-extract/` | Low-level MTLB → `.air` |
|
||||
| SPIR-V delta class | `spirv_delta` validation bin | Classify id/order vs semantic delta |
|
||||
| Pipeline probe | `spirv_pipeline_probe` | Module + pipeline create |
|
||||
| Oracle / runner | `validation` lib | Execution experiments |
|
||||
|
||||
---
|
||||
|
||||
## Interpreting outcomes
|
||||
|
||||
| Symptom | Likely story | Next move |
|
||||
|---|---|---|
|
||||
| Unit red | You broke a structural case | Fix or update the synthetic test honestly |
|
||||
| A/B `DIFFERS` | SPIR-V bytes moved | Revert, or re-mint if intentional |
|
||||
| A/B `NEW-ONLY` / `OLD-ONLY` | One side FALLBACKs | Investigate emit path / stage detect |
|
||||
| Corpus mass FAIL | Broad emit regression | Bisect; do not name-key harvest cases |
|
||||
| Corpus sparse FAIL | Narrow class | Reduce to synthetic `.ll`, land unit test |
|
||||
| spirv-val fail after translate | Invalid module | Prefer honest FALLBACK over wrong SPIR-V |
|
||||
|
||||
---
|
||||
|
||||
## Design rules that keep the ladder honest
|
||||
|
||||
1. **Structure over names** — never branch the translator on a harvested function name.
|
||||
2. **Synthetic first for CI** — private harvest is for *you*; public regression is for *everyone*.
|
||||
3. **Honest FALLBACK** — unsupported is better than wrong-but-valid SPIR-V.
|
||||
4. **Re-mint is a product decision** — changing thousands of hashes without explanation is how
|
||||
regressions hide.
|
||||
5. **Match the ladder to the claim** — “no SPIR-V change on my machine” is only as strong as the
|
||||
sample you actually ran.
|
||||
|
||||
---
|
||||
|
||||
## Minimal cheat sheet
|
||||
|
||||
```sh
|
||||
# Always
|
||||
cargo test -p metal2vulkan -- --test-threads=1
|
||||
|
||||
# Before a scary refactor
|
||||
cargo build --release --bin metal2vulkan && cp target/release/metal2vulkan ./m2v-old
|
||||
|
||||
# After
|
||||
cargo build --release --bin metal2vulkan
|
||||
scripts/metal2vulkan-ab/metal2vulkan-ab.sh --old ./m2v-old
|
||||
|
||||
# Once per machine (macOS): fat private sample
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-harvest
|
||||
cargo run -p metal2vulkan-validation --release --bin corpus-mint
|
||||
# optional execution goldens (see plan.md / validation/README.md)
|
||||
# cargo run -p metal2vulkan-validation --release --bin corpus-run-metal
|
||||
# cargo run -p metal2vulkan-validation --release --bin corpus-run-vulkan
|
||||
```
|
||||
|
||||
Corpus ledger CLIs (full flag list and pipeline): [`validation/README.md`](../validation/README.md),
|
||||
[`validation/corpus/README.md`](../validation/corpus/README.md), [`plan.md`](../plan.md).
|
||||
|
||||
When the ladder is green at the height you chose, ship the refactor. When it is not, the failure
|
||||
is a gift: it named a class before a user did.
|
||||
The published product crate excludes `validation/`, docs, scripts, captures, and private sources.
|
||||
Committed validation artifacts are owned synthetic fixtures, authored manifests, and
|
||||
hash-identified observations. Never commit `validation/corpus/local/`, `.index.sqlite`, metallibs,
|
||||
AIR blobs, SPIR-V dumps, or third-party shader bodies.
|
||||
@@ -1,38 +1,66 @@
|
||||
//! Fast iteration harness: translate a sanitized AIR .ll through the native emitter and spirv-val.
|
||||
//! Fast iteration harness: translate sanitized AIR `.ll` through the native emitter and spirv-val.
|
||||
//! Usage: cargo run -q --example translate_native -- <in.ll> [kernel|fragment|vertex] [out.spv]
|
||||
use metal2vulkan::passes::Stage;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
fn main() {
|
||||
if let Err(error) = run() {
|
||||
eprintln!("FALLBACK: {error}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
fn run() -> Result<(), String> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let path = args
|
||||
.next()
|
||||
.expect("usage: translate_native <in.ll> [stage] [out.spv]");
|
||||
let path = args.next().ok_or_else(|| {
|
||||
"usage: translate_native <in.ll> [kernel|fragment|vertex] [out.spv]".to_string()
|
||||
})?;
|
||||
let stage = match args.next().as_deref() {
|
||||
Some("fragment") => Stage::Fragment,
|
||||
Some("vertex") => Stage::Vertex,
|
||||
_ => Stage::Kernel,
|
||||
Some("kernel") | None => Stage::Kernel,
|
||||
Some(other) => return Err(format!("unsupported stage {other:?}")),
|
||||
};
|
||||
let out = args.next();
|
||||
let san_ll = std::fs::read_to_string(&path).expect("read input");
|
||||
let tmp = std::env::temp_dir().join(format!("translate_native_{}", std::process::id()));
|
||||
std::fs::create_dir_all(&tmp).unwrap();
|
||||
match metal2vulkan::translate_sanitized_native(&san_ll, stage, &tmp) {
|
||||
Err(e) => {
|
||||
eprintln!("FALLBACK: {e}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
Ok(spv) => {
|
||||
if let Some(out) = &out {
|
||||
std::fs::write(out, &spv).unwrap();
|
||||
}
|
||||
match metal2vulkan::tools::spirv_val_bytes(&spv, &tmp) {
|
||||
Ok(()) => println!("PASS spirv-val ({} bytes)", spv.len()),
|
||||
Err(e) => {
|
||||
eprintln!("INVALID-SPIRV: {e}");
|
||||
std::process::exit(3);
|
||||
}
|
||||
}
|
||||
}
|
||||
if args.next().is_some() {
|
||||
return Err("too many arguments".to_string());
|
||||
}
|
||||
|
||||
let san_ll = std::fs::read_to_string(&path).map_err(|error| format!("read {path}: {error}"))?;
|
||||
let scratch = ScratchDir::new("translate-native")?;
|
||||
let spv = metal2vulkan::translate_sanitized_native(&san_ll, stage, scratch.path())?;
|
||||
if let Some(out) = &out {
|
||||
std::fs::write(out, &spv).map_err(|error| format!("write {out}: {error}"))?;
|
||||
}
|
||||
println!("PASS spirv-val ({} bytes)", spv.len());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct ScratchDir(PathBuf);
|
||||
|
||||
impl ScratchDir {
|
||||
fn new(label: &str) -> Result<Self, String> {
|
||||
let nonce = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(|error| format!("clock error: {error}"))?
|
||||
.as_nanos();
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"metal2vulkan-{label}-{}-{nonce}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::create_dir(&path)
|
||||
.map_err(|error| format!("create scratch {}: {error}", path.display()))?;
|
||||
Ok(Self(path))
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ScratchDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&tmp);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//! Translate AIR or LLVM IR and write both validated SPIR-V and reflection JSON.
|
||||
//!
|
||||
//! Usage:
|
||||
//! cargo run --features serde --example translate_reflected -- \
|
||||
//! <in.air|in.ll> <out.spv> <out.json> [auto|kernel|fragment|vertex]
|
||||
|
||||
use metal2vulkan::passes::Stage;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
fn main() {
|
||||
if let Err(error) = run() {
|
||||
eprintln!("FALLBACK: {error}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
fn run() -> Result<(), String> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let input = args.next().ok_or_else(usage)?;
|
||||
let spv_path = args.next().ok_or_else(usage)?;
|
||||
let reflection_path = args.next().ok_or_else(usage)?;
|
||||
let requested_stage = args.next().unwrap_or_else(|| "auto".to_string());
|
||||
if args.next().is_some() {
|
||||
return Err(usage());
|
||||
}
|
||||
|
||||
let scratch = ScratchDir::new("translate-reflected")?;
|
||||
let stage = match requested_stage.as_str() {
|
||||
"auto" => metal2vulkan::detect_stage(&input, scratch.path())?,
|
||||
"kernel" | "compute" => Stage::Kernel,
|
||||
"fragment" => Stage::Fragment,
|
||||
"vertex" => Stage::Vertex,
|
||||
other => return Err(format!("unsupported stage {other:?}; {}", usage())),
|
||||
};
|
||||
let (spv, reflection) = metal2vulkan::translate_reflected(&input, stage, scratch.path())?;
|
||||
let json = serde_json::to_vec_pretty(&reflection)
|
||||
.map_err(|error| format!("serialize reflection: {error}"))?;
|
||||
|
||||
std::fs::write(&spv_path, &spv).map_err(|error| format!("write {spv_path}: {error}"))?;
|
||||
std::fs::write(&reflection_path, json)
|
||||
.map_err(|error| format!("write {reflection_path}: {error}"))?;
|
||||
println!(
|
||||
"PASS: wrote {} SPIR-V bytes and reflection schema v{}",
|
||||
spv.len(),
|
||||
reflection.reflection_version
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn usage() -> String {
|
||||
"usage: translate_reflected <in.air|in.ll> <out.spv> <out.json> \
|
||||
[auto|kernel|fragment|vertex]"
|
||||
.to_string()
|
||||
}
|
||||
|
||||
struct ScratchDir(PathBuf);
|
||||
|
||||
impl ScratchDir {
|
||||
fn new(label: &str) -> Result<Self, String> {
|
||||
let nonce = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(|error| format!("clock error: {error}"))?
|
||||
.as_nanos();
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"metal2vulkan-{label}-{}-{nonce}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::create_dir(&path)
|
||||
.map_err(|error| format!("create scratch {}: {error}", path.display()))?;
|
||||
Ok(Self(path))
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ScratchDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
# metal2vulkan-ab — byte-A/B translation harness
|
||||
|
||||
Translates a pinned sample set with two `metal2vulkan` binaries and diffs the emitted SPIR-V
|
||||
**byte-for-byte**, so a behavior-preserving refactor can be proven not to move any output on the
|
||||
sample before more expensive checks.
|
||||
|
||||
## Why byte comparison is meaningful
|
||||
|
||||
The emitter's output is id-canonicalized by `passes::canonicalize_ids`, so equal semantics ⇒ equal
|
||||
bytes for the vast majority of cases. If a case stays nondeterministic across runs, fall back to a
|
||||
semantic or validator gate rather than trusting the byte diff alone.
|
||||
|
||||
The CLI writes `out.spv` *before* running spirv-val, so a case that FALLBACKs at the spirv-val step
|
||||
still produces comparable bytes. A case whose `translate()` errors writes no file and is reported as
|
||||
a translate failure, not a diff.
|
||||
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
# self-test: HEAD vs HEAD (exit 0 when every case is IDENTICAL or BOTH-FAIL)
|
||||
./metal2vulkan-ab.sh
|
||||
|
||||
# real A/B: build the crate before your change and after, then diff
|
||||
git stash # or check out the parent commit
|
||||
cargo build --release --bin metal2vulkan
|
||||
cp target/release/metal2vulkan ./m2v-old
|
||||
git stash pop
|
||||
./metal2vulkan-ab.sh --old ./m2v-old
|
||||
|
||||
# optional extra shaders after --
|
||||
./metal2vulkan-ab.sh --old ./m2v-old -- path/to/case.ll
|
||||
```
|
||||
|
||||
Flags:
|
||||
|
||||
- `--old PATH` — "before" binary. Default: build `--release` from this checkout.
|
||||
- `--new PATH` — "after" binary. Default: same as `--old` (a self-test).
|
||||
- `--quiet` — print only the summary and any regressions.
|
||||
- `-- file…` — additional `.ll` / `.air` inputs to include in the sample.
|
||||
|
||||
Because `--new` defaults to `--old`, an explicit A/B run is usually: pass the pre-change binary as
|
||||
`--old` and let `--new` build the current tree, **or** pass both explicitly.
|
||||
|
||||
## Sample set
|
||||
|
||||
1. Every `*.air` / `*.ll` under `tests/fixtures/**` when that directory exists (gitignored).
|
||||
2. Every `*.air` / `*.ll` under `validation/fixtures/public/**` (committed synthetic samples).
|
||||
3. Every `air_ll` row under `validation/corpus/local/shards/shard_*.jsonl` (gitignored private harvest).
|
||||
4. Any paths listed after `--`.
|
||||
|
||||
Shard rows materialize temporary `.ll` files under the script work directory and are removed when
|
||||
the run exits.
|
||||
|
||||
This public tree does not ship third-party captured shaders. For cross-version hash pins (without
|
||||
keeping two binaries around), bank with `corpus-mint` / `corpus-remint` (and optional
|
||||
`corpus-run-*` execution ledgers) — see [`validation/corpus/README.md`](../../validation/corpus/README.md)
|
||||
and [`plan.md`](../../plan.md).
|
||||
|
||||
## Output
|
||||
|
||||
Per-case verdicts (`IDENTICAL` / `DIFFERS` / `OLD-ONLY` / `NEW-ONLY` / `BOTH-FAIL`) plus a summary
|
||||
line. Exit status is `0` only when there are **no** `DIFFERS` and no asymmetric cases; any byte
|
||||
divergence exits `1`. `BOTH-FAIL` (both binaries FALLBACK identically) is not a regression.
|
||||
@@ -1,194 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# metal2vulkan byte-A/B harness.
|
||||
#
|
||||
# Translate a pinned sample set with two `metal2vulkan` binaries and diff the emitted SPIR-V
|
||||
# byte-for-byte, reporting per-case identical / differs / asymmetric. This is a cheap gate for
|
||||
# behavior-preserving refactors: build the crate before a change (old) and after (new), run this,
|
||||
# and demand zero diffs on the sample.
|
||||
#
|
||||
# Sample set:
|
||||
# * every `*.air` / `*.ll` under `tests/fixtures/**`, when present
|
||||
# * every path passed after `--` on the command line
|
||||
#
|
||||
# The `metal2vulkan` CLI writes `out.spv` *before* running spirv-val, so a case that FALLBACKs on
|
||||
# spirv-val still yields comparable bytes; a case whose translate() errors produces no file and is
|
||||
# reported as a translate failure (not a diff).
|
||||
#
|
||||
# Exit status: 0 when no case DIFFERS and no case is asymmetric (one binary produced output, the
|
||||
# other did not); nonzero otherwise. A HEAD-vs-HEAD self-test therefore exits 0.
|
||||
#
|
||||
# Usage:
|
||||
# metal2vulkan-ab.sh [--old PATH] [--new PATH] [--quiet] [-- file.ll ...]
|
||||
#
|
||||
# --old PATH "before" binary. Default: build `--release` from this checkout.
|
||||
# --new PATH "after" binary. Default: same as --old (a self-test: everything must be IDENTICAL).
|
||||
# --quiet print only the summary, not per-case lines.
|
||||
#
|
||||
set -euo pipefail
|
||||
|
||||
CRATE_DIR="$(cd -- "$(dirname -- "$0")/../.." && pwd)"
|
||||
|
||||
OLD_BIN=""
|
||||
NEW_BIN=""
|
||||
QUIET=0
|
||||
EXTRA_SRCS=()
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--old) OLD_BIN="$2"; shift 2 ;;
|
||||
--new) NEW_BIN="$2"; shift 2 ;;
|
||||
--quiet) QUIET=1; shift ;;
|
||||
-h|--help) sed -n '2,30p' "$0"; exit 0 ;;
|
||||
--) shift; EXTRA_SRCS+=("$@"); break ;;
|
||||
*) echo "unknown arg: $1" >&2; exit 64 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [ -z "$OLD_BIN" ]; then
|
||||
echo "# building release metal2vulkan (old = new = HEAD self-test)..." >&2
|
||||
( cd "$CRATE_DIR" && cargo build --release --bin metal2vulkan >&2 )
|
||||
OLD_BIN="$CRATE_DIR/target/release/metal2vulkan"
|
||||
fi
|
||||
[ -z "$NEW_BIN" ] && NEW_BIN="$OLD_BIN"
|
||||
|
||||
for b in "$OLD_BIN" "$NEW_BIN"; do
|
||||
[ -x "$b" ] || { echo "not an executable: $b" >&2; exit 64; }
|
||||
done
|
||||
|
||||
WORK="$(mktemp -d)"
|
||||
trap 'rm -rf "$WORK"' EXIT
|
||||
|
||||
# translate SRC with BIN into DST.spv; echo "ok" if the file was produced, "fail" otherwise.
|
||||
translate() {
|
||||
local bin="$1" src="$2" dst="$3"
|
||||
rm -f "$dst"
|
||||
# --stage auto is the CLI default; spirv-val failure is fine, the .spv is already on disk.
|
||||
"$bin" "$src" "$dst" --stage auto >/dev/null 2>&1 || true
|
||||
if [ -s "$dst" ]; then echo ok; else echo fail; fi
|
||||
}
|
||||
|
||||
n_identical=0; n_differs=0; n_asym=0; n_bothfail=0
|
||||
report() {
|
||||
local name="$1" verdict="$2"
|
||||
case "$verdict" in
|
||||
IDENTICAL) n_identical=$((n_identical+1)) ;;
|
||||
DIFFERS) n_differs=$((n_differs+1)) ;;
|
||||
OLD-ONLY|NEW-ONLY) n_asym=$((n_asym+1)) ;;
|
||||
BOTH-FAIL) n_bothfail=$((n_bothfail+1)) ;;
|
||||
esac
|
||||
if [ "$QUIET" -eq 0 ] || [ "$verdict" = DIFFERS ] || [ "$verdict" = OLD-ONLY ] || [ "$verdict" = NEW-ONLY ]; then
|
||||
printf ' %-10s %s\n' "$verdict" "$name"
|
||||
fi
|
||||
}
|
||||
|
||||
compare_case() {
|
||||
local name="$1" src="$2"
|
||||
local o="$WORK/old.spv" n="$WORK/new.spv"
|
||||
local ostat nstat
|
||||
ostat="$(translate "$OLD_BIN" "$src" "$o")"
|
||||
nstat="$(translate "$NEW_BIN" "$src" "$n")"
|
||||
if [ "$ostat" = ok ] && [ "$nstat" = ok ]; then
|
||||
if cmp -s "$o" "$n"; then report "$name" IDENTICAL; else report "$name" DIFFERS; fi
|
||||
elif [ "$ostat" = ok ]; then report "$name" OLD-ONLY
|
||||
elif [ "$nstat" = ok ]; then report "$name" NEW-ONLY
|
||||
else report "$name" BOTH-FAIL
|
||||
fi
|
||||
}
|
||||
|
||||
echo "# old: $OLD_BIN"
|
||||
echo "# new: $NEW_BIN"
|
||||
|
||||
# List .ll/.air under root, preferring stem.ll when stem.air is also present (harvest pairs).
|
||||
list_sources() {
|
||||
local root="$1"
|
||||
# Print paths: for each (dir,stem) keep .ll over .air.
|
||||
find "$root" \( -name '*.air' -o -name '*.ll' \) -type f | sort | python3 -c '
|
||||
import sys
|
||||
from pathlib import Path
|
||||
best = {}
|
||||
for line in sys.stdin:
|
||||
p = Path(line.strip())
|
||||
if not p.is_file():
|
||||
continue
|
||||
key = (str(p.parent.resolve()), p.stem)
|
||||
prev = best.get(key)
|
||||
if prev is None or (p.suffix == ".ll" and Path(prev).suffix == ".air"):
|
||||
best[key] = str(p)
|
||||
for path in sorted(best.values()):
|
||||
print(path)
|
||||
'
|
||||
}
|
||||
|
||||
scan_tree() {
|
||||
local root="$1" tag="$2"
|
||||
if [ -d "$root" ]; then
|
||||
echo "# $tag:"
|
||||
while IFS= read -r src; do
|
||||
[ -n "$src" ] || continue
|
||||
compare_case "${tag}:${src#"$root"/}" "$src"
|
||||
done < <(list_sources "$root")
|
||||
else
|
||||
echo "# $tag: skipped (not present)"
|
||||
fi
|
||||
}
|
||||
|
||||
# Sample set (all optional except explicit -- paths):
|
||||
# 1) tests/fixtures/** — private local fixtures
|
||||
# 2) validation/fixtures/public/** — committed synthetic samples
|
||||
# 3) validation/corpus/local/shards/*.jsonl — gitignored mined AIR rows
|
||||
scan_tree "$CRATE_DIR/tests/fixtures" "fixture"
|
||||
scan_tree "$CRATE_DIR/validation/fixtures/public" "public"
|
||||
|
||||
scan_shards() {
|
||||
local shard_root="$1" tag="$2"
|
||||
if [ ! -d "$shard_root" ]; then
|
||||
echo "# $tag: skipped (not present)"
|
||||
return
|
||||
fi
|
||||
echo "# $tag:"
|
||||
local extracted="$WORK/$tag"
|
||||
mkdir -p "$extracted"
|
||||
python3 - "$shard_root" "$extracted" <<'PY' | while IFS=$'\t' read -r name src; do
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
shard_root = Path(sys.argv[1])
|
||||
out_root = Path(sys.argv[2])
|
||||
for shard in sorted(shard_root.glob("shard_*.jsonl")):
|
||||
shard_name = shard.name
|
||||
with shard.open("r", encoding="utf-8", errors="replace") as f:
|
||||
for line_no, line in enumerate(f, 1):
|
||||
if not line.strip() or line.startswith("#"):
|
||||
continue
|
||||
row = json.loads(line)
|
||||
air = row.get("air_ll") or ""
|
||||
sha = (row.get("air_sha256") or "").lower()
|
||||
if not air or not sha:
|
||||
continue
|
||||
path = out_root / f"{sha}.ll"
|
||||
path.write_text(air, encoding="utf-8")
|
||||
label = row.get("label") or f"{shard_name}:{line_no}"
|
||||
print(f"{label}\t{path}")
|
||||
PY
|
||||
[ -n "$src" ] || continue
|
||||
compare_case "$tag:$name" "$src"
|
||||
done
|
||||
}
|
||||
|
||||
scan_shards "$CRATE_DIR/validation/corpus/local/shards" "local-shards"
|
||||
|
||||
if [ "${#EXTRA_SRCS[@]}" -gt 0 ]; then
|
||||
echo "# extra inputs:"
|
||||
for src in "${EXTRA_SRCS[@]}"; do
|
||||
compare_case "input:$(basename "$src")" "$src"
|
||||
done
|
||||
fi
|
||||
|
||||
echo "# summary: identical=$n_identical differs=$n_differs asymmetric=$n_asym both-fail=$n_bothfail"
|
||||
if [ "$n_differs" -gt 0 ] || [ "$n_asym" -gt 0 ]; then
|
||||
echo "# RESULT: REGRESSION (byte divergence detected)"
|
||||
exit 1
|
||||
fi
|
||||
echo "# RESULT: clean (no byte divergence)"
|
||||
@@ -25,6 +25,10 @@ Hand-written crate code (`parser.rs`, `decoder.rs`, `grammar.rs`, …) is not to
|
||||
Override with `RSPIRV_REF` / `HEADERS_REF` if you deliberately bump both together with
|
||||
`Cargo.toml`'s `spirv` dependency.
|
||||
|
||||
The script caches both repositories under `.cache/rspirv-autogen`. Set
|
||||
`METAL2VULKAN_AUTOGEN_CACHE` to use a different cache directory. It requires `git`, `cargo`,
|
||||
`rustfmt`, and Python 3, and requires network access when fetching missing revisions.
|
||||
|
||||
## Run
|
||||
|
||||
```sh
|
||||
@@ -32,6 +36,9 @@ Override with `RSPIRV_REF` / `HEADERS_REF` if you deliberately bump both togethe
|
||||
cargo test -p metal2vulkan --lib spirv_module -- --test-threads=1
|
||||
```
|
||||
|
||||
The script runs `cargo fmt --all`. Review every generated diff and update the `spirv` dependency and
|
||||
locked revisions together.
|
||||
|
||||
## Provenance
|
||||
|
||||
- **Source of truth:** Khronos `spirv.core.grammar.json` (SPIRV-Headers).
|
||||
|
||||
@@ -0,0 +1,671 @@
|
||||
//! Canonical recognition contract for Metal AIR intrinsic symbols.
|
||||
//!
|
||||
//! Translation validates operand and result shapes in the lowering that owns each family. This
|
||||
//! module answers the earlier, narrower question: whether a symbol belongs to an AIR ABI family for
|
||||
//! which the product has an intentional lowering or static-linkage contract. Validation uses the
|
||||
//! same inventory, so a newly harvested `air.*` family cannot disappear behind an unrelated clean
|
||||
//! authored-resource audit.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Where the product intentionally handles an AIR intrinsic family.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum AirIntrinsicDisposition {
|
||||
/// The native emitter or retained-SPIR-V passes lower this family directly.
|
||||
Lowered,
|
||||
/// Translation consumes this family only after the caller supplies exact authored linkage.
|
||||
StaticLinkage,
|
||||
/// Some exact ABI shapes lower directly while callback-bearing shapes require static linkage.
|
||||
LoweredOrStaticLinkage,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum Matrix16Element {
|
||||
F32,
|
||||
F16,
|
||||
Bf16,
|
||||
F8E4M3,
|
||||
F8E4M3Fn,
|
||||
F8E5M2,
|
||||
I8 { signed: bool },
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) struct Matrix16Intrinsic {
|
||||
pub lhs: Matrix16Element,
|
||||
pub rhs: Matrix16Element,
|
||||
pub integer: bool,
|
||||
}
|
||||
|
||||
/// Parse the complete stable 16x16x16 matrix ABI grammar shared by inventory and lowering.
|
||||
pub(crate) fn matrix16_intrinsic(name: &str) -> Option<Matrix16Intrinsic> {
|
||||
let fields: Vec<_> = name.split('.').collect();
|
||||
if fields.len() != 8 || fields[0] != "air" {
|
||||
return None;
|
||||
}
|
||||
match fields[1] {
|
||||
"simdgroup_matrix_16x16x16_multiply_accumulate"
|
||||
if fields[2] == "f"
|
||||
&& fields[3] == "f"
|
||||
&& fields[4] == "v8f32"
|
||||
&& fields[7] == "v8f32" =>
|
||||
{
|
||||
Some(Matrix16Intrinsic {
|
||||
lhs: matrix16_float_element(fields[5])?,
|
||||
rhs: matrix16_float_element(fields[6])?,
|
||||
integer: false,
|
||||
})
|
||||
}
|
||||
"simdgroup_matrix_16x16x16_widening_multiply_accumulate"
|
||||
if matches!(fields[2], "s" | "u")
|
||||
&& matches!(fields[3], "s" | "u")
|
||||
&& fields[4] == "v8i32"
|
||||
&& fields[5] == "v8i8"
|
||||
&& fields[6] == "v8i8"
|
||||
&& fields[7] == "v8i32" =>
|
||||
{
|
||||
Some(Matrix16Intrinsic {
|
||||
lhs: Matrix16Element::I8 {
|
||||
signed: fields[2] == "s",
|
||||
},
|
||||
rhs: Matrix16Element::I8 {
|
||||
signed: fields[3] == "s",
|
||||
},
|
||||
integer: true,
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn matrix16_float_element(token: &str) -> Option<Matrix16Element> {
|
||||
Some(match token {
|
||||
"v8f32" => Matrix16Element::F32,
|
||||
"v8f16" => Matrix16Element::F16,
|
||||
"v8bf16" => Matrix16Element::Bf16,
|
||||
"v8f8e4m3" => Matrix16Element::F8E4M3,
|
||||
"v8f8e4m3fn" => Matrix16Element::F8E4M3Fn,
|
||||
"v8f8e5m2" => Matrix16Element::F8E5M2,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Count AIR calls in sanitized LLVM IR by exact ABI symbol.
|
||||
///
|
||||
/// Declarations are not uses. The scan accepts ordinary, tail, musttail, and notail calls and counts
|
||||
/// every `@air.*` callee on the instruction line, matching the translator's call-oriented contract.
|
||||
pub fn air_call_counts(ll: &str) -> BTreeMap<String, usize> {
|
||||
let mut calls = BTreeMap::new();
|
||||
for line in ll.lines() {
|
||||
for symbol in direct_air_callees(line) {
|
||||
*calls.entry(symbol).or_default() += 1;
|
||||
}
|
||||
}
|
||||
calls
|
||||
}
|
||||
|
||||
fn direct_air_callees(line: &str) -> Vec<String> {
|
||||
if ![
|
||||
"call ", "call\t", "invoke ", "invoke\t", "callbr ", "callbr\t",
|
||||
]
|
||||
.iter()
|
||||
.any(|opcode| line.contains(opcode))
|
||||
{
|
||||
return Vec::new();
|
||||
}
|
||||
let line = if line.contains(';') {
|
||||
strip_llvm_comment(line)
|
||||
} else {
|
||||
line
|
||||
}
|
||||
.trim();
|
||||
call_opcode_ends(line)
|
||||
.into_iter()
|
||||
.filter_map(|offset| direct_air_callee_after(&line[offset..]))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn call_opcode_ends(line: &str) -> Vec<usize> {
|
||||
const OPCODES: [&str; 6] = [
|
||||
"call ", "call\t", "invoke ", "invoke\t", "callbr ", "callbr\t",
|
||||
];
|
||||
let mut offsets = Vec::new();
|
||||
let mut cursor = 0usize;
|
||||
while cursor < line.len() {
|
||||
let Some((start, opcode)) = OPCODES
|
||||
.iter()
|
||||
.filter_map(|opcode| line[cursor..].find(opcode).map(|at| (cursor + at, *opcode)))
|
||||
.min_by_key(|(at, _)| *at)
|
||||
else {
|
||||
break;
|
||||
};
|
||||
let before = line[..start].chars().next_back();
|
||||
let opcode_context =
|
||||
before.is_none_or(|ch| ch.is_whitespace() || matches!(ch, '=' | '{' | '}' | ';'));
|
||||
if opcode_context && !quoted_at(line, start) {
|
||||
offsets.push(start + opcode.len());
|
||||
}
|
||||
cursor = start + 1;
|
||||
}
|
||||
offsets
|
||||
}
|
||||
|
||||
fn quoted_at(line: &str, offset: usize) -> bool {
|
||||
if !line[..offset].contains('"') {
|
||||
return false;
|
||||
}
|
||||
let mut quoted = false;
|
||||
let mut escaped = false;
|
||||
for ch in line[..offset].chars() {
|
||||
if quoted && ch == '\\' && !escaped {
|
||||
escaped = true;
|
||||
continue;
|
||||
}
|
||||
if ch == '"' && !escaped {
|
||||
quoted = !quoted;
|
||||
}
|
||||
escaped = false;
|
||||
}
|
||||
quoted
|
||||
}
|
||||
|
||||
fn direct_air_callee_after(call: &str) -> Option<String> {
|
||||
let mut depth = 0usize;
|
||||
let mut quoted = false;
|
||||
let mut escaped = false;
|
||||
let mut at = None;
|
||||
for (offset, ch) in call.char_indices() {
|
||||
if quoted && ch == '\\' && !escaped {
|
||||
escaped = true;
|
||||
continue;
|
||||
}
|
||||
if ch == '"' && !escaped {
|
||||
quoted = !quoted;
|
||||
} else if !quoted {
|
||||
match ch {
|
||||
'(' => depth += 1,
|
||||
')' => depth = depth.saturating_sub(1),
|
||||
'@' if depth == 0 => {
|
||||
at = Some(offset);
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
escaped = false;
|
||||
}
|
||||
let symbol = &call[at? + 1..];
|
||||
if let Some(quoted) = symbol.strip_prefix('"') {
|
||||
let end = quoted.find('"')?;
|
||||
return quoted[..end]
|
||||
.starts_with("air.")
|
||||
.then(|| quoted[..end].to_string());
|
||||
}
|
||||
let end = symbol
|
||||
.find(|ch: char| !(ch.is_ascii_alphanumeric() || matches!(ch, '_' | '.')))
|
||||
.unwrap_or(symbol.len());
|
||||
(end > "air.".len() && symbol.starts_with("air.")).then(|| symbol[..end].to_string())
|
||||
}
|
||||
|
||||
fn strip_llvm_comment(line: &str) -> &str {
|
||||
let mut quoted = false;
|
||||
let mut escaped = false;
|
||||
for (offset, ch) in line.char_indices() {
|
||||
if quoted && ch == '\\' && !escaped {
|
||||
escaped = true;
|
||||
continue;
|
||||
}
|
||||
if ch == '"' && !escaped {
|
||||
quoted = !quoted;
|
||||
} else if ch == ';' && !quoted {
|
||||
return &line[..offset];
|
||||
}
|
||||
escaped = false;
|
||||
}
|
||||
line
|
||||
}
|
||||
|
||||
/// Count every called AIR symbol outside the product's intentional family contract.
|
||||
pub fn unrecognized_air_intrinsics(ll: &str) -> BTreeMap<String, usize> {
|
||||
unrecognized_air_intrinsics_from_counts(&air_call_counts(ll))
|
||||
}
|
||||
|
||||
/// Filter an existing exact call inventory through the product's intentional family contract.
|
||||
///
|
||||
/// Classification uses this form so inventory reporting and unknown-family reporting consume the
|
||||
/// same parse rather than independently scanning a potentially large AIR module.
|
||||
pub fn unrecognized_air_intrinsics_from_counts(
|
||||
calls: &BTreeMap<String, usize>,
|
||||
) -> BTreeMap<String, usize> {
|
||||
calls
|
||||
.iter()
|
||||
.filter(|(name, _)| air_intrinsic_disposition(name).is_none())
|
||||
.map(|(name, count)| (name.clone(), *count))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn typed(name: &str, stem: &str) -> bool {
|
||||
name == stem
|
||||
|| name
|
||||
.strip_prefix(stem)
|
||||
.is_some_and(|tail| tail.starts_with('.'))
|
||||
}
|
||||
|
||||
fn any_typed(name: &str, stems: &[&str]) -> bool {
|
||||
stems.iter().any(|stem| typed(name, stem))
|
||||
}
|
||||
|
||||
fn any_prefix(name: &str, prefixes: &[&str]) -> bool {
|
||||
prefixes.iter().any(|prefix| name.starts_with(prefix))
|
||||
}
|
||||
|
||||
pub(crate) fn is_command_encoder_helper(name: &str) -> bool {
|
||||
matches!(
|
||||
name,
|
||||
"air.concurrent_dispatch_threadgroups_compute_command"
|
||||
| "air.concurrent_dispatch_threads_compute_command"
|
||||
| "air.draw_primitives_render_command"
|
||||
| "air.set_barrier_compute_command"
|
||||
| "air.set_pipeline_state_compute_command"
|
||||
| "air.set_threadgroup_memory_length_compute_command"
|
||||
) || any_typed(
|
||||
name,
|
||||
&[
|
||||
"air.set_fragment_buffer_render_command",
|
||||
"air.set_kernel_buffer_compute_command",
|
||||
"air.set_object_buffer_render_command",
|
||||
"air.set_vertex_buffer_render_command",
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// Return the product contract for one complete `air.*` ABI symbol.
|
||||
///
|
||||
/// Broad namespaces such as `air.simdgroup_matrix_` are deliberately not accepted. Every admitted
|
||||
/// prefix corresponds to a concrete dispatch arm, so a new sibling family remains visible until
|
||||
/// its implementation and this contract are added together.
|
||||
pub fn air_intrinsic_disposition(name: &str) -> Option<AirIntrinsicDisposition> {
|
||||
use AirIntrinsicDisposition::{Lowered, LoweredOrStaticLinkage, StaticLinkage};
|
||||
|
||||
if !name.starts_with("air.") {
|
||||
return None;
|
||||
}
|
||||
|
||||
if name.starts_with("air.intersect.") {
|
||||
return Some(LoweredOrStaticLinkage);
|
||||
}
|
||||
|
||||
if any_prefix(
|
||||
name,
|
||||
&[
|
||||
"air.set_buffer_intersection_function_table.",
|
||||
"air.set_intersection_function_table.",
|
||||
],
|
||||
) || matches!(
|
||||
name,
|
||||
"air.get_null_intersection_function_table"
|
||||
| "air.get_size_visible_function_table"
|
||||
| "air.get_function_pointer_visible_function_table"
|
||||
| "air.is_null_visible_function_table"
|
||||
// Inline tensor descriptors are opaque Apple ABI objects consumed by externally-defined
|
||||
// tensor-ops helpers. They must be supplied in the same exact authored linkage unit;
|
||||
// lowering only these calls would invent a layout the linked consumer does not share.
|
||||
| "air.get_descriptor_size_tensor"
|
||||
| "air.get_extent_private_tensor.i32"
|
||||
| "air.init_strided_private_tensor.i32.global"
|
||||
| "air.init_strided_private_tensor.i32.local"
|
||||
| "air.slice_private_tensor_private_tensor.s.i32"
|
||||
) {
|
||||
return Some(StaticLinkage);
|
||||
}
|
||||
|
||||
if matches!(
|
||||
name,
|
||||
"air.simdgroup.barrier"
|
||||
| "air.wg.barrier"
|
||||
| "air.atomic.fence"
|
||||
| "air.atomic.local.store.i32"
|
||||
| "air.atomic.global.store.i32"
|
||||
| "air.atomic.local.load.i32"
|
||||
| "air.atomic.global.load.i32"
|
||||
| "air.atomic.local.cmpxchg.weak.i32"
|
||||
| "air.atomic.global.cmpxchg.weak.i32"
|
||||
| "air.atomic.global.add.f32"
|
||||
| "air.atomic.global.sub.f32"
|
||||
| "air.atomic.local.add.s.i32"
|
||||
| "air.atomic.local.add.u.i32"
|
||||
| "air.atomic.local.sub.s.i32"
|
||||
| "air.atomic.local.sub.u.i32"
|
||||
| "air.atomic.local.max.s.i32"
|
||||
| "air.atomic.local.max.u.i32"
|
||||
| "air.atomic.local.min.s.i32"
|
||||
| "air.atomic.local.min.u.i32"
|
||||
| "air.atomic.local.and.u.i32"
|
||||
| "air.atomic.local.or.u.i32"
|
||||
| "air.atomic.local.xor.u.i32"
|
||||
| "air.atomic.local.xchg.i32"
|
||||
| "air.atomic.global.add.s.i32"
|
||||
| "air.atomic.global.add.u.i32"
|
||||
| "air.atomic.global.and.u.i32"
|
||||
| "air.atomic.global.or.u.i32"
|
||||
| "air.atomic.global.xchg.i32"
|
||||
| "air.atomic.global.max.s.i32"
|
||||
| "air.atomic.global.max.u.i32"
|
||||
| "air.atomic.global.min.s.i32"
|
||||
| "air.atomic.global.min.u.i32"
|
||||
| "air.atomic.global.sub.s.i32"
|
||||
| "air.atomic.global.sub.u.i32"
|
||||
| "air.atomic.global.xor.u.i32"
|
||||
| "air.simd_any"
|
||||
| "air.simd_all"
|
||||
| "air.simd_ballot.i64"
|
||||
| "air.quad_all"
|
||||
| "air.quad_any"
|
||||
| "air.quad_active_threads_mask"
|
||||
| "air.quad_is_first"
|
||||
| "air.simd_is_first"
|
||||
| "air.is_function_constant_defined"
|
||||
| "air.get_num_samples.i32"
|
||||
| "air.get_imageblock_width"
|
||||
| "air.get_imageblock_height"
|
||||
| "air.get_read_sampler"
|
||||
| "air.get_instance_count_instance_acceleration_structure"
|
||||
| "air.get_primitive_acceleration_structure_instance_acceleration_structure"
|
||||
| "air.get_data_pointer_instance_acceleration_structure"
|
||||
| "air.calculate_unclamped_lod_texture_2d"
|
||||
| "air.calculate_clamped_lod_texture_2d"
|
||||
| "air.imageblock_data"
|
||||
| "air.rhadd.u.i16"
|
||||
) {
|
||||
return Some(Lowered);
|
||||
}
|
||||
|
||||
if any_prefix(
|
||||
name,
|
||||
&[
|
||||
"air.load.device_coherent.",
|
||||
"air.load.system_coherent.",
|
||||
"air.store.device_coherent.",
|
||||
"air.store.system_coherent.",
|
||||
"air.fence_texture",
|
||||
"air.sample_texture",
|
||||
"air.sample_depth",
|
||||
"air.sample_compare_depth",
|
||||
"air.gather_texture",
|
||||
"air.gather_depth",
|
||||
"air.read_texture",
|
||||
"air.read_depth",
|
||||
"air.write_texture",
|
||||
"air.atomic_fetch_max_explicit_texture_",
|
||||
"air.write_imageblock_slice_to_texture",
|
||||
"air.load.implicit_imageblock.",
|
||||
"air.store.implicit_imageblock.",
|
||||
"air.discard_fragment",
|
||||
"air.get_width_texture",
|
||||
"air.get_height_texture",
|
||||
"air.get_depth_texture",
|
||||
"air.get_array_size_texture",
|
||||
"air.get_width_depth",
|
||||
"air.get_height_depth",
|
||||
"air.get_depth_depth",
|
||||
"air.get_num_mip_levels_texture",
|
||||
"air.get_num_mip_levels_depth",
|
||||
"air.get_num_samples_texture",
|
||||
"air.is_null_texture",
|
||||
"air.get_null_texture",
|
||||
"air.map_screen_to_physical_coordinates.",
|
||||
"air.map_physical_to_screen_coordinates.",
|
||||
"air.simdgroup_matrix_8x8_load.",
|
||||
"air.simdgroup_matrix_8x8_store.",
|
||||
"air.simdgroup_matrix_8x8_init_diag.",
|
||||
"air.simdgroup_matrix_8x8_multiply_accumulate.",
|
||||
"air.simdgroup_async_copy_2d.",
|
||||
"air.get_null_simdgroup_event",
|
||||
"air.is_null_simdgroup_event",
|
||||
"air.wait_simdgroup_events",
|
||||
"air.function_constant_predicate",
|
||||
"air.normalize_function_constant_predicate.",
|
||||
],
|
||||
) {
|
||||
return Some(Lowered);
|
||||
}
|
||||
|
||||
if matrix16_intrinsic(name).is_some() {
|
||||
return Some(Lowered);
|
||||
}
|
||||
|
||||
// Command helpers are an intentional observed-output contract: translation consumes these exact
|
||||
// stable ABI families while the validation executor reports the indirect-command-buffer tooling
|
||||
// requirement separately. Do not admit the broad `_command` suffix: a new sibling must remain
|
||||
// visible until both this contract and the lowering intentionally support it.
|
||||
if is_command_encoder_helper(name) {
|
||||
return Some(Lowered);
|
||||
}
|
||||
|
||||
if any_typed(
|
||||
name,
|
||||
&[
|
||||
"air.abs_diff",
|
||||
"air.abs",
|
||||
"air.reverse_bits",
|
||||
"air.bswap",
|
||||
"air.rotate",
|
||||
"air.extract_bits.u",
|
||||
"air.extract_bits.s",
|
||||
"air.insert_bits",
|
||||
"air.popcount",
|
||||
"air.ctz",
|
||||
"air.clz",
|
||||
"air.mul_hi.u",
|
||||
"air.mad_sat.s",
|
||||
"air.add_sat.u",
|
||||
"air.sub_sat.u",
|
||||
"air.convert",
|
||||
"air.dfdx",
|
||||
"air.fast_dfdx",
|
||||
"air.dfdy",
|
||||
"air.fast_dfdy",
|
||||
"air.fwidth",
|
||||
"air.dot",
|
||||
"air.is_uniform",
|
||||
"air.get_simdgroup_size",
|
||||
"air.simd_broadcast_first",
|
||||
"air.simd_broadcast",
|
||||
"air.simd_shuffle",
|
||||
"air.simd_shuffle_down",
|
||||
"air.simd_shuffle_rotate_down",
|
||||
"air.simd_shuffle_and_fill_down",
|
||||
"air.simd_shuffle_and_fill_up",
|
||||
"air.simd_shuffle_up",
|
||||
"air.simd_shuffle_xor",
|
||||
"air.quad_shuffle",
|
||||
"air.quad_broadcast",
|
||||
"air.quad_sum",
|
||||
"air.quad_min",
|
||||
"air.quad_max",
|
||||
"air.quad_shuffle_xor",
|
||||
"air.quad_shuffle_rotate_down",
|
||||
"air.quad_shuffle_up",
|
||||
"air.quad_shuffle_down",
|
||||
"air.simd_prefix_exclusive_sum",
|
||||
"air.simd_prefix_inclusive_sum",
|
||||
"air.simd_sum",
|
||||
"air.simd_or",
|
||||
"air.simd_xor",
|
||||
"air.simd_and",
|
||||
"air.simd_min",
|
||||
"air.simd_max",
|
||||
"air.all",
|
||||
"air.any",
|
||||
"air.pack",
|
||||
"air.unpack",
|
||||
"air.sincos",
|
||||
"air.cospi",
|
||||
"air.sinpi",
|
||||
"air.tanpi",
|
||||
"air.exp10",
|
||||
"air.fmod",
|
||||
"air.log10",
|
||||
"air.min.s",
|
||||
"air.min.u",
|
||||
"air.max.s",
|
||||
"air.max.u",
|
||||
"air.clamp.s",
|
||||
"air.clamp.u",
|
||||
"air.max3.u",
|
||||
"air.min3.u",
|
||||
"air.max3.s",
|
||||
"air.min3.s",
|
||||
"air.fmax3",
|
||||
"air.fmin3",
|
||||
"air.fmedian3",
|
||||
"air.ldexp",
|
||||
"air.atan2",
|
||||
"air.asin",
|
||||
"air.acos",
|
||||
"air.atan",
|
||||
"air.fmax",
|
||||
"air.max",
|
||||
"air.fmin",
|
||||
"air.min",
|
||||
"air.sqrt",
|
||||
"air.rsqrt",
|
||||
"air.fabs",
|
||||
"air.pow",
|
||||
"air.powr",
|
||||
"air.sign",
|
||||
"air.mix",
|
||||
"air.floor",
|
||||
"air.ceil",
|
||||
"air.round",
|
||||
"air.rint",
|
||||
"air.trunc",
|
||||
"air.tan",
|
||||
"air.sinh",
|
||||
"air.cosh",
|
||||
"air.tanh",
|
||||
"air.asinh",
|
||||
"air.acosh",
|
||||
"air.atanh",
|
||||
"air.sin",
|
||||
"air.cos",
|
||||
"air.exp2",
|
||||
"air.exp",
|
||||
"air.log2",
|
||||
"air.log",
|
||||
"air.fract",
|
||||
"air.fma",
|
||||
"air.clamp",
|
||||
"air.saturate",
|
||||
],
|
||||
) || name.strip_prefix("air.fast_").is_some_and(|tail| {
|
||||
[
|
||||
"sincos", "cospi", "sinpi", "tanpi", "exp10", "fmod", "log10", "fmax3", "fmin3",
|
||||
"fmedian3", "ldexp", "atan2", "asin", "acos", "atan", "fmax", "max", "fmin", "min",
|
||||
"sqrt", "rsqrt", "fabs", "pow", "powr", "sign", "mix", "floor", "ceil", "round",
|
||||
"rint", "trunc", "tan", "sinh", "cosh", "tanh", "asinh", "acosh", "atanh", "sin",
|
||||
"cos", "exp2", "exp", "log2", "log", "fract", "fma", "clamp", "saturate",
|
||||
]
|
||||
.iter()
|
||||
.any(|stem| {
|
||||
tail.strip_prefix(stem)
|
||||
.is_some_and(|rest| rest.starts_with('.'))
|
||||
})
|
||||
}) {
|
||||
return Some(Lowered);
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn recognition_is_family_bounded() {
|
||||
assert_eq!(
|
||||
air_intrinsic_disposition("air.any.v4i1"),
|
||||
Some(AirIntrinsicDisposition::Lowered)
|
||||
);
|
||||
assert_eq!(air_intrinsic_disposition("air.anything.v4i1"), None);
|
||||
assert_eq!(air_intrinsic_disposition("air.tensor_future.i32"), None);
|
||||
assert_eq!(
|
||||
air_intrinsic_disposition("air.init_strided_private_tensor.i32.local"),
|
||||
Some(AirIntrinsicDisposition::StaticLinkage)
|
||||
);
|
||||
assert_eq!(air_intrinsic_disposition("air.future_command"), None);
|
||||
assert_eq!(
|
||||
air_intrinsic_disposition("air.set_kernel_buffer_compute_command.p1i8"),
|
||||
Some(AirIntrinsicDisposition::Lowered)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linkage_is_distinct_from_direct_lowering() {
|
||||
assert_eq!(
|
||||
air_intrinsic_disposition("air.intersect.instancing.triangle_data"),
|
||||
Some(AirIntrinsicDisposition::LoweredOrStaticLinkage)
|
||||
);
|
||||
assert_eq!(
|
||||
air_intrinsic_disposition("air.simdgroup_matrix_8x8_load.v64f32.p1f32"),
|
||||
Some(AirIntrinsicDisposition::Lowered)
|
||||
);
|
||||
assert_eq!(
|
||||
air_intrinsic_disposition(
|
||||
"air.simdgroup_matrix_16x16x16_multiply_accumulate.f.f.v8f32.v8f16.v8f16.v8f32"
|
||||
),
|
||||
Some(AirIntrinsicDisposition::Lowered)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matrix16_recognition_requires_the_complete_known_abi_shape() {
|
||||
let float =
|
||||
"air.simdgroup_matrix_16x16x16_multiply_accumulate.f.f.v8f32.v8bf16.v8f8e4m3.v8f32";
|
||||
assert_eq!(
|
||||
matrix16_intrinsic(float),
|
||||
Some(Matrix16Intrinsic {
|
||||
lhs: Matrix16Element::Bf16,
|
||||
rhs: Matrix16Element::F8E4M3,
|
||||
integer: false,
|
||||
})
|
||||
);
|
||||
assert!(matrix16_intrinsic(
|
||||
"air.simdgroup_matrix_16x16x16_multiply_accumulate.f.f.v8f32.v8future.v8f16.v8f32"
|
||||
)
|
||||
.is_none());
|
||||
assert!(matrix16_intrinsic(
|
||||
"air.simdgroup_matrix_16x16x16_multiply_accumulate.f.f.v8f16.v8f16.v8f16.v8f16"
|
||||
)
|
||||
.is_none());
|
||||
assert!(matrix16_intrinsic(
|
||||
"air.simdgroup_matrix_16x16x16_widening_multiply_accumulate.s.x.v8i32.v8i8.v8i8.v8i32"
|
||||
)
|
||||
.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_inventory_ignores_non_callees_and_counts_all_call_forms() {
|
||||
let ll = "define void @main() {\nentry:\n %a = call i32 @air.abs.s.i32(i32 -1)\n %b = tail call i32 @air.future_tensor.i32(i32 1)\n %c = musttail\tcall i32 @air.future_tensor.i32(i32 2)\n %d = invoke i32 @\"air.quoted_future.i32\"(i32 3) to label %ok unwind label %err\n callbr void @air.branch_future() to label %ok [label %err]\n call void @ordinary(ptr @air.declaration_only.i32) ; @air.comment_only\n ret void\n}\ndefine void @compact() { %x = call i32 @air.compact_future(i32 0) ret void }\ndeclare i32 @air.declaration_only.i32(i32)";
|
||||
assert_eq!(
|
||||
air_call_counts(ll),
|
||||
BTreeMap::from([
|
||||
("air.abs.s.i32".into(), 1),
|
||||
("air.branch_future".into(), 1),
|
||||
("air.compact_future".into(), 1),
|
||||
("air.future_tensor.i32".into(), 2),
|
||||
("air.quoted_future.i32".into(), 1),
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
unrecognized_air_intrinsics(ll),
|
||||
BTreeMap::from([
|
||||
("air.branch_future".into(), 1),
|
||||
("air.compact_future".into(), 1),
|
||||
("air.future_tensor.i32".into(), 2),
|
||||
("air.quoted_future.i32".into(), 1),
|
||||
])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -18,3 +18,14 @@ pub const INSTANCE_COUNT_BYTE_OFFSET: u64 =
|
||||
pub const CHILD_REFERENCES_BYTE_OFFSET: u64 =
|
||||
std::mem::size_of::<AccelerationStructureShadowHeader>() as u64;
|
||||
pub const CHILD_REFERENCE_BYTE_STRIDE: u64 = std::mem::size_of::<u64>() as u64;
|
||||
|
||||
/// Fixed header preceding tightly packed primitive triangle vertices.
|
||||
#[repr(C)]
|
||||
pub struct PrimitiveAccelerationStructureShadowHeader {
|
||||
pub triangle_count: u32,
|
||||
pub reserved: u32,
|
||||
}
|
||||
|
||||
pub const PRIMITIVE_TRIANGLES_BYTE_OFFSET: u64 =
|
||||
std::mem::size_of::<PrimitiveAccelerationStructureShadowHeader>() as u64;
|
||||
pub const PRIMITIVE_TRIANGLE_BYTE_STRIDE: u64 = 9 * std::mem::size_of::<f32>() as u64;
|
||||
+325
-9
@@ -11,9 +11,31 @@ pub(crate) struct EmitSidecar {
|
||||
/// Emitted `OpTypeStruct` id -> exact AIR member offsets, including backend padding members.
|
||||
pub(crate) air_struct_offsets: HashMap<Word, Vec<u32>>,
|
||||
pub(crate) buffer_address_words: Vec<BufferAddressWord>,
|
||||
/// Exact constant byte address of a GEP result relative to one buffer root. This preserves the
|
||||
/// source aggregate layout across the native-emitter → remodeled-interface seam, where an
|
||||
/// overlapping struct/union may intentionally become a raw word block.
|
||||
pub(crate) buffer_access_offsets: Vec<BufferAccessOffset>,
|
||||
/// Affine byte address of a dynamic GEP relative to one buffer root. Each term is an emitted
|
||||
/// integer index id and its exact source-layout byte stride.
|
||||
pub(crate) buffer_access_affine_offsets: Vec<BufferAccessAffineOffset>,
|
||||
/// Final descriptor variable -> original emitted parameter pointee type. Raw interface blocks
|
||||
/// deliberately discard that aggregate shape; constant late access paths still need it as the
|
||||
/// exact AIR layout oracle.
|
||||
pub(crate) buffer_root_source_types: HashMap<Word, Word>,
|
||||
/// Pointer-handle value loaded from a fixed byte offset of a buffer parameter root. The root id
|
||||
/// is remapped with helper parameters during inlining, so the fact reaches the entry parameter
|
||||
/// without retaining a callee-local ordinal.
|
||||
pub(crate) buffer_pointer_field_loads: Vec<BufferPointerFieldLoad>,
|
||||
/// Pointer handle loaded from element `index` of a buffer parameter whose AIR element is one
|
||||
/// serialized 64-bit opaque handle (for example `array_ref<texture2d<...>>`).
|
||||
pub(crate) buffer_pointer_dynamic_field_loads: Vec<BufferPointerDynamicFieldLoad>,
|
||||
pub(crate) local_pointer_field_stores: Vec<LocalPointerFieldStore>,
|
||||
pub(crate) local_pointer_field_loads: Vec<LocalPointerFieldLoad>,
|
||||
pub(crate) local_pointer_dynamic_field_loads: Vec<LocalPointerDynamicFieldLoad>,
|
||||
/// Result ids emitted as typed sentinels for the stable `llvm.agx2.cluster.num` ABI intrinsic.
|
||||
/// The final interface pass replaces each sentinel with the AGX2 physical-cluster number derived
|
||||
/// from Vulkan `LocalInvocationId` and the caller-supplied kernel local size.
|
||||
pub(crate) agx2_cluster_numbers: Vec<Word>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -23,10 +45,42 @@ pub(crate) struct BufferAddressWord {
|
||||
pub(crate) component: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct BufferAccessOffset {
|
||||
pub(crate) id: Word,
|
||||
pub(crate) root: Word,
|
||||
pub(crate) byte_offset: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct BufferAccessAffineOffset {
|
||||
pub(crate) id: Word,
|
||||
pub(crate) root: Word,
|
||||
pub(crate) constant: u64,
|
||||
pub(crate) terms: Vec<(Word, u64)>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct BufferPointerFieldLoad {
|
||||
pub(crate) id: Word,
|
||||
pub(crate) root: Word,
|
||||
pub(crate) byte_offset: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct BufferPointerDynamicFieldLoad {
|
||||
pub(crate) id: Word,
|
||||
pub(crate) root: Word,
|
||||
pub(crate) byte_offset: u64,
|
||||
pub(crate) index: Word,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct LocalPointerFieldStore {
|
||||
pub(crate) id: Word,
|
||||
pub(crate) source: Word,
|
||||
pub(crate) root: Word,
|
||||
pub(crate) indices: Vec<u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -60,9 +114,30 @@ impl EmitSidecar {
|
||||
for fact in &mut self.buffer_address_words {
|
||||
replace(&mut fact.id);
|
||||
}
|
||||
for fact in &mut self.buffer_access_offsets {
|
||||
replace(&mut fact.id);
|
||||
replace(&mut fact.root);
|
||||
}
|
||||
for fact in &mut self.buffer_access_affine_offsets {
|
||||
replace(&mut fact.id);
|
||||
replace(&mut fact.root);
|
||||
for (index, _) in &mut fact.terms {
|
||||
replace(index);
|
||||
}
|
||||
}
|
||||
for fact in &mut self.buffer_pointer_field_loads {
|
||||
replace(&mut fact.id);
|
||||
replace(&mut fact.root);
|
||||
}
|
||||
for fact in &mut self.buffer_pointer_dynamic_field_loads {
|
||||
replace(&mut fact.id);
|
||||
replace(&mut fact.root);
|
||||
replace(&mut fact.index);
|
||||
}
|
||||
for fact in &mut self.local_pointer_field_stores {
|
||||
replace(&mut fact.id);
|
||||
replace(&mut fact.source);
|
||||
replace(&mut fact.root);
|
||||
}
|
||||
for fact in &mut self.local_pointer_field_loads {
|
||||
replace(&mut fact.id);
|
||||
@@ -73,13 +148,94 @@ impl EmitSidecar {
|
||||
replace(&mut fact.root);
|
||||
replace(&mut fact.index);
|
||||
}
|
||||
for id in &mut self.agx2_cluster_numbers {
|
||||
replace(id);
|
||||
}
|
||||
self.air_struct_offsets = std::mem::take(&mut self.air_struct_offsets)
|
||||
.into_iter()
|
||||
.map(|(id, offsets)| (remap.get(&id).copied().unwrap_or(id), offsets))
|
||||
.collect();
|
||||
self.buffer_root_source_types = std::mem::take(&mut self.buffer_root_source_types)
|
||||
.into_iter()
|
||||
.map(|(root, source_ty)| {
|
||||
(
|
||||
remap.get(&root).copied().unwrap_or(root),
|
||||
remap.get(&source_ty).copied().unwrap_or(source_ty),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
pub(crate) fn clone_inlined_local_pointer_field_loads(&mut self, remap: &HashMap<Word, Word>) {
|
||||
pub(crate) fn clone_inlined_facts(&mut self, remap: &HashMap<Word, Word>) {
|
||||
let clones = self
|
||||
.buffer_access_offsets
|
||||
.iter()
|
||||
.filter_map(|fact| {
|
||||
Some(BufferAccessOffset {
|
||||
id: remap.get(&fact.id).copied()?,
|
||||
root: remap.get(&fact.root).copied().unwrap_or(fact.root),
|
||||
byte_offset: fact.byte_offset,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
self.buffer_access_offsets.extend(clones);
|
||||
let clones = self
|
||||
.buffer_access_affine_offsets
|
||||
.iter()
|
||||
.filter_map(|fact| {
|
||||
Some(BufferAccessAffineOffset {
|
||||
id: remap.get(&fact.id).copied()?,
|
||||
root: remap.get(&fact.root).copied().unwrap_or(fact.root),
|
||||
constant: fact.constant,
|
||||
terms: fact
|
||||
.terms
|
||||
.iter()
|
||||
.map(|(index, stride)| {
|
||||
(remap.get(index).copied().unwrap_or(*index), *stride)
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
self.buffer_access_affine_offsets.extend(clones);
|
||||
let clones = self
|
||||
.local_pointer_field_stores
|
||||
.iter()
|
||||
.filter_map(|fact| {
|
||||
Some(LocalPointerFieldStore {
|
||||
id: remap.get(&fact.id).copied().unwrap_or(fact.id),
|
||||
source: remap.get(&fact.source).copied().unwrap_or(fact.source),
|
||||
root: remap.get(&fact.root).copied()?,
|
||||
indices: fact.indices.clone(),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
self.local_pointer_field_stores.extend(clones);
|
||||
let clones = self
|
||||
.buffer_pointer_field_loads
|
||||
.iter()
|
||||
.filter_map(|fact| {
|
||||
Some(BufferPointerFieldLoad {
|
||||
id: remap.get(&fact.id).copied()?,
|
||||
root: remap.get(&fact.root).copied().unwrap_or(fact.root),
|
||||
byte_offset: fact.byte_offset,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
self.buffer_pointer_field_loads.extend(clones);
|
||||
let clones = self
|
||||
.buffer_pointer_dynamic_field_loads
|
||||
.iter()
|
||||
.filter_map(|fact| {
|
||||
Some(BufferPointerDynamicFieldLoad {
|
||||
id: remap.get(&fact.id).copied()?,
|
||||
root: remap.get(&fact.root).copied().unwrap_or(fact.root),
|
||||
byte_offset: fact.byte_offset,
|
||||
index: remap.get(&fact.index).copied().unwrap_or(fact.index),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
self.buffer_pointer_dynamic_field_loads.extend(clones);
|
||||
let clones = self
|
||||
.local_pointer_field_loads
|
||||
.iter()
|
||||
@@ -108,6 +264,12 @@ impl EmitSidecar {
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
self.local_pointer_dynamic_field_loads.extend(clones);
|
||||
let clones = self
|
||||
.agx2_cluster_numbers
|
||||
.iter()
|
||||
.filter_map(|id| remap.get(id).copied())
|
||||
.collect::<Vec<_>>();
|
||||
self.agx2_cluster_numbers.extend(clones);
|
||||
}
|
||||
|
||||
pub(crate) fn remap_local_pointer_field_store_sources(&mut self, remap: &HashMap<Word, Word>) {
|
||||
@@ -142,7 +304,28 @@ mod tests {
|
||||
#[test]
|
||||
fn inlining_clones_load_facts_and_remaps_store_sources() {
|
||||
let mut sidecar = EmitSidecar {
|
||||
local_pointer_field_stores: vec![LocalPointerFieldStore { id: 10, source: 20 }],
|
||||
buffer_access_offsets: vec![BufferAccessOffset {
|
||||
id: 82,
|
||||
root: 92,
|
||||
byte_offset: 28,
|
||||
}],
|
||||
buffer_pointer_field_loads: vec![BufferPointerFieldLoad {
|
||||
id: 80,
|
||||
root: 90,
|
||||
byte_offset: 16,
|
||||
}],
|
||||
buffer_pointer_dynamic_field_loads: vec![BufferPointerDynamicFieldLoad {
|
||||
id: 81,
|
||||
root: 91,
|
||||
byte_offset: 8,
|
||||
index: 71,
|
||||
}],
|
||||
local_pointer_field_stores: vec![LocalPointerFieldStore {
|
||||
id: 10,
|
||||
source: 20,
|
||||
root: 40,
|
||||
indices: vec![1, 2],
|
||||
}],
|
||||
local_pointer_field_loads: vec![LocalPointerFieldLoad {
|
||||
id: 30,
|
||||
root: 40,
|
||||
@@ -157,17 +340,88 @@ mod tests {
|
||||
}],
|
||||
..EmitSidecar::default()
|
||||
};
|
||||
let remap = HashMap::from([(20, 120), (30, 130), (40, 140), (50, 150), (60, 160)]);
|
||||
let remap = HashMap::from([
|
||||
(20, 120),
|
||||
(30, 130),
|
||||
(40, 140),
|
||||
(50, 150),
|
||||
(60, 160),
|
||||
(80, 180),
|
||||
(90, 190),
|
||||
(81, 181),
|
||||
(91, 191),
|
||||
(82, 182),
|
||||
(92, 192),
|
||||
]);
|
||||
|
||||
sidecar.clone_inlined_local_pointer_field_loads(&remap);
|
||||
sidecar.clone_inlined_facts(&remap);
|
||||
sidecar.remap_local_pointer_field_store_sources(&remap);
|
||||
|
||||
assert_eq!(
|
||||
sidecar.buffer_access_offsets,
|
||||
vec![
|
||||
BufferAccessOffset {
|
||||
id: 82,
|
||||
root: 92,
|
||||
byte_offset: 28,
|
||||
},
|
||||
BufferAccessOffset {
|
||||
id: 182,
|
||||
root: 192,
|
||||
byte_offset: 28,
|
||||
},
|
||||
]
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
sidecar.buffer_pointer_field_loads,
|
||||
vec![
|
||||
BufferPointerFieldLoad {
|
||||
id: 80,
|
||||
root: 90,
|
||||
byte_offset: 16,
|
||||
},
|
||||
BufferPointerFieldLoad {
|
||||
id: 180,
|
||||
root: 190,
|
||||
byte_offset: 16,
|
||||
},
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
sidecar.buffer_pointer_dynamic_field_loads,
|
||||
vec![
|
||||
BufferPointerDynamicFieldLoad {
|
||||
id: 81,
|
||||
root: 91,
|
||||
byte_offset: 8,
|
||||
index: 71,
|
||||
},
|
||||
BufferPointerDynamicFieldLoad {
|
||||
id: 181,
|
||||
root: 191,
|
||||
byte_offset: 8,
|
||||
index: 71,
|
||||
},
|
||||
]
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
sidecar.local_pointer_field_stores,
|
||||
vec![LocalPointerFieldStore {
|
||||
id: 10,
|
||||
source: 120
|
||||
}]
|
||||
vec![
|
||||
LocalPointerFieldStore {
|
||||
id: 10,
|
||||
source: 120,
|
||||
root: 40,
|
||||
indices: vec![1, 2],
|
||||
},
|
||||
LocalPointerFieldStore {
|
||||
id: 10,
|
||||
source: 120,
|
||||
root: 140,
|
||||
indices: vec![1, 2],
|
||||
},
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
sidecar.local_pointer_field_loads,
|
||||
@@ -214,7 +468,35 @@ mod tests {
|
||||
param_index: 2,
|
||||
component: 1,
|
||||
}],
|
||||
local_pointer_field_stores: vec![LocalPointerFieldStore { id: 20, source: 21 }],
|
||||
buffer_access_offsets: vec![BufferAccessOffset {
|
||||
id: 16,
|
||||
root: 17,
|
||||
byte_offset: 28,
|
||||
}],
|
||||
buffer_access_affine_offsets: vec![BufferAccessAffineOffset {
|
||||
id: 23,
|
||||
root: 24,
|
||||
constant: 32,
|
||||
terms: vec![(25, 48)],
|
||||
}],
|
||||
buffer_root_source_types: HashMap::from([(18, 19)]),
|
||||
buffer_pointer_field_loads: vec![BufferPointerFieldLoad {
|
||||
id: 11,
|
||||
root: 12,
|
||||
byte_offset: 24,
|
||||
}],
|
||||
buffer_pointer_dynamic_field_loads: vec![BufferPointerDynamicFieldLoad {
|
||||
id: 13,
|
||||
root: 14,
|
||||
byte_offset: 16,
|
||||
index: 15,
|
||||
}],
|
||||
local_pointer_field_stores: vec![LocalPointerFieldStore {
|
||||
id: 20,
|
||||
source: 21,
|
||||
root: 22,
|
||||
indices: vec![3],
|
||||
}],
|
||||
local_pointer_field_loads: vec![LocalPointerFieldLoad {
|
||||
id: 30,
|
||||
root: 31,
|
||||
@@ -227,30 +509,64 @@ mod tests {
|
||||
index: 42,
|
||||
suffix: vec![6],
|
||||
}],
|
||||
agx2_cluster_numbers: vec![50],
|
||||
};
|
||||
let remap = HashMap::from([
|
||||
(10, 110),
|
||||
(11, 111),
|
||||
(12, 112),
|
||||
(13, 113),
|
||||
(14, 114),
|
||||
(15, 115),
|
||||
(16, 116),
|
||||
(17, 117),
|
||||
(18, 118),
|
||||
(19, 119),
|
||||
(20, 120),
|
||||
(21, 121),
|
||||
(22, 122),
|
||||
(23, 123),
|
||||
(24, 124),
|
||||
(25, 125),
|
||||
(30, 130),
|
||||
(31, 131),
|
||||
(40, 140),
|
||||
(41, 141),
|
||||
(42, 142),
|
||||
(5, 105),
|
||||
(50, 150),
|
||||
]);
|
||||
|
||||
sidecar.remap_ids(&remap);
|
||||
assert_eq!(
|
||||
sidecar.buffer_root_source_types,
|
||||
HashMap::from([(118, 119)])
|
||||
);
|
||||
|
||||
assert_eq!(sidecar.air_struct_offsets.get(&105), Some(&vec![0, 16]));
|
||||
assert!(!sidecar.air_struct_offsets.contains_key(&5));
|
||||
assert_eq!(sidecar.buffer_address_words[0].id, 110);
|
||||
assert_eq!(sidecar.buffer_access_offsets[0].id, 116);
|
||||
assert_eq!(sidecar.buffer_access_offsets[0].root, 117);
|
||||
assert_eq!(sidecar.buffer_access_affine_offsets[0].id, 123);
|
||||
assert_eq!(sidecar.buffer_access_affine_offsets[0].root, 124);
|
||||
assert_eq!(
|
||||
sidecar.buffer_access_affine_offsets[0].terms,
|
||||
vec![(125, 48)]
|
||||
);
|
||||
assert_eq!(sidecar.buffer_pointer_field_loads[0].id, 111);
|
||||
assert_eq!(sidecar.buffer_pointer_field_loads[0].root, 112);
|
||||
assert_eq!(sidecar.buffer_pointer_dynamic_field_loads[0].id, 113);
|
||||
assert_eq!(sidecar.buffer_pointer_dynamic_field_loads[0].root, 114);
|
||||
assert_eq!(sidecar.buffer_pointer_dynamic_field_loads[0].index, 115);
|
||||
assert_eq!(sidecar.local_pointer_field_stores[0].id, 120);
|
||||
assert_eq!(sidecar.local_pointer_field_stores[0].source, 121);
|
||||
assert_eq!(sidecar.local_pointer_field_stores[0].root, 122);
|
||||
assert_eq!(sidecar.local_pointer_field_loads[0].id, 130);
|
||||
assert_eq!(sidecar.local_pointer_field_loads[0].root, 131);
|
||||
assert_eq!(sidecar.local_pointer_dynamic_field_loads[0].id, 140);
|
||||
assert_eq!(sidecar.local_pointer_dynamic_field_loads[0].root, 141);
|
||||
assert_eq!(sidecar.local_pointer_dynamic_field_loads[0].index, 142);
|
||||
assert_eq!(sidecar.agx2_cluster_numbers, vec![150]);
|
||||
}
|
||||
}
|
||||
+26
-72
@@ -1,6 +1,6 @@
|
||||
//! One registry for every `METAL2VULKAN_*` environment variable the crate honors (refactor S8).
|
||||
//!
|
||||
//! Before this module the ~19 vars were read at ~33 scattered `std::env::var` sites with subtly
|
||||
//! Environment reads previously lived at scattered `std::env::var` sites with subtly
|
||||
//! different idioms (`var_os().is_some()` vs `var().is_ok()`, `map_or(true, |v| v != "0")` vs
|
||||
//! `is_ok_and(|v| v == "0")`, ad-hoc integer parses) and none were documented in `--help`. Every var
|
||||
//! now has exactly one typed accessor here plus a `REGISTRY` entry (name/default/effect) that
|
||||
@@ -48,14 +48,13 @@ pub const REGISTRY: &[EnvVar] = &[
|
||||
EnvVar {
|
||||
name: "METAL2VULKAN_RETRY_DUMP",
|
||||
default: "unset",
|
||||
effect: "path to dump a failing inline+SROA module (debug)",
|
||||
effect: "path to dump a failing retry or corpus-audit SPIR-V module (debug)",
|
||||
},
|
||||
EnvVar {
|
||||
name: "METAL2VULKAN_<TOOL>",
|
||||
default: "PATH search",
|
||||
effect: "dynamic family: per-external-tool path override — METAL2VULKAN_<CMD> (uppercased, \
|
||||
-> _) gives an absolute path to that tool binary (e.g. METAL2VULKAN_LLVM_DIS, \
|
||||
METAL2VULKAN_SPIRV_VAL). Absent → search the known tool dirs then PATH",
|
||||
effect: "absolute per-tool override (for example METAL2VULKAN_LLVM_DIS or \
|
||||
METAL2VULKAN_SPIRV_VAL)",
|
||||
},
|
||||
// presence-flag debug/trace toggles (set to any value to enable)
|
||||
EnvVar {
|
||||
@@ -71,68 +70,41 @@ pub const REGISTRY: &[EnvVar] = &[
|
||||
EnvVar {
|
||||
name: "METAL2VULKAN_TIER_CENSUS",
|
||||
default: "off",
|
||||
effect: "print `[tier-census] <tier>` per translate: which retry tier (if any) was \
|
||||
adopted (M-C1 cascade-redundancy telemetry)",
|
||||
effect: "print the adopted retry tier for each translation",
|
||||
},
|
||||
EnvVar {
|
||||
name: "METAL2VULKAN_PARAM_POINTEE_DBG",
|
||||
default: "off",
|
||||
effect: "enumerate S18 param-pointee sidecar divergences (--param-pointee-check)",
|
||||
effect: "trace parameter-pointee sidecar mismatches",
|
||||
},
|
||||
EnvVar {
|
||||
name: "METAL2VULKAN_POINTEE_DBG",
|
||||
default: "off",
|
||||
effect: "enumerate M2 pointee-carrier divergences (--tir-pointee-check)",
|
||||
effect: "trace typed-IR pointee-carrier mismatches",
|
||||
},
|
||||
EnvVar {
|
||||
name: "METAL2VULKAN_WHOLE_PART",
|
||||
default: "off",
|
||||
effect: "M-A2(b) whole-vs-part: upgrade a SCALAR local-pointer pointee to the use-implied \
|
||||
WHOLE composite carrier (Vector(S,N)/[N x S] of the same scalar S) when the pointer \
|
||||
is dereferenced as the whole. Excludes raw_offsets/unmodeled/byte-view and any \
|
||||
pointer participating in a phi/select pointer merge. Byte-changing; default OFF — \
|
||||
the 112 changed banked cases MoltenVK-conform (109 byte-exact + 3 flag-independent \
|
||||
FP-drift) ONLY because the retry cascade rescues its INVALID primary emits: the \
|
||||
upgrade widens a load's result to the whole vector WITHOUT retyping the feeding \
|
||||
access-chain pointer, so a bitcast-aliased whole-vector load through a scalar-element \
|
||||
access chain emits `OpLoad <4 x half> from half*` (spirv-val invalid — see the \
|
||||
native_pointer_bitcast_vector_load_store_uses_scalar_lanes test). The flip is blocked \
|
||||
by that partial-retyping soundness gap, NOT by G8 hardware; it needs consistent \
|
||||
def-site pointer-network retyping (M-A2(c)/M-B1 keystone) first. Frozen by dead-end \
|
||||
A9 (read-side prefer-carrier retyping is proven unsound); kept as measurement \
|
||||
substrate only",
|
||||
effect:
|
||||
"UNSAFE diagnostic: probe whole-composite local-pointer carriers; may emit invalid \
|
||||
SPIR-V and must not be used as a product feature",
|
||||
},
|
||||
EnvVar {
|
||||
name: "METAL2VULKAN_REINTERP_REAL",
|
||||
default: "off",
|
||||
effect: "M-A2(a) Float<->Int reinterpret (DIAGNOSTIC/UNSOUND — do NOT flip): upgrade a SCALAR \
|
||||
local-pointer pointee to a use-implied carrier scalar of the SAME bit width but \
|
||||
different kind (Float(32)<->Int(32), Half(16)<->Int(16), …). Enumerable via \
|
||||
--reinterp-real-check. Proven NON-conformant: a G7 MoltenVK sample miscompiles the \
|
||||
topk_common_matrix_float family (naive prefer-carrier picks one arm of a genuine \
|
||||
reinterpret). Frozen by dead-end A9 (read-side prefer-carrier retyping is proven \
|
||||
unsound). Kept default-off as the measurement substrate for the eventual sound \
|
||||
def-site-unambiguous version; never flip in this naive form",
|
||||
effect: "UNSAFE diagnostic: probe same-width float/integer pointer retyping; known \
|
||||
nonconformant and never a product feature",
|
||||
},
|
||||
EnvVar {
|
||||
name: "METAL2VULKAN_STRADDLE_ADMIT",
|
||||
default: "off",
|
||||
effect: "M-B1 straddle DIAGNOSTIC (default-off, NOT a fix): bypass the \
|
||||
`selection:straddle-loop-merge` self-check so the structured plan is admitted anyway. \
|
||||
For the enclosing-guard early-return shape (05/b00a8a8d — top-level `if(!c) return` \
|
||||
guards whose false arm is the OpReturn block that doubles as the loop merge) this lets \
|
||||
the downstream synth run and exposes the NEXT blocker (a byte-view pointer-phi) the \
|
||||
CFG reject otherwise masks. Flag-on emits invalid SPIR-V for genuine straddles, so it \
|
||||
is a single-case probe knob for phi/pointee work, never enabled at large scale",
|
||||
effect:
|
||||
"UNSAFE diagnostic: bypass one structured-CFG straddle check; may emit invalid SPIR-V",
|
||||
},
|
||||
EnvVar {
|
||||
name: "METAL2VULKAN_PTR_NETWORK_WHY",
|
||||
default: "off",
|
||||
effect: "M-A2/M-B1 DIAGNOSTIC (default-off, read-only): per function, print each pointer \
|
||||
network (connected component over phi result↔incoming + select result↔arm edges) \
|
||||
whose recorded pointees are non-uniform, tagged whole-vs-part / reinterpret-mix / \
|
||||
unclassified. Builds the grouping M-A2's def-site finest-granularity recording needs \
|
||||
and quantifies its scope. Changes no bytes",
|
||||
effect: "trace pointer phi/select networks with non-uniform pointee types (byte-neutral)",
|
||||
},
|
||||
EnvVar {
|
||||
name: "METAL2VULKAN_STORAGE_DBG",
|
||||
@@ -162,66 +134,48 @@ pub const REGISTRY: &[EnvVar] = &[
|
||||
EnvVar {
|
||||
name: "METAL2VULKAN_RELOOP_WHY",
|
||||
default: "off",
|
||||
effect: "M-B DIAGNOSTIC (default-off, read-only): per relooper invocation, print the function \
|
||||
count handed in (RELOOP-ENTER) and, per function, its block count and the reason \
|
||||
rewrite_to_relooper bails (RELOOP-FN / RELOOP-BAIL: too-few/too-many-blocks, \
|
||||
empty-block, unhandled-terminator, non-spillable-demote). Surfaces WHY the relooper \
|
||||
(repair's designed replacement) cannot rescue an M-B2 NO_REPAIR blocker — e.g. 05 \
|
||||
bails on non-spillable pointer demotion (loop-carried buffer pointers). Changes no bytes",
|
||||
effect: "trace relooper entry, block counts, and exact bailout reasons (byte-neutral)",
|
||||
},
|
||||
EnvVar {
|
||||
name: "METAL2VULKAN_SPI_WHY",
|
||||
default: "off",
|
||||
effect: "Keystone-2 DIAGNOSTIC (default-off, read-only eprintln): log the exact point + the \
|
||||
(converge_inloop, break_aware) flags at which structured_plan_inner returns \
|
||||
None for a function, so the ACTUAL residual reject of a merge-inloop case can be seen \
|
||||
(the --structured-why LABEL is computed with converge=false and does not name why the \
|
||||
converge/protect attempts fail). On a branch-no-merge reject it also dumps the sblocks \
|
||||
skeleton. Changes no bytes",
|
||||
effect: "trace exact structured-plan rejection points and plan flags (byte-neutral)",
|
||||
},
|
||||
// default-off measurement / gate substrates
|
||||
EnvVar {
|
||||
name: "METAL2VULKAN_CONVERGE_INLOOP",
|
||||
default: "off",
|
||||
effect: "Measurement override: force the in-loop merge-collision convergence on ALL \
|
||||
structured_plan attempts, not just the reject-triggered 4th (the default). Measures the \
|
||||
large-scale byte churn (~2170 rows) the unconditional broad form would cause vs the \
|
||||
bounded reject-triggered set",
|
||||
effect:
|
||||
"measurement override: force in-loop merge convergence on every structured-plan attempt",
|
||||
},
|
||||
// default-off diagnostics (read-only eprintln, never change bytes)
|
||||
EnvVar {
|
||||
name: "METAL2VULKAN_UNMODELED_WHY",
|
||||
default: "off",
|
||||
effect: "log every unmodeled-pointer PLACEHOLDER the emitter synthesizes \
|
||||
(emit_private_zero_pointer_value) with result id, pointee, and callsite, so the \
|
||||
provenance behind a blocker can be identified",
|
||||
effect: "trace synthesized unmodeled-pointer placeholders and their provenance",
|
||||
},
|
||||
EnvVar {
|
||||
name: "METAL2VULKAN_FLM_WHY",
|
||||
default: "off",
|
||||
effect: "log every loop plan forest_loop_merges processes with its restructure kind, natural \
|
||||
merge block, whether that merge collides with an outer selection, and whether it \
|
||||
carries a phi — the loop-merge/selection-merge collision topology behind the \
|
||||
cond-phi-shared/loop-role/merge-inloop reject class",
|
||||
effect: "trace loop-merge plans, selection collisions, and merge phis",
|
||||
},
|
||||
EnvVar {
|
||||
name: "METAL2VULKAN_EXIT_WHY",
|
||||
default: "off",
|
||||
effect: "log each illegal structured-exit edge exit_check finds (EXIT-ILLEGAL \
|
||||
innermost-header/merge/block->succ), surfacing why a block escapes its innermost \
|
||||
construct",
|
||||
effect: "trace illegal structured-exit edges and their innermost constructs",
|
||||
},
|
||||
EnvVar {
|
||||
name: "METAL2VULKAN_SWITCH_TAIL_WHY",
|
||||
default: "off",
|
||||
effect: "log the switch-case shared-continuation candidates privatize_dominated_region's \
|
||||
deep-shared clone loop considers each round",
|
||||
effect: "trace switch-case shared-continuation cloning candidates",
|
||||
},
|
||||
];
|
||||
|
||||
/// Multi-line `--help` block listing every registry var.
|
||||
pub fn help_text() -> String {
|
||||
let mut out = String::from("environment variables:\n");
|
||||
let mut out = String::from(
|
||||
"environment variables (debug toggles are enabled by presence, regardless of value):\n",
|
||||
);
|
||||
for v in REGISTRY {
|
||||
out.push_str(&format!(
|
||||
" {:<32} {} [default: {}]\n",
|
||||
|
||||
+64
-9
@@ -7,7 +7,7 @@ use crate::spirv_module::load_bytes;
|
||||
const FC_DEFINED_NAME_PREFIX: &str = "__metal2vulkan.MTL_FC_DEFINED_";
|
||||
|
||||
/// Parse the FC index `N` out of an `air.fc_initializer` global's mangled name — the stable
|
||||
/// `...MTL_FC_INIT_<N>_<suffix>` shape the AIR/LLVM backend emits for a `[[function_constant(N)]]`.
|
||||
/// `...MTL_FC_INIT_<N>_<suffix>` shape present in AIR for a `[[function_constant(N)]]`.
|
||||
/// Returns `None` for any name lacking that ABI marker (working copies, ordinary globals), so this
|
||||
/// keys only on the documented Metal function-constant machinery, never on a shader-specific name.
|
||||
pub(crate) fn fc_init_index(name: &str) -> Option<u32> {
|
||||
@@ -325,9 +325,8 @@ fn materialize_zero_fc_initializers(module: &mut crate::spirv_module::Module) ->
|
||||
true
|
||||
}
|
||||
|
||||
fn fc_lanes_from_le_value(value: u64, width: u32, count: u32) -> Vec<u64> {
|
||||
fn fc_lanes_from_le_bytes(bytes: &[u8], width: u32, count: u32) -> Vec<u64> {
|
||||
let width_bytes = (width as usize).div_ceil(8).min(8);
|
||||
let bytes = value.to_le_bytes();
|
||||
(0..count)
|
||||
.map(|lane| {
|
||||
let start = lane as usize * width_bytes;
|
||||
@@ -342,6 +341,10 @@ fn fc_lanes_from_le_value(value: u64, width: u32, count: u32) -> Vec<u64> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn fc_scalar_from_le_bytes(bytes: &[u8], width: u32) -> u64 {
|
||||
fc_lanes_from_le_bytes(bytes, width, 1)[0]
|
||||
}
|
||||
|
||||
fn int_constant_id(
|
||||
scalar_ty: u32,
|
||||
width: u32,
|
||||
@@ -417,13 +420,40 @@ pub fn specialize_function_constants_zero(spv: &[u8]) -> Result<Vec<u8>, String>
|
||||
/// error, so a stale behavior-changing override can never silently no-op. An absent zero override
|
||||
/// is harmless when translation has already erased every use of that FC.
|
||||
pub fn specialize_function_constants(spv: &[u8], values: &[(u32, u64)]) -> Result<Vec<u8>, String> {
|
||||
let bytes = values
|
||||
.iter()
|
||||
.map(|(index, value)| (*index, value.to_le_bytes().to_vec()))
|
||||
.collect::<Vec<_>>();
|
||||
specialize_function_constant_bytes_impl(spv, &bytes, false)
|
||||
}
|
||||
|
||||
/// Bake exact little-endian scalar or vector payloads into Metal function constants.
|
||||
///
|
||||
/// Unlike [`specialize_function_constants`], this entry point is not limited to one `u64` and can
|
||||
/// therefore represent the full 2/3/4-lane Metal vector ABI. The SPIR-V variable type determines
|
||||
/// the exact payload width, and every payload must match it exactly.
|
||||
pub fn specialize_function_constant_bytes(
|
||||
spv: &[u8],
|
||||
values: &[(u32, Vec<u8>)],
|
||||
) -> Result<Vec<u8>, String> {
|
||||
specialize_function_constant_bytes_impl(spv, values, true)
|
||||
}
|
||||
|
||||
fn specialize_function_constant_bytes_impl(
|
||||
spv: &[u8],
|
||||
values: &[(u32, Vec<u8>)],
|
||||
exact_payload_size: bool,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
use crate::spirv_module::Instruction;
|
||||
use crate::spirv_module::Operand;
|
||||
use spirv::Op;
|
||||
if values.is_empty() {
|
||||
return Ok(spv.to_vec());
|
||||
}
|
||||
let want: std::collections::HashMap<u32, u64> = values.iter().copied().collect();
|
||||
let want: std::collections::HashMap<u32, &[u8]> = values
|
||||
.iter()
|
||||
.map(|(index, bytes)| (*index, bytes.as_slice()))
|
||||
.collect();
|
||||
let mut module = load_bytes(spv).map_err(|e| format!("SPIR-V load: {e:?}"))?;
|
||||
|
||||
// OpName: var id -> FC index, restricted to `MTL_FC_INIT_<N>` globals.
|
||||
@@ -496,7 +526,9 @@ pub fn specialize_function_constants(spv: &[u8], values: &[(u32, u64)]) -> Resul
|
||||
let Some(&idx) = var_index.get(&vid) else {
|
||||
continue;
|
||||
};
|
||||
let Some(&val) = want.get(&idx) else { continue };
|
||||
let Some(&bytes) = want.get(&idx) else {
|
||||
continue;
|
||||
};
|
||||
let ptr_ty = inst
|
||||
.result_type
|
||||
.ok_or_else(|| format!("FC var %{vid} has no result type"))?;
|
||||
@@ -504,6 +536,14 @@ pub fn specialize_function_constants(spv: &[u8], values: &[(u32, u64)]) -> Resul
|
||||
.get(&ptr_ty)
|
||||
.ok_or_else(|| format!("FC var %{vid}: pointer type %{ptr_ty} has no pointee"))?;
|
||||
if let Some(&width) = scalar_width.get(&scalar_ty) {
|
||||
let required = (width as usize).div_ceil(8);
|
||||
if exact_payload_size && bytes.len() != required {
|
||||
return Err(format!(
|
||||
"FC index {idx}: payload has {} bytes, scalar type requires {required}",
|
||||
bytes.len()
|
||||
));
|
||||
}
|
||||
let val = fc_scalar_from_le_bytes(bytes, width);
|
||||
let cid = int_constant_id(
|
||||
scalar_ty,
|
||||
width,
|
||||
@@ -521,7 +561,14 @@ pub fn specialize_function_constants(spv: &[u8], values: &[(u32, u64)]) -> Resul
|
||||
));
|
||||
};
|
||||
let width = scalar_width[&component_ty];
|
||||
let lanes = fc_lanes_from_le_value(val, width, count);
|
||||
let required = (width as usize).div_ceil(8) * count as usize;
|
||||
if exact_payload_size && bytes.len() != required {
|
||||
return Err(format!(
|
||||
"FC index {idx}: payload has {} bytes, vector type requires {required}",
|
||||
bytes.len()
|
||||
));
|
||||
}
|
||||
let lanes = fc_lanes_from_le_bytes(bytes, width, count);
|
||||
let mut const_ids = Vec::with_capacity(lanes.len() + 1);
|
||||
for lane in &lanes {
|
||||
const_ids.push(int_constant_id(
|
||||
@@ -563,7 +610,10 @@ pub fn specialize_function_constants(spv: &[u8], values: &[(u32, u64)]) -> Resul
|
||||
let missing: Vec<u32> = requested
|
||||
.difference(&applied)
|
||||
.copied()
|
||||
.filter(|index| want.get(index).copied().unwrap_or(0) != 0)
|
||||
.filter(|index| {
|
||||
want.get(index)
|
||||
.is_some_and(|bytes| bytes.iter().any(|byte| *byte != 0))
|
||||
})
|
||||
.collect();
|
||||
if !missing.is_empty() {
|
||||
return Err(format!(
|
||||
@@ -1933,7 +1983,12 @@ mod tests {
|
||||
vec![name(5, "_ZN3app12shader_stateE.MTL_FC_INIT_0_Dv4_j")],
|
||||
);
|
||||
|
||||
let out = specialize_function_constants(&bytes, &[(0, 1)]).expect("specialize");
|
||||
let payload = [1u32, 2, 3, 4]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect::<Vec<_>>();
|
||||
let out = specialize_function_constant_bytes(&bytes, &[(0, payload)])
|
||||
.expect("specialize full vector");
|
||||
let m = load_bytes(&out).expect("reload");
|
||||
let vector_init = m
|
||||
.types_global_values
|
||||
@@ -1974,7 +2029,7 @@ mod tests {
|
||||
other => panic!("unexpected composite operand: {other:?}"),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(lane_values, vec![1, 0, 0, 0]);
|
||||
assert_eq!(lane_values, vec![1, 2, 3, 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+458
-62
@@ -1,11 +1,9 @@
|
||||
//! metal2vulkan — Metal AIR (LLVM bitcode) -> Vulkan SPIR-V, via a native LLVM-IR emitter.
|
||||
//!
|
||||
//! The decisive difference from the legacy `metal2vulkanspirv` crate: that one targeted the OpenCL/Kernel
|
||||
//! SPIR-V backend (`spirv64-unknown-unknown`), which emits UNSTRUCTURED, Physical64/OpenCL-dialect
|
||||
//! SPIR-V, then did a ~1300-line regex dialect rewrite + a hand-written structurizer to reach a
|
||||
//! Vulkan-legal module. Here the native emitter produces `OpCapability Shader` / `Logical GLSL450`
|
||||
//! SPIR-V directly from sanitized AIR LLVM IR. What remains is the stage *interface* — done as a
|
||||
//! handful of passes on the crate-owned SPIR-V module representation (see `passes/`).
|
||||
//! The native emitter produces `OpCapability Shader` / `Logical GLSL450` SPIR-V directly from
|
||||
//! sanitized AIR LLVM IR. Crate-owned retained-SPIR-V passes then build the Vulkan stage interface,
|
||||
//! lower residual AIR operations, normalize memory access and control flow, and finalize the module
|
||||
//! (see [`passes`]).
|
||||
//!
|
||||
//! Pipeline: `.air|.ll` -> llvm-dis -> sanitize -> native Vulkan SPIR-V emit -> retained crate
|
||||
//! module -> interface+lowering passes -> assemble -> spirv-val (vulkan1.3).
|
||||
@@ -18,11 +16,13 @@
|
||||
// without improving clarity, so both are accepted crate-wide rather than scattered per-site.
|
||||
#![allow(clippy::too_many_arguments, clippy::type_complexity)]
|
||||
|
||||
pub mod air_intrinsics;
|
||||
pub mod as_shadow;
|
||||
mod emit_sidecar;
|
||||
pub mod env_vars;
|
||||
mod fc_specialize;
|
||||
mod layout;
|
||||
pub mod linked_functions;
|
||||
pub mod meta;
|
||||
pub mod native;
|
||||
pub mod passes;
|
||||
@@ -37,20 +37,20 @@ mod spirv_variable_ptr;
|
||||
pub mod tools;
|
||||
pub(crate) mod types;
|
||||
|
||||
pub use fc_specialize::{specialize_function_constants, specialize_function_constants_zero};
|
||||
pub use passthrough::translate_passthrough;
|
||||
pub use fc_specialize::{
|
||||
specialize_function_constant_bytes, specialize_function_constants,
|
||||
specialize_function_constants_zero,
|
||||
};
|
||||
pub use passthrough::{translate_passthrough, translate_vertex_observer};
|
||||
use primary_retry::*;
|
||||
|
||||
use crate::spirv_module::{load_bytes as load_owned_module, Module};
|
||||
use std::path::Path;
|
||||
|
||||
/// Translate an AIR/`.ll` shader to Vulkan SPIR-V bytes for the given stage. On success returns the
|
||||
/// assembled SPIR-V words. The caller validates with `tools::spirv_val`.
|
||||
/// Detect the shader stage from the AIR's own `!air.vertex`/`!air.fragment`/`!air.kernel` metadata
|
||||
/// (which the compiler emits and SPIR-V emission later drops). Lets the caller translate a captured
|
||||
/// AIR blob without knowing its stage — the kext forwards raw AIR; the stage is intrinsic to the
|
||||
/// module. A fragment shader run as `--stage vertex` (or vice-versa) mis-maps the [[position]] role,
|
||||
/// so detecting beats guessing.
|
||||
/// (which SPIR-V emission later drops). This lets callers translate an AIR blob without separately
|
||||
/// carrying its stage. Supplying the wrong stage can mis-map stage-interface roles, so prefer this
|
||||
/// function when the metadata is present.
|
||||
pub fn detect_stage(src: &str, tmp: &Path) -> Result<passes::Stage, String> {
|
||||
let ll = tools::air_to_sanitized_ll(src, tmp)?;
|
||||
if ll.contains("!air.vertex =") {
|
||||
@@ -67,6 +67,12 @@ pub fn detect_stage(src: &str, tmp: &Path) -> Result<passes::Stage, String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Translate an AIR bitcode or LLVM-IR file to Vulkan SPIR-V for `stage`.
|
||||
///
|
||||
/// The final module is validated with `spirv-val` under the Vulkan 1.3 environment. A primary module
|
||||
/// that fails validation may enter the validation-gated retry cascade; only a validating candidate
|
||||
/// is returned. `tmp` is caller-owned scratch space and may be reused sequentially, but callers
|
||||
/// should give concurrent translations separate directories.
|
||||
pub fn translate(src: &str, stage: passes::Stage, tmp: &Path) -> Result<Vec<u8>, String> {
|
||||
translate_with_options(src, stage, tmp, passes::TransformOptions::default())
|
||||
}
|
||||
@@ -81,8 +87,7 @@ pub fn translate_with_options(
|
||||
translate_sanitized_native_with_options(&san_ll, stage, tmp, options)
|
||||
}
|
||||
|
||||
/// Translate already-sanitized LLVM IR through the native emitter. The LLVM `llc` backend and its
|
||||
/// crash-workaround passes are not used.
|
||||
/// Translate already-sanitized LLVM IR through the native emitter.
|
||||
pub fn translate_sanitized_native(
|
||||
san_ll: &str,
|
||||
stage: passes::Stage,
|
||||
@@ -109,23 +114,6 @@ fn reject_unsupported_metal_linked_functions(san_ll: &str) -> Result<(), String>
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
if san_ll.contains(".MTL_CONTROL_POINT_FN")
|
||||
|| san_ll.contains("\"air.patch_control_point_function\"")
|
||||
{
|
||||
return Err(
|
||||
"native emitter: unsupported Metal patch control point function; tessellation patch \
|
||||
inputs are not yet lowered to the Vulkan tessellation interface"
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
if san_ll.contains("@air.simd_prefix_exclusive_sum.u.v4i16") {
|
||||
return Err(
|
||||
"native emitter: unsupported AIR u16x4 SIMD exclusive prefix scan; the current \
|
||||
subgroup lowering does not preserve Metal radix semantics through aliased \
|
||||
threadgroup storage"
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -273,7 +261,7 @@ pub fn translate_sanitized_native_with_options(
|
||||
// pointer arm over-indexed as an array), which they could not before when the lowering lived only
|
||||
// inside `emit_vulkan_spirv` (the retries bypass that entry). Floor-safe by construction: the
|
||||
// rewrite is a no-op unless the module calls `air.simdgroup_async_copy_2d`, and such modules fail
|
||||
// the emitter outright today. See `native::async_copy` + journal AIR2VK-ASYNC-COPY-CLEAR.
|
||||
// the emitter outright today. See `native::async_copy` and its structural regression tests.
|
||||
let lowered = lower_async_copy_if_enabled(san_ll);
|
||||
let san_ll = lowered.as_str();
|
||||
reject_unsupported_metal_linked_functions(san_ll)?;
|
||||
@@ -293,10 +281,42 @@ pub fn translate_sanitized_native_with_options(
|
||||
)
|
||||
}
|
||||
|
||||
/// Like [`translate`] but also returns the [`reflect::ShaderReflection`] — the stage-interface
|
||||
/// facade (descriptor bindings, vertex attributes, varyings, render targets) the translator already
|
||||
/// parsed, so a downstream consumer never re-reflects the emitted SPIR-V. The SPIR-V bytes are
|
||||
/// byte-identical to [`translate`]; reflection is a pure re-shaping of the parsed metadata.
|
||||
/// Translate sanitized AIR after resolving authored direct visible-function references and
|
||||
/// function-table slots to exact linked AIR definitions. This is the portable Logical-SPIR-V
|
||||
/// alternative to Metal's runtime function linker and function pointers.
|
||||
pub fn translate_sanitized_native_linked_with_options(
|
||||
san_ll: &str,
|
||||
stage: passes::Stage,
|
||||
tmp: &Path,
|
||||
options: passes::TransformOptions,
|
||||
linkage: &linked_functions::LinkedFunctionLinkage,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let stage_name = match stage {
|
||||
passes::Stage::Kernel => "kernel",
|
||||
passes::Stage::Vertex => "vertex",
|
||||
passes::Stage::Fragment => "fragment",
|
||||
};
|
||||
let entry_name = meta::entry_name(san_ll, stage_name)
|
||||
.ok_or_else(|| format!("linked translation found no AIR {stage_name} entry"))?;
|
||||
let specialized =
|
||||
linked_functions::specialize_visible_function_tables(san_ll, &entry_name, linkage)?;
|
||||
let specialized =
|
||||
linked_functions::specialize_visible_function_references(&specialized, linkage)?;
|
||||
let specialized = linked_functions::specialize_opaque_triangle_intersection_tables(
|
||||
&specialized,
|
||||
&entry_name,
|
||||
linkage,
|
||||
)?;
|
||||
translate_sanitized_native_with_options(&specialized, stage, tmp, options)
|
||||
}
|
||||
|
||||
/// Like [`translate`] but also returns the [`reflect::ShaderReflection`] needed to integrate the
|
||||
/// resulting module.
|
||||
///
|
||||
/// Interface facts come from AIR metadata and the translator's descriptor ABI. Conservative buffer
|
||||
/// footprints come from read-only analysis of the final adopted SPIR-V, after retry selection. The
|
||||
/// analysis does not mutate the module, so the returned SPIR-V remains byte-identical to
|
||||
/// [`translate`] for the same input, stage, and options.
|
||||
pub fn translate_reflected(
|
||||
src: &str,
|
||||
stage: passes::Stage,
|
||||
@@ -320,6 +340,38 @@ pub fn translate_reflected_with_options(
|
||||
Ok((spv, reflection))
|
||||
}
|
||||
|
||||
/// Reflect sanitized AIR without requiring its executable lowering to be supported yet.
|
||||
///
|
||||
/// Authored dependency validation uses this for link-time resources such as function tables: their
|
||||
/// stage interface is fully described by AIR metadata even before indirect calls have been resolved
|
||||
/// to linked function definitions. The returned shape is identical to the reflection attached to a
|
||||
/// successful translated module.
|
||||
pub fn reflect_sanitized(
|
||||
san_ll: &str,
|
||||
stage: passes::Stage,
|
||||
options: passes::TransformOptions,
|
||||
) -> Result<reflect::ShaderReflection, String> {
|
||||
let lowered = lower_async_copy_if_enabled(san_ll);
|
||||
let san_ll = lowered.as_str();
|
||||
let stage_meta = parse_stage_meta(san_ll, stage);
|
||||
let options = options_for_air(san_ll, options);
|
||||
let mut reflection = build_reflection(
|
||||
stage,
|
||||
stage_meta.frag.as_ref(),
|
||||
stage_meta.vert.as_ref(),
|
||||
stage_meta.kern.as_ref(),
|
||||
stage_meta.entry_name.as_deref(),
|
||||
&options,
|
||||
);
|
||||
reflection.function_constants = meta::parse_function_constants(san_ll);
|
||||
reflection.refine_buffer_access_from_entry(san_ll);
|
||||
reflection.add_static_samplers(san_ll)?;
|
||||
if stage == passes::Stage::Kernel && has_device_address_pointer_load(san_ll) {
|
||||
reflection.add_buffer_address_table();
|
||||
}
|
||||
Ok(reflection)
|
||||
}
|
||||
|
||||
/// [`translate_sanitized_native_with_options`] plus the reflection facade. See [`translate_reflected`].
|
||||
pub fn translate_sanitized_native_reflected(
|
||||
san_ll: &str,
|
||||
@@ -340,14 +392,12 @@ pub fn translate_sanitized_native_reflected(
|
||||
stage_meta.entry_name.as_deref(),
|
||||
&options,
|
||||
);
|
||||
// Function constants are a cross-stage IR fact (not in the per-stage meta): scan the sanitized
|
||||
// IR once so a consumer can discover the module's spec-ids without walking SPIR-V.
|
||||
reflection.function_constants = meta::parse_function_constants(san_ll);
|
||||
reflection.refine_buffer_access_from_entry(san_ll);
|
||||
// AIR constexpr samplers are module globals rather than entry parameters, so stage metadata
|
||||
// does not carry them. Reflect their decoded state and the same first-free sampler-band
|
||||
// allocation used by the interface pass before returning the consumer contract.
|
||||
reflection.add_static_samplers(san_ll)?;
|
||||
if stage == passes::Stage::Kernel && has_device_address_pointer_load(san_ll) {
|
||||
reflection.add_buffer_address_table();
|
||||
}
|
||||
let spv = translate_sanitized_with_meta(
|
||||
san_ll,
|
||||
stage,
|
||||
@@ -360,6 +410,7 @@ pub fn translate_sanitized_native_reflected(
|
||||
options,
|
||||
true,
|
||||
)?;
|
||||
reflection.add_buffer_footprints(&spv)?;
|
||||
Ok((spv, reflection))
|
||||
}
|
||||
|
||||
@@ -399,7 +450,7 @@ fn translate_native_no_retry_with_meta(
|
||||
kern: Option<&meta::KernMeta>,
|
||||
entry_name: Option<&str>,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
// `tools::llc_vulkan_spirv` is the in-process native emitter (no subprocess); `finish_module` is
|
||||
// `tools::emit_vulkan_spirv` is the in-process native emitter (no subprocess); `finish_module` is
|
||||
// the shared passes tail every translate path runs. Together they are the default path's output
|
||||
// up to (but not including) `spirv_val_bytes` and the tier cascade.
|
||||
emit_finish_primary_module(
|
||||
@@ -442,6 +493,13 @@ pub fn translate_native_primary_validated(
|
||||
let Err(validation_error) = tools::spirv_val_bytes(&primary, tmp) else {
|
||||
return Ok(primary);
|
||||
};
|
||||
// The corpus audit calls this primary-only gate before the full retry cascade. Make its existing
|
||||
// default-off dump control capture the actual first-invalid module, so a later retry error cannot
|
||||
// hide where validation first failed. Diagnostics must never affect translation if the requested
|
||||
// dump path itself is unavailable.
|
||||
if let Some(path) = env_vars::retry_dump() {
|
||||
let _ = std::fs::write(path, &primary);
|
||||
}
|
||||
if let Some(primary) = primary_xbind_phi_psb_for_validation_error(
|
||||
&primary_module,
|
||||
&primary,
|
||||
@@ -462,6 +520,9 @@ pub fn translate_native_primary_validated(
|
||||
passes::TransformOptions::default(),
|
||||
true,
|
||||
);
|
||||
if let Some(primary) = primary_storage_buffer_raw_feed_if_needed(&validation_error, &retry) {
|
||||
return Ok(primary);
|
||||
}
|
||||
Ok(primary_primitive_phi_metadata_if_needed(
|
||||
&validation_error,
|
||||
san_ll,
|
||||
@@ -605,7 +666,11 @@ fn finish_module(
|
||||
options: passes::TransformOptions,
|
||||
rewrites: FinishRewrites,
|
||||
) -> Result<FinishedModule, String> {
|
||||
let (mut out, sidecar) = passes::transform_with_options_and_sidecar(
|
||||
let retry_debug = env_vars::retry_debug();
|
||||
if retry_debug {
|
||||
eprintln!("[retry-debug] finish: passes start");
|
||||
}
|
||||
let (mut out, mut sidecar) = passes::transform_with_options_and_sidecar(
|
||||
emitted.module,
|
||||
emitted.sidecar,
|
||||
stage,
|
||||
@@ -615,11 +680,21 @@ fn finish_module(
|
||||
entry_name,
|
||||
options,
|
||||
)?;
|
||||
if retry_debug {
|
||||
eprintln!("[retry-debug] finish: passes complete; native rewrites start");
|
||||
}
|
||||
// M4: legalize illegal logical-pointer phis (Private/Function/UniformConstant `OpPhi`) on the
|
||||
// PRIMARY emit path via the phi-the-index rewrite, so those functions validate directly instead of
|
||||
// shipping only via retry rescue. Floor-safe by construction (it touches only already-invalid
|
||||
// logical-pointer phis, never a validating module).
|
||||
native::rewrite_logical_pointer_phis_module(&mut out);
|
||||
let mut native_pointer_changed = native::rewrite_logical_pointer_phis_module(&mut out);
|
||||
// Opaque AIR pointers can select a real StorageBuffer byte view against a typed Private fallback.
|
||||
// Such a pointer select is invalid under Logical addressing regardless of VariablePointers.
|
||||
// Load each concrete arm in its own storage domain and select values; pointer escapes remain an
|
||||
// honest failure.
|
||||
while native::rewrite_mixed_storage_pointer_select_loads_module(&mut out) {
|
||||
native_pointer_changed = true;
|
||||
}
|
||||
// M4: legalize integer-width phi mismatches (a narrow `uint` loop phi fed a wide `ulong` induction
|
||||
// back-edge value) by truncating the wide incoming to the phi's result type. Floor-safe (touches
|
||||
// only already-invalid integer phis). Runs after the pointer-phi rewrite so it can also legalize
|
||||
@@ -629,7 +704,7 @@ fn finish_module(
|
||||
// loop-body value used raw in a post-loop block the restructured CFG can reach without the defining
|
||||
// block), by register-demoting the offending value to a function-scope OpVariable. Floor-safe by
|
||||
// construction — a validating module has every def dominating its uses, so this never fires on one.
|
||||
native::demote_nondominating_values_module(&mut out);
|
||||
native_pointer_changed |= native::demote_nondominating_values_module(&mut out);
|
||||
// Workgroup struct-padding clears emitted as byte-addressed `uchar*` stores are not legal
|
||||
// Logical SPIR-V when rooted at a struct pointer. Drop the provably-padding zero stores before
|
||||
// validation so the normal retry cascade only sees semantic failures.
|
||||
@@ -640,7 +715,39 @@ fn finish_module(
|
||||
// `steel_attention` family), so the PRIMARY structured emit validates instead of shipping only via
|
||||
// the relooper retry. Floor-safe by construction (a valid loop is single-entry). Runs after the phi
|
||||
// rewrites; the attention rows also need the integer-width phi legalization above.
|
||||
native::split_multientry_loop_selection_exits_module(&mut out);
|
||||
let native_cfg_changed = native::split_multientry_loop_selection_exits_module(&mut out);
|
||||
if native_pointer_changed {
|
||||
passes::repair_exact_raw_byte_loads_after_native_rewrites(&mut out, &sidecar, entry_name)?;
|
||||
}
|
||||
if retry_debug {
|
||||
eprintln!("[retry-debug] finish: native rewrites complete; cfg repair start");
|
||||
}
|
||||
// The complete-module rewrites above run after the main passes pipeline and can introduce or
|
||||
// redirect CFG edges, or synthesize index phis from pointer phis. Re-establish the shared
|
||||
// merge/continue/phi invariant before ids are canonicalized so late native composition cannot
|
||||
// bypass structured-CFG repair.
|
||||
if native_cfg_changed || native_pointer_changed {
|
||||
out = passes::repair_structured_cfg_after_native_rewrites(out, stage, entry_name)?;
|
||||
}
|
||||
// CFG repair can introduce a forwarding phi after the earlier loop-closed-SSA pass. Re-check the
|
||||
// completed graph at this mutation boundary; the repair is self-gating and touches only a value
|
||||
// whose definition does not dominate its use.
|
||||
if native::demote_nondominating_values_module(&mut out) {
|
||||
out = passes::repair_structured_cfg_after_native_rewrites(out, stage, entry_name)?;
|
||||
}
|
||||
// CFG repair can split an edge and leave a forwarding phi with exactly one incoming pair. Fold
|
||||
// that SSA identity before validation and canonicalization. Besides avoiding redundant phis,
|
||||
// this prevents a stale pre-interface pointer result type from wrapping a refined image value.
|
||||
native::collapse_single_incoming_phis_module(&mut out);
|
||||
while native::rewrite_mixed_storage_pointer_select_loads_module(&mut out) {}
|
||||
native::rewrite_private_vector_word_loads_module(&mut out);
|
||||
native::repair_sampled_image_result_types_module(&mut out);
|
||||
// Complete-module pointer rewrites and their exact-raw repair can rematerialize access chains
|
||||
// after the main transform's null cleanup. Re-close the invariant after the final producer.
|
||||
passes::neutralize_null_access_chains_after_native_rewrites(&mut out, entry_name)?;
|
||||
if retry_debug {
|
||||
eprintln!("[retry-debug] finish: cfg repair complete; canonicalize start");
|
||||
}
|
||||
// Renumber all ids into a deterministic, serialized-order canonical form. This format
|
||||
// normalization keeps equivalent producer paths directly comparable and SPIR-V-level diffs
|
||||
// meaningful.
|
||||
@@ -649,12 +756,47 @@ fn finish_module(
|
||||
.iter()
|
||||
.map(|fact| fact.id)
|
||||
.collect::<Vec<_>>();
|
||||
passes::canonicalize_ids_and_remap(&mut out, &mut retained_global_ids);
|
||||
passes::canonicalize_ids_and_remap_sidecar(&mut out, &mut retained_global_ids, &mut sidecar);
|
||||
if retry_debug {
|
||||
eprintln!("[retry-debug] finish: canonicalize complete");
|
||||
}
|
||||
let original_module = (rewrites == FinishRewrites::Primary).then(|| out.clone());
|
||||
if rewrites == FinishRewrites::Primary {
|
||||
primary_retry::apply_primary_emit_rewrites_module(&mut out, &mut retained_global_ids);
|
||||
let (primary_pointer_changed, primary_cfg_changed) =
|
||||
primary_retry::apply_primary_emit_rewrites_module(
|
||||
&mut out,
|
||||
&mut retained_global_ids,
|
||||
&mut sidecar,
|
||||
);
|
||||
if primary_pointer_changed {
|
||||
passes::repair_exact_raw_byte_loads_after_native_rewrites(
|
||||
&mut out, &sidecar, entry_name,
|
||||
)?;
|
||||
}
|
||||
// Primary-only rewrites deliberately run after canonical id remapping and can perform their
|
||||
// own CFG surgery. They are the final mutation boundary, so close the same structured-CFG
|
||||
// invariant here as well instead of assuming the earlier finish-time repair still applies.
|
||||
if primary_cfg_changed {
|
||||
out = passes::repair_structured_cfg_after_native_rewrites(out, stage, entry_name)?;
|
||||
}
|
||||
if native::demote_nondominating_values_module(&mut out) {
|
||||
out = passes::repair_structured_cfg_after_native_rewrites(out, stage, entry_name)?;
|
||||
}
|
||||
native::collapse_single_incoming_phis_module(&mut out);
|
||||
while native::rewrite_mixed_storage_pointer_select_loads_module(&mut out) {}
|
||||
native::rewrite_private_vector_word_loads_module(&mut out);
|
||||
native::repair_sampled_image_result_types_module(&mut out);
|
||||
passes::neutralize_null_access_chains_after_native_rewrites(&mut out, entry_name)?;
|
||||
native::drop_unused_values_module(&mut out);
|
||||
}
|
||||
// Every late producer above may substitute a pointer carrier after its users were typed. Close
|
||||
// the SPIR-V access-chain contract at the final module boundary: the result pointer keeps its
|
||||
// pointee but always inherits the actual base pointer's storage class.
|
||||
native::reconcile_access_chain_storage_classes_module(&mut out);
|
||||
let bytes = assemble_finished_module(&out);
|
||||
if retry_debug {
|
||||
eprintln!("[retry-debug] finish: assembly complete");
|
||||
}
|
||||
Ok(FinishedModule {
|
||||
module: out,
|
||||
bytes,
|
||||
@@ -697,7 +839,7 @@ pub fn translate_raw_tiers_probe(
|
||||
})
|
||||
};
|
||||
vec![
|
||||
run(tools::llc_vulkan_spirv_all_buffers_raw_with_sidecar(
|
||||
run(tools::emit_vulkan_spirv_all_buffers_raw_with_sidecar(
|
||||
san_ll,
|
||||
tmp,
|
||||
stage_meta.kern.as_ref(),
|
||||
@@ -710,7 +852,7 @@ pub fn translate_raw_tiers_probe(
|
||||
),
|
||||
)),
|
||||
run(
|
||||
tools::llc_vulkan_spirv_all_buffers_raw_with_workgroup_sidecar(
|
||||
tools::emit_vulkan_spirv_all_buffers_raw_with_workgroup_sidecar(
|
||||
san_ll,
|
||||
tmp,
|
||||
stage_meta.kern.as_ref(),
|
||||
@@ -740,7 +882,7 @@ pub fn translate_bda_probe(
|
||||
reject_unsupported_metal_linked_functions(san_ll)?;
|
||||
let stage_meta = parse_stage_meta(san_ll, stage);
|
||||
let opts = passes::TransformOptions::default();
|
||||
tools::llc_vulkan_spirv_all_buffers_raw_bda_with_sidecar(
|
||||
tools::emit_vulkan_spirv_all_buffers_raw_bda_with_sidecar(
|
||||
san_ll,
|
||||
tmp,
|
||||
stage_meta.kern.as_ref(),
|
||||
@@ -795,8 +937,26 @@ fn translate_sanitized_with_meta(
|
||||
options,
|
||||
psb_retry_enabled,
|
||||
);
|
||||
// Within the relooper's hard cap, a large source CFG is owned by the global structurizers.
|
||||
// Above that cap, speculative construct-tree pre-routing can consume the entire translation
|
||||
// budget before a valid primary is even attempted; try the primary first and let validation
|
||||
// select later retries. Count structural LLVM blocks without parsing instruction bodies.
|
||||
let max_function_blocks = sanitized_max_function_basic_block_count(san_ll);
|
||||
if large_cfg_relooper_eligible(max_function_blocks) {
|
||||
if let Some(relooped) = rc.raw_feed_then_relooper() {
|
||||
return Ok(relooped);
|
||||
}
|
||||
if rc.large_cfg_construct_tree_eligible() {
|
||||
if let Some(constructed) = rc.construct_tree_retry() {
|
||||
return Ok(constructed);
|
||||
}
|
||||
} else if rc.retry_debug_on {
|
||||
eprintln!("[retry-debug] large cfg: construct-tree skipped after non-CFG feed failure");
|
||||
}
|
||||
}
|
||||
let retry_debug_on = rc.retry_debug_on;
|
||||
let translated = match tools::llc_vulkan_spirv_with_sidecar(
|
||||
let has_device_address_pointer = has_device_address_pointer_load(san_ll);
|
||||
let translated = match tools::emit_vulkan_spirv_with_sidecar(
|
||||
san_ll,
|
||||
tmp,
|
||||
rc.kern,
|
||||
@@ -834,13 +994,42 @@ fn translate_sanitized_with_meta(
|
||||
} else {
|
||||
let out = assemble_finished_module(&out_module);
|
||||
let validation_error = primary_validation.expect_err("checked above");
|
||||
if let Some(primary) = primary_xbind_phi_psb_for_validation_error(
|
||||
if retry_debug_on {
|
||||
eprintln!(
|
||||
"[retry-debug] primary module spirv-val failed: {}",
|
||||
validation_error
|
||||
.lines()
|
||||
.take(4)
|
||||
.collect::<Vec<_>>()
|
||||
.join(" | ")
|
||||
);
|
||||
}
|
||||
let primary_block_count = primary_module
|
||||
.functions
|
||||
.iter()
|
||||
.map(|function| function.blocks.len())
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
// The whole-function relooper cannot own an emitted graph beyond its hard cap, but
|
||||
// static function-constant arms can be the only reason it grew past that ceiling.
|
||||
// First prune and reloop the already-built primary; only if it cannot shrink into
|
||||
// the hard budget, give the compact source CFG one construct-tree attempt. Raw and
|
||||
// SROA re-emissions remain skipped for this oversized case.
|
||||
if primary_block_count > native::CFG_EMIT_RELOOPER_MAX_BLOCKS {
|
||||
primary_cfg_prune_then_relooper_if_needed(&validation_error, &primary, tmp)
|
||||
.or_else(|| primary_construct_tree_if_needed(&validation_error, &rc))
|
||||
.ok_or(validation_error)
|
||||
} else if let Some(primary) = primary_xbind_phi_psb_for_validation_error(
|
||||
&primary_module,
|
||||
&primary,
|
||||
&validation_error,
|
||||
tmp,
|
||||
) {
|
||||
Ok(primary)
|
||||
} else if let Some(primary) =
|
||||
primary_storage_buffer_raw_feed_if_needed(&validation_error, &rc)
|
||||
{
|
||||
Ok(primary)
|
||||
} else if let Some(primary) = primary_primitive_phi_metadata_if_needed(
|
||||
&validation_error,
|
||||
san_ll,
|
||||
@@ -875,6 +1064,10 @@ fn translate_sanitized_with_meta(
|
||||
&rc,
|
||||
) {
|
||||
Ok(primary)
|
||||
} else if let Some(primary) =
|
||||
primary_cfg_prune_if_needed(&validation_error, &primary, &rc)
|
||||
{
|
||||
Ok(primary)
|
||||
} else if let Some(primary) =
|
||||
primary_construct_tree_if_needed(&validation_error, &rc)
|
||||
{
|
||||
@@ -933,13 +1126,25 @@ fn translate_sanitized_with_meta(
|
||||
if native::classify_validation_error(&e)
|
||||
== native::ValidationClass::PointerTyping =>
|
||||
{
|
||||
let fc_promote_first = e
|
||||
.contains("reached non-composite")
|
||||
.then(|| {
|
||||
rc.census("val-ptr:fc_promote_logical", rc.fc_promote_logical())
|
||||
})
|
||||
.flatten();
|
||||
let fc_promote_first =
|
||||
validation_error_may_be_fc_private_placeholder(&e)
|
||||
.then(|| {
|
||||
rc.census(
|
||||
"val-ptr:fc_promote_logical",
|
||||
rc.fc_promote_logical(),
|
||||
)
|
||||
})
|
||||
.flatten();
|
||||
Ok(fc_promote_first
|
||||
// A descriptor-root/device-address phi reports as pointer typing on
|
||||
// the Logical primary. Prefer the address-domain BDA emitter before
|
||||
// the generic raw/CFG ladders, but only when LLVM `inttoptr` proves
|
||||
// the physical-address mechanism is actually present.
|
||||
.or_else(|| {
|
||||
has_device_address_pointer
|
||||
.then(|| rc.census("val-ptr:bda", rc.bda_retry()))
|
||||
.flatten()
|
||||
})
|
||||
.or_else(|| rc.census("val-ptr:raw_retry", rc.raw_retry()))
|
||||
.or_else(|| rc.census("val-ptr:prune", rc.prune_retry(&out)))
|
||||
// A Function scalar-integer alloca reinterpreted as smaller-element lanes (the
|
||||
@@ -1131,6 +1336,16 @@ fn translate_sanitized_with_meta(
|
||||
// All adopt-if-validates / floor-safe.
|
||||
Err(_) => Ok(rc
|
||||
.census("val-other:prune", rc.prune_retry(&out))
|
||||
// A logical pointer type mismatch can be the surface form of a device-
|
||||
// address hierarchy: one phi arm is a descriptor-rooted buffer and a
|
||||
// backedge arm is produced by LLVM `inttoptr`. Only try the BDA emitter
|
||||
// when that structural opcode is actually present; its address-domain phi
|
||||
// lowering is adopted only after full SPIR-V validation.
|
||||
.or_else(|| {
|
||||
has_device_address_pointer
|
||||
.then(|| rc.census("val-other:bda", rc.bda_retry()))
|
||||
.flatten()
|
||||
})
|
||||
// A local union alloca whose conflicting typed views live in a CALLEE emits a
|
||||
// structurally-typed chain against the caller's byte-array storage (the DecodeETC2
|
||||
// class: `OpInBoundsAccessChain %uint` with indexes left over on `[N x uchar]`).
|
||||
@@ -1174,6 +1389,23 @@ fn translate_sanitized_with_meta(
|
||||
}
|
||||
}
|
||||
}
|
||||
// A cross-storage select deliberately has no materializable Logical-SPIR-V pointer. If its
|
||||
// first opaque consumer is an internal-helper argument, erase that boundary first: typed
|
||||
// inlining carries the deferred select into the helper and its load/store handlers replay
|
||||
// the concrete arms in value space. This is both the semantically direct repair and far
|
||||
// cheaper than trying whole-module BDA/raw remodelling before the diagnosed mechanism.
|
||||
Err(emit_err)
|
||||
if native::classify_emit_error(&emit_err)
|
||||
== native::EmitErrorClass::DeferredPointerMaterialization =>
|
||||
{
|
||||
let selected_pointer = native::deferred_pointer_materialization_name(&emit_err)
|
||||
.expect("classified deferred pointer error carries its SSA value");
|
||||
rc.census(
|
||||
"emit-deferred-pointer:consumer-inline",
|
||||
rc.pointer_select_consumer_inline_retry(&selected_pointer),
|
||||
)
|
||||
.ok_or(emit_err)
|
||||
}
|
||||
// The default typed emission FAILED outright with a buffer/pointer-typing emit gap the raw
|
||||
// byte-offset model expresses (a reinterpret-load width mismatch or a missing pointer storage
|
||||
// class). Retry raw and adopt it only if it independently validates; the raw bytes may
|
||||
@@ -1275,6 +1507,65 @@ fn translate_sanitized_with_meta(
|
||||
})
|
||||
}
|
||||
|
||||
fn has_device_address_pointer_load(san_ll: &str) -> bool {
|
||||
san_ll.lines().any(|line| {
|
||||
line.split_once('=').is_some_and(|(_, rhs)| {
|
||||
let rhs = rhs.trim_start();
|
||||
rhs.starts_with("inttoptr ")
|
||||
|| (rhs.starts_with("load ptr addrspace(1)")
|
||||
&& rhs.split_once(',').is_some_and(|(_, pointer)| {
|
||||
let pointer = pointer.trim_start();
|
||||
pointer.starts_with("ptr addrspace(1) ")
|
||||
|| pointer.starts_with("ptr addrspace(2) ")
|
||||
}))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn sanitized_max_function_basic_block_count(san_ll: &str) -> usize {
|
||||
let mut current = None::<(usize, bool)>;
|
||||
let mut maximum = 0usize;
|
||||
let finish_count =
|
||||
|(labels, implicit): (usize, bool)| labels.saturating_add(usize::from(implicit)).max(1);
|
||||
for line in san_ll
|
||||
.lines()
|
||||
.filter_map(|line| line.split(';').next().map(str::trim))
|
||||
{
|
||||
if line.starts_with("define ") {
|
||||
if let Some(state) = current.replace((0, false)) {
|
||||
maximum = maximum.max(finish_count(state));
|
||||
}
|
||||
} else if line == "}" {
|
||||
if let Some(state) = current.take() {
|
||||
maximum = maximum.max(finish_count(state));
|
||||
}
|
||||
} else if line.ends_with(':') {
|
||||
if let Some((labels, _)) = current.as_mut() {
|
||||
*labels += 1;
|
||||
}
|
||||
} else if !line.is_empty() {
|
||||
if let Some((0, implicit)) = current.as_mut() {
|
||||
*implicit = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
maximum.max(current.map(finish_count).unwrap_or_default())
|
||||
}
|
||||
|
||||
fn large_cfg_relooper_eligible(max_function_blocks: usize) -> bool {
|
||||
max_function_blocks > native::LARGE_CFG_BLOCK_THRESHOLD
|
||||
&& max_function_blocks <= native::CFG_EMIT_RELOOPER_MAX_BLOCKS
|
||||
}
|
||||
|
||||
fn validation_error_may_be_fc_private_placeholder(error: &str) -> bool {
|
||||
error.contains("reached non-composite") && error.contains("_ptr_Private_")
|
||||
}
|
||||
|
||||
fn validation_error_may_be_storage_buffer_overindex(error: &str) -> bool {
|
||||
error.contains("reached non-composite type while indexes still remain")
|
||||
&& error.contains("_ptr_StorageBuffer_")
|
||||
}
|
||||
|
||||
/// Canonicalize the ids of an emitted SPIR-V byte stream into the deterministic serialized-order form
|
||||
/// the shipped pipeline applies in `finish_module`. Exposed for the byte-drift gates
|
||||
/// (historical validation tooling byte-baseline-check` / `byte-determinism-check`), which compare native-emit
|
||||
@@ -1300,6 +1591,111 @@ pub fn disassemble(spv: &[u8]) -> Result<String, String> {
|
||||
mod single_meta_parse_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn large_cfg_pretry_uses_the_largest_function_not_module_total() {
|
||||
let many_small = (0..400)
|
||||
.map(|index| {
|
||||
format!(
|
||||
"define void @f{index}() {{\nentry:\n br label %exit\nexit:\n ret void\n}}\n"
|
||||
)
|
||||
})
|
||||
.collect::<String>();
|
||||
assert_eq!(sanitized_max_function_basic_block_count(&many_small), 2);
|
||||
|
||||
let one_large = format!(
|
||||
"define void @large() {{\nentry:\n{} ret void\n}}\n",
|
||||
(0..350)
|
||||
.map(|index| format!("b{index}:\n br label %b{}\n", index + 1))
|
||||
.collect::<String>()
|
||||
);
|
||||
assert_eq!(sanitized_max_function_basic_block_count(&one_large), 351);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_cfg_pretry_never_reloads_a_graph_beyond_the_relooper_cap() {
|
||||
assert!(!large_cfg_relooper_eligible(
|
||||
native::LARGE_CFG_BLOCK_THRESHOLD
|
||||
));
|
||||
assert!(large_cfg_relooper_eligible(
|
||||
native::LARGE_CFG_BLOCK_THRESHOLD + 1
|
||||
));
|
||||
assert!(large_cfg_relooper_eligible(
|
||||
native::CFG_EMIT_RELOOPER_MAX_BLOCKS
|
||||
));
|
||||
assert!(!large_cfg_relooper_eligible(
|
||||
native::CFG_EMIT_RELOOPER_MAX_BLOCKS + 1
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_address_model_detects_loaded_device_pointers_not_local_pointer_staging() {
|
||||
assert!(has_device_address_pointer_load(
|
||||
"%p = load ptr addrspace(1), ptr addrspace(2) %field"
|
||||
));
|
||||
assert!(has_device_address_pointer_load(
|
||||
"%p = load ptr addrspace(1), ptr addrspace(1) %field"
|
||||
));
|
||||
assert!(has_device_address_pointer_load(
|
||||
"%p = inttoptr i64 %address to ptr addrspace(1)"
|
||||
));
|
||||
assert!(!has_device_address_pointer_load(
|
||||
"%p = load ptr addrspace(1), ptr %local"
|
||||
));
|
||||
assert!(!has_device_address_pointer_load(
|
||||
"%p = load ptr addrspace(2), ptr addrspace(2) %field"
|
||||
));
|
||||
|
||||
let ll = r#"
|
||||
define void @k(ptr addrspace(1) %out, i64 %address) {
|
||||
%p = inttoptr i64 %address to ptr addrspace(1)
|
||||
ret void
|
||||
}
|
||||
!air.kernel = !{!0}
|
||||
!0 = !{ptr @k, !1, !2}
|
||||
!1 = !{}
|
||||
!2 = !{!3, !4}
|
||||
!3 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.write", !"air.address_space", i32 1}
|
||||
!4 = !{i32 1, !"air.thread_position_in_grid"}
|
||||
"#;
|
||||
let reflection = reflect_sanitized(
|
||||
ll,
|
||||
passes::Stage::Kernel,
|
||||
passes::TransformOptions::default(),
|
||||
)
|
||||
.expect("reflect device-address kernel");
|
||||
let table = reflection
|
||||
.bindings
|
||||
.iter()
|
||||
.find(|binding| binding.kind == reflect::ResourceKind::BufferAddressTable)
|
||||
.expect("buffer-address table reflection");
|
||||
assert_eq!(
|
||||
table.descriptor.map(|descriptor| descriptor.binding),
|
||||
Some(1)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fc_buffer_promotion_only_routes_private_placeholder_chains() {
|
||||
assert!(validation_error_may_be_fc_private_placeholder(
|
||||
"OpInBoundsAccessChain reached non-composite type; %x = OpInBoundsAccessChain %_ptr_Private_uint"
|
||||
));
|
||||
assert!(!validation_error_may_be_fc_private_placeholder(
|
||||
"OpInBoundsAccessChain reached non-composite type; %x = OpInBoundsAccessChain %_ptr_StorageBuffer_uint"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_relooper_feed_only_routes_storage_buffer_overindex() {
|
||||
assert!(validation_error_may_be_storage_buffer_overindex(
|
||||
"OpInBoundsAccessChain reached non-composite type while indexes still remain: \
|
||||
%x = OpInBoundsAccessChain %_ptr_StorageBuffer_uint %root %index"
|
||||
));
|
||||
assert!(!validation_error_may_be_storage_buffer_overindex(
|
||||
"OpInBoundsAccessChain reached non-composite type while indexes still remain: \
|
||||
%x = OpInBoundsAccessChain %_ptr_Private_uint %root %index"
|
||||
));
|
||||
}
|
||||
|
||||
const SIMPLE_KERNEL: &str = r#"
|
||||
define void @k(ptr addrspace(1) %out) {
|
||||
entry:
|
||||
@@ -1318,7 +1714,7 @@ entry:
|
||||
fn production_kernel_emit_reuses_one_stage_meta_parse() {
|
||||
meta::reset_air_meta_parse_count();
|
||||
let stage_meta = parse_stage_meta(SIMPLE_KERNEL, passes::Stage::Kernel);
|
||||
tools::llc_vulkan_spirv_with_sidecar(
|
||||
tools::emit_vulkan_spirv_with_sidecar(
|
||||
SIMPLE_KERNEL,
|
||||
Path::new(""),
|
||||
stage_meta.kern.as_ref(),
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+28
-4
@@ -1,5 +1,5 @@
|
||||
//! metal2vulkan CLI — host translator used by fixtures, coverage tools, and replay/oracle experiments.
|
||||
//! Usage: metal2vulkan <in.air|.ll> <out.spv> --stage vertex|fragment|passthrough|kernel
|
||||
//! metal2vulkan CLI — AIR/LLVM-IR to validated Vulkan SPIR-V.
|
||||
//! Usage: metal2vulkan <in.air|.ll> <out.spv> [--stage auto|vertex|fragment|passthrough|kernel]
|
||||
//! Prints a line containing `PASS` on success (spirv-val vulkan1.3 clean), nonzero exit + `FALLBACK`
|
||||
//! on any failure.
|
||||
|
||||
@@ -38,13 +38,29 @@ fn main() {
|
||||
let mut stage = "auto".to_string();
|
||||
let mut emit_meta: Option<String> = None;
|
||||
let mut simd_cluster32 = false;
|
||||
let mut raster_sample_count = None;
|
||||
let mut pos: Vec<String> = vec![];
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"--help" | "-h" => {
|
||||
println!(
|
||||
"usage: metal2vulkan <in.air|.ll> <out.spv> [--stage auto|vertex|fragment|passthrough|kernel] [--emit-meta out.json] [--simd-cluster32] (default stage: auto)\n"
|
||||
r#"usage: metal2vulkan <in.air|.ll> [out.spv] [options]
|
||||
|
||||
If out.spv is omitted, the default is <input-without-extension>.vk.spv.
|
||||
|
||||
options:
|
||||
--stage auto|vertex|fragment|passthrough|kernel
|
||||
shader stage (default: auto from AIR metadata; compute aliases kernel)
|
||||
--emit-meta out.json
|
||||
write ShaderReflection JSON (requires the serde feature; not passthrough)
|
||||
--simd-cluster32
|
||||
request 32-lane clustered subgroup reductions
|
||||
--raster-samples 1|2|4|8|16|32|64
|
||||
exact graphics-pipeline sample count for AIR sample-count queries
|
||||
-h, --help
|
||||
show this help
|
||||
"#
|
||||
);
|
||||
print!("{}", metal2vulkan::env_vars::help_text());
|
||||
process::exit(0);
|
||||
@@ -64,7 +80,14 @@ fn main() {
|
||||
simd_cluster32 = true;
|
||||
i += 1;
|
||||
}
|
||||
// accept (and ignore) the legacy flags so the harness/contract is a superset.
|
||||
"--raster-samples" => {
|
||||
raster_sample_count = args.get(i + 1).and_then(|value| value.parse().ok());
|
||||
if !matches!(raster_sample_count, Some(1 | 2 | 4 | 8 | 16 | 32 | 64)) {
|
||||
fail("--raster-samples requires one of 1, 2, 4, 8, 16, 32, or 64");
|
||||
}
|
||||
i += 2;
|
||||
}
|
||||
// Accept and ignore compatibility options used by external harnesses.
|
||||
"--entry" | "--local" => {
|
||||
i += 2;
|
||||
}
|
||||
@@ -98,6 +121,7 @@ fn main() {
|
||||
|
||||
let options = TransformOptions {
|
||||
simd_cluster32,
|
||||
raster_sample_count,
|
||||
..TransformOptions::default()
|
||||
};
|
||||
let want_meta = emit_meta.is_some();
|
||||
|
||||
+156
-19
@@ -1,34 +1,61 @@
|
||||
use super::types::{struct_member_starts_at, tokenize, Tok};
|
||||
use super::{arg_type_name, role_strings, texture_shape_from_name, TextureFormat};
|
||||
use super::{arg_type_name, role_strings, texture_shape_from_name, BufferAccess, TextureFormat};
|
||||
use crate::passes::ImageComp;
|
||||
use spirv::Dim;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// A texture that lives inside an `air.indirect_buffer` argument buffer, marked
|
||||
/// `air.indirect_argument` → `air.texture` in the buffer's `air.struct_type_info`, and used by the
|
||||
/// kernel body through an AIR texture read/write intrinsic.
|
||||
/// shader body through an AIR texture intrinsic.
|
||||
///
|
||||
/// The translator materializes a synthetic UniformConstant sampled image for it and the validation
|
||||
/// harness binds the SAME deterministically-seeded texture on both the Apple-oracle side (encoded
|
||||
/// into the arg buffer via `MTLArgumentEncoder`) and the Vulkan-runner side (a plain `TextureInput`),
|
||||
/// so all layers agree on one number: the synthetic texture index `K` (see
|
||||
/// [`embedded_synthetic_texture_index`]).
|
||||
/// into the arg buffer via `MTLArgumentEncoder`) and the Vulkan-runner side (the reflected synthetic
|
||||
/// descriptor). The authored identity remains the owning buffer plus field offset; the synthetic
|
||||
/// texture index `K` is translator-owned (see [`embedded_synthetic_texture_index`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct EmbeddedTexture {
|
||||
/// Kernel parameter index of the owning `air.indirect_buffer` argument.
|
||||
pub buffer_param_index: u32,
|
||||
/// Kernel parameter index of the owning `air.indirect_buffer` argument.
|
||||
pub buffer_index: u32,
|
||||
/// Byte offset of the texture handle within the argument-buffer struct.
|
||||
pub field_offset: u32,
|
||||
/// Texture dimensionality (only 2D is currently detected/supported).
|
||||
pub field_ordinal: u32,
|
||||
/// Metal argument-encoder index (`[[id(n)]]`) of this texture inside the argument buffer.
|
||||
pub argument_index: u32,
|
||||
/// Texture dimensionality (2D, with `arrayed` carrying the 2D-array distinction).
|
||||
pub dim: Dim,
|
||||
pub arrayed: bool,
|
||||
/// Sampled/storage component type (Float for `texture2d<float, read/write>`).
|
||||
pub comp: ImageComp,
|
||||
/// Storage-image format for write/read_write textures; `None` for sampled/read textures.
|
||||
pub storage_format: Option<TextureFormat>,
|
||||
/// Fixed number of opaque texture handles in this argument-buffer field. `None` denotes one
|
||||
/// handle; embedded runtime `array_ref` fields are not yet representable by Metal's fixed
|
||||
/// argument-buffer layout metadata.
|
||||
pub array_length: Option<u32>,
|
||||
/// The synthetic texture index `K` this embedded texture binds at.
|
||||
pub synthetic_texture_index: u32,
|
||||
}
|
||||
|
||||
/// One resource-handle member of an AIR indirect argument buffer. This is the common structural
|
||||
/// coordinate used by authored embedded resources, Metal argument encoding, and static lowering.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct EmbeddedArgument {
|
||||
pub buffer_param_index: u32,
|
||||
pub buffer_index: u32,
|
||||
pub field_ordinal: u32,
|
||||
pub field_offset: u32,
|
||||
pub argument_index: u32,
|
||||
/// Nested Metal buffer location for an `air.buffer` field; absent for constants, textures, and
|
||||
/// function-table handles represented by the same structural coordinate.
|
||||
pub resource_buffer_index: Option<u32>,
|
||||
pub resource_address_space: Option<u32>,
|
||||
pub resource_declared_size: Option<u32>,
|
||||
pub resource_access: Option<BufferAccess>,
|
||||
}
|
||||
|
||||
/// The synthetic texture index `K` for embedded argument-buffer textures, derived so the translator
|
||||
/// (binding decoration) and the validation harness (model + oracle) agree WITHOUT any name key.
|
||||
///
|
||||
@@ -41,28 +68,31 @@ pub fn embedded_synthetic_texture_index(texture_locations: &[u32]) -> u32 {
|
||||
texture_locations.iter().copied().max().map_or(0, |m| m + 1)
|
||||
}
|
||||
|
||||
/// True iff the kernel body calls an AIR texture read/write intrinsic. These are stable AIR intrinsic
|
||||
/// True iff the shader body calls an AIR texture intrinsic. These are stable AIR intrinsic
|
||||
/// symbols, not shader identifiers. A declaration line is only emitted when the body actually calls it,
|
||||
/// so its presence in the `.ll` text is a sound structural signal.
|
||||
pub(super) fn body_uses_texture_read_or_write(ll: &str) -> bool {
|
||||
ll.contains("@air.read_texture") || ll.contains("@air.write_texture")
|
||||
pub(super) fn body_uses_texture_intrinsic(ll: &str) -> bool {
|
||||
ll.contains("@air.sample_")
|
||||
|| ll.contains("@air.gather_")
|
||||
|| ll.contains("@air.read_texture")
|
||||
|| ll.contains("@air.write_texture")
|
||||
|| ll.contains("@air.write_imageblock_slice_to_texture")
|
||||
}
|
||||
|
||||
/// Scan each `air.indirect_buffer`'s `air.struct_type_info` for members marked
|
||||
/// `air.indirect_argument` whose nested node is an `air.texture`. Each such texture is
|
||||
/// surfaced as an `EmbeddedTexture` with a synthetic index K, K+1, … (K from
|
||||
/// [`embedded_synthetic_texture_index`]) so the translator and harness agree on the binding without
|
||||
/// a name key. Only plain 2D float/int textures are detected (the shape the current read/write paths
|
||||
/// support).
|
||||
/// a name key. Plain 2D and 2D-array float/int textures share this structural contract.
|
||||
pub(super) fn detect_embedded_textures(
|
||||
nodes: &HashMap<u32, String>,
|
||||
indirect_buffer_struct_refs: &[(u32, u32)],
|
||||
indirect_buffer_struct_refs: &[(u32, u32, u32)],
|
||||
top_level_texture_locations: &[u32],
|
||||
) -> Vec<EmbeddedTexture> {
|
||||
let mut out = vec![];
|
||||
let mut next_k = embedded_synthetic_texture_index(top_level_texture_locations);
|
||||
for &(buffer_index, sref) in indirect_buffer_struct_refs {
|
||||
for (field_offset, tex_node_ref) in embedded_texture_members(nodes, sref) {
|
||||
for &(buffer_param_index, buffer_index, sref) in indirect_buffer_struct_refs {
|
||||
for (field_ordinal, field_offset, tex_node_ref) in embedded_argument_members(nodes, sref) {
|
||||
let Some(tex_node) = nodes.get(&tex_node_ref) else {
|
||||
continue;
|
||||
};
|
||||
@@ -79,16 +109,20 @@ pub(super) fn detect_embedded_textures(
|
||||
let name = arg_type_name(tex_node).unwrap_or_default();
|
||||
let shape = texture_shape_from_name(&name);
|
||||
let dim = shape.dimension.to_spirv_dim();
|
||||
// Only the plain 2D non-arrayed shape is supported by the read lowering today.
|
||||
if dim != Dim::Dim2D || shape.arrayed {
|
||||
if dim != Dim::Dim2D {
|
||||
continue;
|
||||
}
|
||||
out.push(EmbeddedTexture {
|
||||
buffer_param_index,
|
||||
buffer_index,
|
||||
field_offset,
|
||||
field_ordinal,
|
||||
argument_index: super::location_index(tex_node, field_ordinal),
|
||||
dim,
|
||||
arrayed: shape.arrayed,
|
||||
comp: shape.component.to_image_comp(),
|
||||
storage_format: shape.storage_format,
|
||||
array_length: shape.array_length,
|
||||
synthetic_texture_index: next_k,
|
||||
});
|
||||
next_k += 1;
|
||||
@@ -97,6 +131,41 @@ pub(super) fn detect_embedded_textures(
|
||||
out
|
||||
}
|
||||
|
||||
pub(super) fn detect_embedded_arguments(
|
||||
nodes: &HashMap<u32, String>,
|
||||
indirect_buffer_struct_refs: &[(u32, u32, u32)],
|
||||
) -> Vec<EmbeddedArgument> {
|
||||
indirect_buffer_struct_refs
|
||||
.iter()
|
||||
.flat_map(|&(buffer_param_index, buffer_index, sref)| {
|
||||
embedded_argument_members(nodes, sref)
|
||||
.into_iter()
|
||||
.filter_map(move |(field_ordinal, field_offset, node_ref)| {
|
||||
let node = nodes.get(&node_ref)?;
|
||||
let is_buffer = role_strings(node).iter().any(|role| role == "buffer");
|
||||
Some(EmbeddedArgument {
|
||||
buffer_param_index,
|
||||
buffer_index,
|
||||
field_ordinal,
|
||||
field_offset,
|
||||
argument_index: super::location_index(node, field_ordinal),
|
||||
resource_buffer_index: is_buffer
|
||||
.then(|| super::location_index(node, field_ordinal)),
|
||||
resource_address_space: is_buffer
|
||||
.then(|| super::address_space(node))
|
||||
.flatten(),
|
||||
resource_declared_size: is_buffer
|
||||
.then(|| super::i32_after_marker(node, "air.arg_type_size"))
|
||||
.flatten(),
|
||||
resource_access: is_buffer
|
||||
.then(|| super::declared_buffer_access(node))
|
||||
.flatten(),
|
||||
})
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Yield `(field_offset, nested_node_ref)` for every `air.indirect_argument` member of an
|
||||
/// `air.struct_type_info` node. Each member of a struct-type-info node is a 5-tuple
|
||||
/// `i32 offset, i32 size, i32 array_len, !"type", !"name"`, optionally PREFIXED by
|
||||
@@ -106,13 +175,14 @@ pub(super) fn detect_embedded_textures(
|
||||
/// `air.indirect_argument` suffix that belongs to THAT member, so the caller can classify the nested
|
||||
/// node. (Nested `air.struct_type_info` members are walked but never carry a top-level embedded
|
||||
/// texture, so their suffix is ignored.)
|
||||
fn embedded_texture_members(nodes: &HashMap<u32, String>, sref: u32) -> Vec<(u32, u32)> {
|
||||
fn embedded_argument_members(nodes: &HashMap<u32, String>, sref: u32) -> Vec<(u32, u32, u32)> {
|
||||
let Some(body) = nodes.get(&sref) else {
|
||||
return vec![];
|
||||
};
|
||||
let toks = tokenize(body);
|
||||
let mut out = vec![];
|
||||
let mut i = 0;
|
||||
let mut field_ordinal = 0u32;
|
||||
while i < toks.len() {
|
||||
// Optional nested-struct prefix (`!"air.struct_type_info", !N`).
|
||||
if let (Some(Tok::Str(s)), Some(Tok::Ref(_))) = (toks.get(i), toks.get(i + 1)) {
|
||||
@@ -138,11 +208,12 @@ fn embedded_texture_members(nodes: &HashMap<u32, String>, sref: u32) -> Vec<(u32
|
||||
while i < toks.len() && !struct_member_starts_at(&toks, i) {
|
||||
if let (Some(Tok::Str(s)), Some(Tok::Ref(x))) = (toks.get(i), toks.get(i + 1)) {
|
||||
if s == "air.indirect_argument" {
|
||||
out.push((offset, *x));
|
||||
out.push((field_ordinal, offset, *x));
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
field_ordinal += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -152,6 +223,19 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::meta::TextureFormat;
|
||||
|
||||
#[test]
|
||||
fn embedded_texture_use_gate_includes_sampling_and_gathering() {
|
||||
assert!(body_uses_texture_intrinsic(
|
||||
"call <4 x float> @air.sample_texture_2d(...)"
|
||||
));
|
||||
assert!(body_uses_texture_intrinsic(
|
||||
"call <4 x float> @air.gather_texture_2d(...)"
|
||||
));
|
||||
assert!(!body_uses_texture_intrinsic(
|
||||
"declare void @unrelated_texture_helper()"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embedded_texture_detection_includes_read_and_write_fields() {
|
||||
let mut nodes = HashMap::new();
|
||||
@@ -168,13 +252,66 @@ mod tests {
|
||||
r#"i32 1, !"air.texture", !"air.location_index", i32 1, i32 1, !"air.write", !"air.arg_type_name", !"texture2d<float, write>""#.to_string(),
|
||||
);
|
||||
|
||||
let textures = detect_embedded_textures(&nodes, &[(0, 10)], &[]);
|
||||
let textures = detect_embedded_textures(&nodes, &[(4, 0, 10)], &[]);
|
||||
assert_eq!(textures.len(), 2);
|
||||
assert_eq!(textures[0].buffer_param_index, 4);
|
||||
assert_eq!(textures[0].field_offset, 0);
|
||||
assert_eq!(textures[0].argument_index, 0);
|
||||
assert_eq!(textures[0].storage_format, None);
|
||||
assert!(!textures[0].arrayed);
|
||||
assert_eq!(textures[0].synthetic_texture_index, 0);
|
||||
assert_eq!(textures[1].field_offset, 8);
|
||||
assert_eq!(textures[1].argument_index, 1);
|
||||
assert_eq!(textures[1].storage_format, Some(TextureFormat::R32f));
|
||||
assert_eq!(textures[1].array_length, None);
|
||||
assert!(!textures[1].arrayed);
|
||||
assert_eq!(textures[1].synthetic_texture_index, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embedded_fixed_depth_array_preserves_handle_count_and_image_shape() {
|
||||
let mut nodes = HashMap::new();
|
||||
nodes.insert(
|
||||
10,
|
||||
r#"i32 0, i32 16, i32 0, !"array<depth2d_array<float, sample>, 2>", !"depth", !"air.indirect_argument", !20"#.to_string(),
|
||||
);
|
||||
nodes.insert(
|
||||
20,
|
||||
r#"i32 0, !"air.texture", !"air.location_index", i32 4, i32 2, !"air.sample", !"air.arg_type_name", !"array<depth2d_array<float, sample>, 2>""#.to_string(),
|
||||
);
|
||||
|
||||
let textures = detect_embedded_textures(&nodes, &[(1, 16, 10)], &[]);
|
||||
assert_eq!(textures.len(), 1);
|
||||
assert_eq!(textures[0].argument_index, 4);
|
||||
assert_eq!(textures[0].array_length, Some(2));
|
||||
assert!(textures[0].arrayed);
|
||||
assert_eq!(textures[0].storage_format, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embedded_argument_detection_classifies_only_nested_buffers_as_device_resources() {
|
||||
let mut nodes = HashMap::new();
|
||||
nodes.insert(
|
||||
10,
|
||||
r#"i32 0, i32 4, i32 0, !"uint", !"count", !"air.indirect_argument", !20, i32 8, i32 8, i32 0, !"float", !"values", !"air.indirect_argument", !21"#.to_string(),
|
||||
);
|
||||
nodes.insert(
|
||||
20,
|
||||
r#"i32 0, !"air.indirect_constant", !"air.location_index", i32 2, i32 1"#.to_string(),
|
||||
);
|
||||
nodes.insert(
|
||||
21,
|
||||
r#"i32 1, !"air.buffer", !"air.location_index", i32 7, i32 1, !"air.address_space", i32 1"#.to_string(),
|
||||
);
|
||||
|
||||
let arguments = detect_embedded_arguments(&nodes, &[(3, 5, 10)]);
|
||||
assert_eq!(arguments.len(), 2);
|
||||
assert_eq!(arguments[0].resource_buffer_index, None);
|
||||
assert_eq!(arguments[1].buffer_param_index, 3);
|
||||
assert_eq!(arguments[1].buffer_index, 5);
|
||||
assert_eq!(arguments[1].field_offset, 8);
|
||||
assert_eq!(arguments[1].argument_index, 7);
|
||||
assert_eq!(arguments[1].resource_buffer_index, Some(7));
|
||||
assert_eq!(arguments[1].resource_address_space, Some(1));
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,10 @@ pub struct FunctionConstant {
|
||||
pub name: String,
|
||||
/// The LLVM-IR type of the constant (`i32`, `i1`, `<4 x i32>`, `float`, …).
|
||||
pub type_name: String,
|
||||
/// Itanium ABI type encoding carried after `MTL_FC_INIT_<index>_` (`j`, `Dv4_j`, `Dh`, …).
|
||||
/// Unlike LLVM's signless integer type, this preserves the Metal scalar signedness and lanes
|
||||
/// needed to bind an exact `MTLFunctionConstantValues` value.
|
||||
pub abi_type_encoding: String,
|
||||
}
|
||||
|
||||
/// Scan LLVM-IR for `[[function_constant]]` initializer globals — module-scope declarations named
|
||||
@@ -35,6 +39,11 @@ pub fn parse_function_constants(ll: &str) -> Vec<FunctionConstant> {
|
||||
let Ok(index) = digits.parse::<u32>() else {
|
||||
continue;
|
||||
};
|
||||
let abi_type_encoding = marker
|
||||
.strip_prefix(&digits)
|
||||
.and_then(|suffix| suffix.strip_prefix('_'))
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
if out.iter().any(|f| f.index == index) {
|
||||
continue;
|
||||
}
|
||||
@@ -42,6 +51,7 @@ pub fn parse_function_constants(ll: &str) -> Vec<FunctionConstant> {
|
||||
index,
|
||||
name: base.to_string(),
|
||||
type_name: fc_global_decl_type(&t[eq + 3..]).unwrap_or_default(),
|
||||
abi_type_encoding,
|
||||
});
|
||||
}
|
||||
out.sort_by_key(|f| f.index);
|
||||
|
||||
@@ -103,6 +103,103 @@ pub(super) fn static_init_int_global_values(ll: &str) -> HashMap<String, u32> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Integer mirrors derived from an AIR function-constant initializer and only read afterward. This
|
||||
/// is the product-safe subset of the metadata evaluator above: ordinary constructor state is left
|
||||
/// intact, and any non-load use outside a constructor may mutate or escape the cell, so it is
|
||||
/// excluded.
|
||||
pub(crate) fn static_init_foldable_int_global_values(ll: &str) -> HashMap<String, u32> {
|
||||
let mut values = static_init_int_global_values(ll);
|
||||
let mut derived_globals = ll
|
||||
.lines()
|
||||
.filter_map(|raw| {
|
||||
let line = raw.split(';').next().unwrap_or(raw).trim();
|
||||
(line.starts_with('@') && line.contains("air.fc_initializer"))
|
||||
.then(|| line.split_once(" = ").map(|(name, _)| name.to_string()))
|
||||
.flatten()
|
||||
})
|
||||
.collect::<HashSet<_>>();
|
||||
let mut derived_locals = HashSet::<String>::new();
|
||||
let mut in_constructor = false;
|
||||
for raw in ll.lines() {
|
||||
let line = raw.split(';').next().unwrap_or(raw).trim();
|
||||
if line.starts_with("define ") {
|
||||
in_constructor = line.contains("@_GLOBAL__sub_I");
|
||||
derived_locals.clear();
|
||||
continue;
|
||||
}
|
||||
if line == "}" {
|
||||
in_constructor = false;
|
||||
continue;
|
||||
}
|
||||
if !in_constructor {
|
||||
continue;
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix("store ") {
|
||||
let mut parts = rest.splitn(2, ',');
|
||||
let value = parts.next().map(value_token);
|
||||
let target = parts.next().and_then(parse_global_name);
|
||||
if let (Some(value), Some(target)) = (value, target) {
|
||||
if derived_locals.contains(value) || derived_globals.contains(value) {
|
||||
derived_globals.insert(target);
|
||||
} else {
|
||||
derived_globals.remove(&target);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some((result, rhs)) = line.split_once(" = ") else {
|
||||
continue;
|
||||
};
|
||||
if result.starts_with('%')
|
||||
&& derived_globals
|
||||
.iter()
|
||||
.chain(&derived_locals)
|
||||
.any(|symbol| references_symbol(rhs, symbol))
|
||||
{
|
||||
derived_locals.insert(result.to_string());
|
||||
}
|
||||
}
|
||||
values.retain(|global, _| derived_globals.contains(global));
|
||||
|
||||
let mut in_static_init = false;
|
||||
let mut in_function = false;
|
||||
for raw in ll.lines() {
|
||||
let line = raw.split(';').next().unwrap_or(raw).trim();
|
||||
if line.starts_with("define ") {
|
||||
in_function = true;
|
||||
in_static_init = line.contains("@_GLOBAL__sub_I");
|
||||
continue;
|
||||
}
|
||||
if line == "}" {
|
||||
in_function = false;
|
||||
in_static_init = false;
|
||||
continue;
|
||||
}
|
||||
if !in_function || in_static_init || line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
values.retain(|global, _| {
|
||||
if !references_symbol(line, global) {
|
||||
return true;
|
||||
}
|
||||
let Some(load) = line.split_once(" = load ").map(|(_, load)| load) else {
|
||||
return false;
|
||||
};
|
||||
parse_global_name(load).as_ref() == Some(global)
|
||||
});
|
||||
}
|
||||
values
|
||||
}
|
||||
|
||||
fn references_symbol(text: &str, symbol: &str) -> bool {
|
||||
text.match_indices(symbol).any(|(start, _)| {
|
||||
let end = start + symbol.len();
|
||||
let boundary = |byte: u8| !matches!(byte, b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'_' | b'.' | b'$');
|
||||
(start == 0 || boundary(text.as_bytes()[start - 1]))
|
||||
&& (end == text.len() || boundary(text.as_bytes()[end]))
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_integer_global_initializers(ll: &str) -> HashMap<String, u32> {
|
||||
let mut globals = HashMap::new();
|
||||
for raw in ll.lines() {
|
||||
@@ -142,6 +239,9 @@ fn eval_static_rhs(
|
||||
env: &HashMap<String, StaticValue>,
|
||||
globals: &HashMap<String, u32>,
|
||||
) -> Option<StaticValue> {
|
||||
if rhs.contains("@air.is_function_constant_defined(") {
|
||||
return Some(StaticValue::Bool(false));
|
||||
}
|
||||
if rhs.starts_with("load <4 x i32>") {
|
||||
return Some(StaticValue::Vec4([0; 4]));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
//! Structural description of the stable `air.intersect.*` ABI family.
|
||||
//!
|
||||
//! AIR spells ray queries as a compositional callee suffix. Keeping that grammar here lets the
|
||||
//! translator and validation tooling agree on the exact family, result aggregate, and parameter
|
||||
//! count without either side growing a corpus-derived allowlist of complete symbol names.
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum AirIntersectionInstancing {
|
||||
None,
|
||||
SingleLevel,
|
||||
MultiLevel,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum AirIntersectionResultField {
|
||||
IntersectionType,
|
||||
Distance,
|
||||
PrimitiveId,
|
||||
GeometryId,
|
||||
OpaquePointer,
|
||||
InstanceId,
|
||||
UserInstanceId,
|
||||
InstanceLevel,
|
||||
Barycentrics,
|
||||
FrontFacing,
|
||||
WorldSpaceVector(u8),
|
||||
}
|
||||
|
||||
impl AirIntersectionResultField {
|
||||
pub fn llvm_type(self) -> &'static str {
|
||||
match self {
|
||||
Self::IntersectionType | Self::PrimitiveId | Self::GeometryId => "i32",
|
||||
Self::Distance => "float",
|
||||
Self::OpaquePointer => "ptr addrspace(1)",
|
||||
Self::InstanceId | Self::UserInstanceId => "i32",
|
||||
Self::InstanceLevel => "i8",
|
||||
Self::Barycentrics => "<2 x float>",
|
||||
Self::FrontFacing => "i1",
|
||||
Self::WorldSpaceVector(_) => "<3 x float>",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AirIntersectionFamily {
|
||||
pub intersection_function_buffer: bool,
|
||||
pub instancing: AirIntersectionInstancing,
|
||||
pub triangle_data: bool,
|
||||
pub world_space_data: bool,
|
||||
pub user_data: bool,
|
||||
pub primitive_motion: bool,
|
||||
pub instance_motion: bool,
|
||||
pub extended_limits: bool,
|
||||
}
|
||||
|
||||
impl AirIntersectionFamily {
|
||||
/// Parse a complete stable ABI symbol such as
|
||||
/// `air.intersect.intersection_function_buffer.instancing.triangle_data.user_data`.
|
||||
///
|
||||
/// `Ok(None)` means this is not an AIR intersection symbol. Unknown, duplicated, or
|
||||
/// structurally contradictory suffixes are errors rather than silently acquiring semantics.
|
||||
pub fn parse(callee: &str) -> Result<Option<Self>, String> {
|
||||
let Some(suffix) = callee.strip_prefix("air.intersect.") else {
|
||||
return Ok(None);
|
||||
};
|
||||
if suffix.is_empty() {
|
||||
return Err("AIR intersection symbol has an empty family suffix".into());
|
||||
}
|
||||
let mut family = Self {
|
||||
intersection_function_buffer: false,
|
||||
instancing: AirIntersectionInstancing::None,
|
||||
triangle_data: false,
|
||||
world_space_data: false,
|
||||
user_data: false,
|
||||
primitive_motion: false,
|
||||
instance_motion: false,
|
||||
extended_limits: false,
|
||||
};
|
||||
for token in suffix.split('.') {
|
||||
match token {
|
||||
"intersection_function_buffer" if !family.intersection_function_buffer => {
|
||||
family.intersection_function_buffer = true;
|
||||
}
|
||||
"instancing" if family.instancing == AirIntersectionInstancing::None => {
|
||||
family.instancing = AirIntersectionInstancing::SingleLevel;
|
||||
}
|
||||
"multi_level_instancing"
|
||||
if family.instancing == AirIntersectionInstancing::None =>
|
||||
{
|
||||
family.instancing = AirIntersectionInstancing::MultiLevel;
|
||||
}
|
||||
"triangle_data" if !family.triangle_data => family.triangle_data = true,
|
||||
"world_space_data" if !family.world_space_data => {
|
||||
family.world_space_data = true;
|
||||
}
|
||||
"user_data" if !family.user_data => family.user_data = true,
|
||||
"primitive_motion" if !family.primitive_motion => family.primitive_motion = true,
|
||||
"instance_motion" if !family.instance_motion => family.instance_motion = true,
|
||||
"extended_limits" if !family.extended_limits => family.extended_limits = true,
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"AIR intersection symbol {callee} has an unknown or duplicate token {token}"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
if family.user_data && !family.intersection_function_buffer {
|
||||
return Err(format!(
|
||||
"AIR intersection symbol {callee} requests user_data without an intersection function buffer"
|
||||
));
|
||||
}
|
||||
if family.instance_motion && family.instancing == AirIntersectionInstancing::None {
|
||||
return Err(format!(
|
||||
"AIR intersection symbol {callee} requests instance_motion without instancing"
|
||||
));
|
||||
}
|
||||
if family.world_space_data && family.instancing == AirIntersectionInstancing::None {
|
||||
return Err(format!(
|
||||
"AIR intersection symbol {callee} requests world_space_data without instancing"
|
||||
));
|
||||
}
|
||||
Ok(Some(family))
|
||||
}
|
||||
|
||||
pub fn result_fields(&self) -> Vec<AirIntersectionResultField> {
|
||||
use AirIntersectionResultField as Field;
|
||||
let mut fields = vec![
|
||||
Field::IntersectionType,
|
||||
Field::Distance,
|
||||
Field::PrimitiveId,
|
||||
Field::GeometryId,
|
||||
Field::OpaquePointer,
|
||||
];
|
||||
match self.instancing {
|
||||
AirIntersectionInstancing::None => {}
|
||||
AirIntersectionInstancing::SingleLevel => {
|
||||
fields.extend([Field::InstanceId, Field::UserInstanceId]);
|
||||
}
|
||||
AirIntersectionInstancing::MultiLevel => fields.push(Field::InstanceLevel),
|
||||
}
|
||||
if self.triangle_data {
|
||||
fields.extend([Field::Barycentrics, Field::FrontFacing]);
|
||||
}
|
||||
if self.world_space_data {
|
||||
fields.extend((0..8).map(Field::WorldSpaceVector));
|
||||
}
|
||||
fields
|
||||
}
|
||||
|
||||
pub fn llvm_result_type(&self) -> String {
|
||||
format!(
|
||||
"{{ {} }}",
|
||||
self.result_fields()
|
||||
.into_iter()
|
||||
.map(AirIntersectionResultField::llvm_type)
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
)
|
||||
}
|
||||
|
||||
/// AIR's base query has eighteen operands. Feature operands are compositional; result-only
|
||||
/// features (`triangle_data`, `world_space_data`, `extended_limits`) add no operand.
|
||||
pub fn argument_count(&self) -> usize {
|
||||
18 + match self.instancing {
|
||||
AirIntersectionInstancing::None => 0,
|
||||
AirIntersectionInstancing::SingleLevel => 2,
|
||||
AirIntersectionInstancing::MultiLevel => 5,
|
||||
} + usize::from(self.intersection_function_buffer) * 4
|
||||
// Primitive and instance motion share the query's single motion-time operand.
|
||||
+ usize::from(self.primitive_motion || self.instance_motion)
|
||||
+ usize::from(self.user_data)
|
||||
}
|
||||
|
||||
/// Operand containing the intersection-function table. AIR places an instance mask before it
|
||||
/// for either instancing mode and one shared motion time before it for either motion feature.
|
||||
pub fn intersection_table_argument_index(&self) -> usize {
|
||||
5 + usize::from(self.instancing != AirIntersectionInstancing::None)
|
||||
+ usize::from(self.primitive_motion || self.instance_motion)
|
||||
}
|
||||
|
||||
/// Operand ordinals omitted when an authored all-opaque table query is projected to AIR's
|
||||
/// callback-free ABI.
|
||||
///
|
||||
/// The two ABIs share the table-shaped opaque operand and the following payload pointer/stride.
|
||||
/// The callback form inserts table size + function stride immediately after the table, inserts
|
||||
/// one additional user-data buffer when `user_data` is present, and appends two callback dispatch
|
||||
/// controls. The removal is therefore deliberately non-contiguous.
|
||||
pub fn opaque_triangle_removed_argument_indices(&self) -> Option<Vec<usize>> {
|
||||
self.intersection_function_buffer.then(|| {
|
||||
let table = self.intersection_table_argument_index();
|
||||
let mut removed = vec![table + 1, table + 2];
|
||||
if self.user_data {
|
||||
removed.push(table + 3);
|
||||
}
|
||||
removed.extend([self.argument_count() - 2, self.argument_count() - 1]);
|
||||
removed
|
||||
})
|
||||
}
|
||||
|
||||
pub fn result_field(&self, index: usize) -> Option<AirIntersectionResultField> {
|
||||
self.result_fields().get(index).copied()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_composed_multi_level_callback_family() {
|
||||
let family = AirIntersectionFamily::parse(
|
||||
"air.intersect.intersection_function_buffer.multi_level_instancing.triangle_data.world_space_data.user_data.primitive_motion.instance_motion",
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(family.instancing, AirIntersectionInstancing::MultiLevel);
|
||||
assert_eq!(family.argument_count(), 29);
|
||||
assert_eq!(family.intersection_table_argument_index(), 7);
|
||||
assert_eq!(
|
||||
family.opaque_triangle_removed_argument_indices(),
|
||||
Some(vec![8, 9, 10, 27, 28])
|
||||
);
|
||||
assert_eq!(family.result_fields().len(), 16);
|
||||
assert_eq!(
|
||||
family.llvm_result_type(),
|
||||
"{ i32, float, i32, i32, ptr addrspace(1), i8, <2 x float>, i1, <3 x float>, <3 x float>, <3 x float>, <3 x float>, <3 x float>, <3 x float>, <3 x float>, <3 x float> }"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_single_level_base_and_extended_limits_without_shape_changes() {
|
||||
let base = AirIntersectionFamily::parse("air.intersect.instancing")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let extended = AirIntersectionFamily::parse("air.intersect.instancing.extended_limits")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(base.argument_count(), 20);
|
||||
assert_eq!(base.intersection_table_argument_index(), 6);
|
||||
assert_eq!(base.result_fields(), extended.result_fields());
|
||||
assert_eq!(extended.argument_count(), 20);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_contradictory_or_unknown_families() {
|
||||
assert!(AirIntersectionFamily::parse("air.intersect.user_data").is_err());
|
||||
assert!(AirIntersectionFamily::parse("air.intersect.world_space_data").is_err());
|
||||
assert!(AirIntersectionFamily::parse("air.intersect.triangle_data.mystery").is_err());
|
||||
assert_eq!(AirIntersectionFamily::parse("air.foo").unwrap(), None);
|
||||
}
|
||||
}
|
||||
+823
-124
File diff suppressed because it is too large.
Load diff
+229
-1
@@ -198,6 +198,9 @@ fn fragment_depth_output_is_not_a_render_target() {
|
||||
assert_eq!(m.n_render_targets, 0);
|
||||
assert!(m.render_target_members.is_empty());
|
||||
assert_eq!(m.depth_members, vec![0]);
|
||||
assert_eq!(m.depth_qualifier, Some(DepthQualifier::Any));
|
||||
let reflection = crate::reflect::ShaderReflection::from_fragment(&m, Some("F"));
|
||||
assert_eq!(reflection.depth_qualifier, Some(DepthQualifier::Any));
|
||||
assert!(m.is_depth_member(0));
|
||||
assert!(!m.is_depth_member(1));
|
||||
}
|
||||
@@ -247,6 +250,46 @@ fn vertex_builtin_roles() {
|
||||
assert_eq!(m.output_role_of(2), Some(&VertOutRole::ClipDistance));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vertex_patch_contract_preserves_domain_control_points_and_system_locations() {
|
||||
let ll = r#"
|
||||
!air.vertex = !{!0}
|
||||
!0 = !{ptr @vmain, !1, !2, !10}
|
||||
!1 = !{!3}
|
||||
!2 = !{!4, !7, !8, !9}
|
||||
!3 = !{!"air.position", !"air.arg_type_name", !"float4"}
|
||||
!4 = !{i32 0, !"air.patch_control_point_input", !5, !6}
|
||||
!5 = !{!"air.patch_control_point_function", ptr @control.MTL_CONTROL_POINT_FN}
|
||||
!6 = !{!"air.location_index", i32 2, i32 1, !"air.arg_type_name", !"float3"}
|
||||
!7 = !{i32 1, !"air.function_constant", !11, !"air.patch_input", !"air.location_index", i32 5, i32 1, !"air.arg_type_name", !"float4"}
|
||||
!8 = !{i32 2, !"air.instance_id", !"air.arg_type_name", !"uint"}
|
||||
!9 = !{i32 3, !"air.amplification_count", !"air.arg_type_name", !"ushort"}
|
||||
!10 = !{!"air.patch", !"quad", !"air.patch_control_point", i32 16}
|
||||
!11 = !{ptr addrspace(2) @fc, !"bool", !"enabled"}
|
||||
"#;
|
||||
let meta = parse_air_vertex_meta(ll).unwrap();
|
||||
let tessellation = meta.tessellation.as_ref().unwrap();
|
||||
assert_eq!(tessellation.domain, PatchDomain::Quad);
|
||||
assert_eq!(tessellation.control_point_count, 16);
|
||||
assert_eq!(
|
||||
tessellation.control_point_function.as_deref(),
|
||||
Some("control.MTL_CONTROL_POINT_FN")
|
||||
);
|
||||
assert_eq!(tessellation.control_point_fields[0].location, 2);
|
||||
assert_eq!(meta.role_of(0), Some(&VertRole::PatchControlPoints));
|
||||
assert_eq!(meta.role_of(1), Some(&VertRole::PatchInput(5)));
|
||||
assert_eq!(meta.role_of(2), Some(&VertRole::InstanceId));
|
||||
assert_eq!(meta.role_of(3), Some(&VertRole::AmplificationCount));
|
||||
assert_eq!(
|
||||
meta.tessellation_system_input_location(&VertRole::InstanceId),
|
||||
Some(6)
|
||||
);
|
||||
assert_eq!(
|
||||
meta.tessellation_system_input_location(&VertRole::AmplificationCount),
|
||||
Some(8)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vertex_render_target_array_index_role() {
|
||||
let ll = r#"
|
||||
@@ -255,7 +298,7 @@ fn vertex_render_target_array_index_role() {
|
||||
!1 = !{!2, !3, !4}
|
||||
!2 = !{!"air.position", !"air.arg_type_name", !"float4"}
|
||||
!3 = !{!"air.render_target_array_index", !"air.arg_type_name", !"uint", !"air.arg_name", !"layer"}
|
||||
!4 = !{!"air.vertex_output", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"float", !"air.arg_name", !"varying"}
|
||||
!4 = !{!"air.vertex_output", !"generated(7varyingf)", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"float", !"air.arg_name", !"varying"}
|
||||
!5 = !{}
|
||||
"#;
|
||||
let m = parse_air_vertex_meta(ll).unwrap();
|
||||
@@ -265,6 +308,12 @@ fn vertex_render_target_array_index_role() {
|
||||
Some(&VertOutRole::RenderTargetArrayIndex)
|
||||
);
|
||||
assert_eq!(m.output_role_of(2), Some(&VertOutRole::Varying(0)));
|
||||
assert_eq!(m.output_varying_type(0), Some("float"));
|
||||
assert_eq!(m.output_varying_name(0), Some("varying"));
|
||||
assert_eq!(
|
||||
m.output_varying_user_semantic(0),
|
||||
Some("generated(7varyingf)")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -335,6 +384,25 @@ fn kernel_roles() {
|
||||
assert_eq!(m.role_of(13), Some(&KernRole::SimdgroupsPerThreadgroup));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_table_roles_preserve_metal_buffer_indices() {
|
||||
let ll = r#"
|
||||
define void @k(ptr addrspace(1) %visible, ptr addrspace(1) %intersection) { ret void }
|
||||
!air.kernel = !{!0}
|
||||
!0 = !{ptr @k, !1, !2}
|
||||
!1 = !{}
|
||||
!2 = !{!3, !4}
|
||||
!3 = !{i32 0, !"air.visible_function_table", !"air.location_index", i32 7}
|
||||
!4 = !{i32 1, !"air.intersection_function_table", !"air.location_index", i32 9}
|
||||
"#;
|
||||
let meta = parse_air_kernel_meta(ll).unwrap();
|
||||
assert_eq!(meta.role_of(0), Some(&KernRole::VisibleFunctionTable(7)));
|
||||
assert_eq!(
|
||||
meta.role_of(1),
|
||||
Some(&KernRole::IntersectionFunctionTable(9))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kernel_texture_sampler_roles() {
|
||||
let ll = r#"
|
||||
@@ -381,6 +449,13 @@ fn kernel_indirect_buffer_is_a_buffer_role() {
|
||||
assert_eq!(m.buffer_address_space(1), Some(2));
|
||||
assert_eq!(m.buffer_type_size(1), Some(8));
|
||||
assert!(matches!(m.layout_of(1), Some(AirType::Struct(fields)) if fields.len() == 2));
|
||||
assert_eq!(m.embedded_arguments.len(), 2);
|
||||
assert_eq!(m.embedded_arguments[0].buffer_param_index, 1);
|
||||
assert_eq!(m.embedded_arguments[0].buffer_index, 3);
|
||||
assert_eq!(m.embedded_arguments[0].field_ordinal, 0);
|
||||
assert_eq!(m.embedded_arguments[0].field_offset, 0);
|
||||
assert_eq!(m.embedded_arguments[1].field_ordinal, 1);
|
||||
assert_eq!(m.embedded_arguments[1].field_offset, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -408,6 +483,29 @@ declare i32 @air.get_instance_count_instance_acceleration_structure(ptr addrspac
|
||||
assert_eq!(m.role_of(1), Some(&KernRole::Buffer(0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kernel_primitive_acceleration_structure_is_always_a_literal_geometry_resource() {
|
||||
let ll = r#"
|
||||
define void @k(ptr addrspace(1) %as, ptr addrspace(1) %out) {
|
||||
store i32 7, ptr addrspace(1) %out
|
||||
ret void
|
||||
}
|
||||
|
||||
!air.kernel = !{!0}
|
||||
!0 = !{ptr @k, !1, !2}
|
||||
!1 = !{}
|
||||
!2 = !{!3, !4}
|
||||
!3 = !{i32 0, !"air.primitive_acceleration_structure", !"air.location_index", i32 5, i32 1, !"air.read", !"air.arg_type_name", !"acceleration_structure<>", !"air.arg_name", !"as"}
|
||||
!4 = !{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.write", !"air.address_space", i32 1, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"}
|
||||
"#;
|
||||
let meta = parse_air_kernel_meta(ll).unwrap();
|
||||
assert_eq!(
|
||||
meta.role_of(0),
|
||||
Some(&KernRole::PrimitiveAccelerationStructure(5))
|
||||
);
|
||||
assert_eq!(meta.role_of(1), Some(&KernRole::Buffer(0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kernel_imageblock_layout_is_not_a_buffer_layout() {
|
||||
let ll = r#"
|
||||
@@ -466,6 +564,73 @@ fn kernel_function_constant_imageblock_keeps_its_cell_layout() {
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kernel_implicit_imageblock_inventory_preserves_attachment_rate_index_and_access() {
|
||||
let ll = r#"
|
||||
define void @k() {
|
||||
%a = call <4 x half> @air.load.implicit_imageblock.v4f16(i32 2, <2 x i16> zeroinitializer, i32 3, i16 1)
|
||||
call void @air.store.implicit_imageblock.v4f16(<4 x half> %a, i32 2, <2 x i16> zeroinitializer, i32 5, i16 1)
|
||||
%b = call <2 x half> @air.load.implicit_imageblock.v2f16(i32 3, <2 x i16> zeroinitializer, i32 0, i16 0)
|
||||
call void @air.store.implicit_imageblock.i32(i32 7, i32 4, <2 x i16> zeroinitializer, i32 0, i16 0)
|
||||
ret void
|
||||
}
|
||||
|
||||
declare <4 x half> @air.load.implicit_imageblock.v4f16(i32, <2 x i16>, i32, i16)
|
||||
declare void @air.store.implicit_imageblock.v4f16(<4 x half>, i32, <2 x i16>, i32, i16)
|
||||
declare <2 x half> @air.load.implicit_imageblock.v2f16(i32, <2 x i16>, i32, i16)
|
||||
declare void @air.store.implicit_imageblock.i32(i32, i32, <2 x i16>, i32, i16)
|
||||
!air.kernel = !{!0}
|
||||
!0 = !{ptr @k, !1, !1}
|
||||
!1 = !{}
|
||||
"#;
|
||||
let meta = parse_air_kernel_meta(ll).unwrap();
|
||||
assert_eq!(
|
||||
meta.implicit_imageblock_attachments,
|
||||
[
|
||||
ImplicitImageblockAttachment {
|
||||
attachment: 2,
|
||||
data_rate: 1,
|
||||
max_index: Some(5),
|
||||
format: TextureFormat::Rgba16f,
|
||||
reads: true,
|
||||
writes: true,
|
||||
},
|
||||
ImplicitImageblockAttachment {
|
||||
attachment: 3,
|
||||
data_rate: 0,
|
||||
max_index: Some(0),
|
||||
format: TextureFormat::Rg16f,
|
||||
reads: true,
|
||||
writes: false,
|
||||
},
|
||||
ImplicitImageblockAttachment {
|
||||
attachment: 4,
|
||||
data_rate: 0,
|
||||
max_index: Some(0),
|
||||
format: TextureFormat::R32ui,
|
||||
reads: false,
|
||||
writes: true,
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_implicit_imageblock_suffix_cannot_disappear_from_reflection() {
|
||||
let ll = r#"
|
||||
define void @k() {
|
||||
%value = call <3 x half> @air.load.implicit_imageblock.v3f16(i32 0, <2 x i16> zeroinitializer, i32 0, i16 0)
|
||||
ret void
|
||||
}
|
||||
declare <3 x half> @air.load.implicit_imageblock.v3f16(i32, <2 x i16>, i32, i16)
|
||||
!air.kernel = !{!0}
|
||||
!0 = !{ptr @k, !1, !1}
|
||||
!1 = !{}
|
||||
"#;
|
||||
assert!(parse_air_kernel_meta(ll).is_none());
|
||||
assert!(implicit_imageblock_texture_format("air.load.implicit_imageblock.v3f16").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kernel_threadgroup_buffer_records_address_space() {
|
||||
let ll = r#"
|
||||
@@ -711,6 +876,7 @@ entry:
|
||||
%1 = load <4 x i32>, ptr addrspace(2) @_ZN2RB6Shader8Constant13_shader_stateE.MTL_FC_INIT_0_Dv4_j
|
||||
ret void
|
||||
}
|
||||
|
||||
";
|
||||
let fcs = parse_function_constants(ll);
|
||||
assert_eq!(fcs.len(), 2, "two distinct FC indices");
|
||||
@@ -718,9 +884,71 @@ entry:
|
||||
assert_eq!(fcs[0].index, 0);
|
||||
assert_eq!(fcs[0].name, "_ZN2RB6Shader8Constant13_shader_stateE");
|
||||
assert_eq!(fcs[0].type_name, "<4 x i32>");
|
||||
assert_eq!(fcs[0].abi_type_encoding, "Dv4_j");
|
||||
assert_eq!(fcs[1].index, 3);
|
||||
assert_eq!(fcs[1].type_name, "i32");
|
||||
assert_eq!(fcs[1].abi_type_encoding, "i");
|
||||
// The `load` use of the same global must NOT create a duplicate; the plain implicit global is
|
||||
// ignored (no MTL_FC_INIT marker).
|
||||
assert!(parse_function_constants("@x = global i32 0").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fragment_imageblock_projects_members_by_semantic() {
|
||||
let ll = r#"
|
||||
define { <4 x half>, { half } } @f({ half } %tile) { ret { <4 x half>, { half } } poison }
|
||||
!air.fragment = !{!0}
|
||||
!0 = !{ptr @f, !1, !2}
|
||||
!1 = !{!3, !4}
|
||||
!2 = !{!5}
|
||||
!3 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"half4"}
|
||||
!4 = !{!"air.imageblock_data", !"air.imageblock_data_size", i32 8, !"air.struct_type_info", !6, !"air.imageblock_master", !7}
|
||||
!5 = !{i32 0, !"air.imageblock_data", !"air.imageblock_data_size", i32 8, !"air.struct_type_info", !6, !"air.imageblock_master", !7}
|
||||
!6 = !{i32 0, i32 2, i32 0, !"half", !"user(depth)"}
|
||||
!7 = !{i32 0, i32 2, i32 0, !"half", !"user(other)", !"air.raster_order_group", i32 1, i32 2, i32 2, i32 0, !"half", !"user(depth)", !"air.raster_order_group", i32 3}
|
||||
"#;
|
||||
let meta = parse_air_fragment_meta(ll).expect("fragment metadata");
|
||||
assert_eq!(meta.role_of(0), Some(&FragRole::ImageblockData));
|
||||
let reflection = crate::reflect::ShaderReflection::from_fragment(&meta, Some("f"));
|
||||
let reflected = reflection
|
||||
.fragment_imageblock
|
||||
.expect("reflected imageblock master");
|
||||
assert_eq!(reflected.members[0].binding, None);
|
||||
assert_eq!(reflected.members[1].binding, Some(161));
|
||||
assert_eq!(
|
||||
reflected.members[1].access,
|
||||
crate::reflect::ResourceAccess::ReadWrite
|
||||
);
|
||||
let imageblock = meta.fragment_imageblock.expect("imageblock master");
|
||||
assert_eq!(imageblock.sample_size, 8);
|
||||
assert_eq!(imageblock.members[1].offset, 2);
|
||||
assert_eq!(imageblock.members[1].raster_order_group, 3);
|
||||
assert_eq!(imageblock.inputs[0].members[0].master_member, 1);
|
||||
assert_eq!(imageblock.outputs[0].interface_index, 1);
|
||||
assert_eq!(imageblock.outputs[0].members[0].master_member, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_fragment_imageblock_data_layout_is_its_own_master() {
|
||||
let ll = r#"
|
||||
define { { <4 x half>, i16 } } @f({ <4 x half>, i16 } %tile) { ret { { <4 x half>, i16 } } poison }
|
||||
!air.fragment = !{!0}
|
||||
!0 = !{ptr @f, !1, !2}
|
||||
!1 = !{!3}
|
||||
!2 = !{!4}
|
||||
!3 = !{!"air.imageblock_data", !"air.imageblock_data_size", i32 16, !"air.struct_type_info", !5}
|
||||
!4 = !{i32 0, !"air.imageblock_data", !"air.imageblock_data_size", i32 16, !"air.struct_type_info", !5}
|
||||
!5 = !{i32 0, i32 8, i32 0, !"half4", !"color", !"air.raster_order_group", i32 0, i32 8, i32 2, i32 0, !"ushort", !"depth", !"air.raster_order_group", i32 1}
|
||||
"#;
|
||||
let imageblock = parse_air_fragment_meta(ll)
|
||||
.expect("fragment metadata")
|
||||
.fragment_imageblock
|
||||
.expect("direct imageblock master");
|
||||
assert_eq!(imageblock.sample_size, 16);
|
||||
assert_eq!(imageblock.members.len(), 2);
|
||||
assert_eq!(imageblock.members[0].type_name, "half4");
|
||||
assert_eq!(imageblock.members[1].semantic, "depth");
|
||||
assert_eq!(imageblock.members[1].raster_order_group, 1);
|
||||
assert_eq!(imageblock.inputs[0].members[1].master_member, 1);
|
||||
assert_eq!(imageblock.outputs[0].members[0].master_member, 0);
|
||||
}
|
||||
+37
-5
@@ -1,9 +1,13 @@
|
||||
use crate::passes::ImageComp;
|
||||
use spirv::{Dim, ImageFormat};
|
||||
|
||||
/// Descriptor capacity used for AIR texture-handle arrays. Fixed arrays occupy their prefix;
|
||||
/// runtime `array_ref` cases author the logical prefix they may access.
|
||||
pub const TEXTURE_HANDLE_ARRAY_DESCRIPTOR_COUNT: u32 = 128;
|
||||
|
||||
/// Texture dimensionality decoded from a Metal texture type name, independent of the SPIR-V emit
|
||||
/// enum (`spirv::Dim`) so it can appear in the serializable reflection ABI.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum TextureDimension {
|
||||
D1,
|
||||
@@ -71,10 +75,13 @@ impl TextureComponent {
|
||||
/// The SPIR-V `OpTypeImage` format a write-capable Metal texture lowers to, decoded from its type
|
||||
/// name's scalar. Neutral of the emit enum (`spirv::ImageFormat`) so it can appear in the reflection
|
||||
/// ABI; the emitter maps it back via [`TextureFormat::to_spirv_format`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum TextureFormat {
|
||||
R16f,
|
||||
Rg16f,
|
||||
R32f,
|
||||
R32ui,
|
||||
Rgba32f,
|
||||
Rgba16f,
|
||||
Rgba8ui,
|
||||
@@ -86,7 +93,10 @@ impl TextureFormat {
|
||||
/// The SPIR-V `ImageFormat` the emitter decorates the storage image with.
|
||||
pub fn to_spirv_format(self) -> ImageFormat {
|
||||
match self {
|
||||
TextureFormat::R16f => ImageFormat::R16f,
|
||||
TextureFormat::Rg16f => ImageFormat::Rg16f,
|
||||
TextureFormat::R32f => ImageFormat::R32f,
|
||||
TextureFormat::R32ui => ImageFormat::R32ui,
|
||||
TextureFormat::Rgba32f => ImageFormat::Rgba32f,
|
||||
TextureFormat::Rgba16f => ImageFormat::Rgba16f,
|
||||
TextureFormat::Rgba8ui => ImageFormat::Rgba8ui,
|
||||
@@ -112,6 +122,9 @@ pub struct TextureShape {
|
||||
pub writable: bool,
|
||||
/// The argument is a runtime-indexed descriptor array of texture handles.
|
||||
pub array_ref: bool,
|
||||
/// Fixed texture-handle array length (`array<texture..., N>`), or `None` for a runtime
|
||||
/// `array_ref` and for a single texture.
|
||||
pub array_length: Option<u32>,
|
||||
/// For a `writable` texture, the storage-image texel format the emitter decorates the
|
||||
/// `OpTypeImage` with; `None` for a sampled texture.
|
||||
pub storage_format: Option<TextureFormat>,
|
||||
@@ -119,12 +132,14 @@ pub struct TextureShape {
|
||||
|
||||
/// Decode a Metal texture argument/type name into its [`TextureShape`]. The dimensionality/arrayed
|
||||
/// classification is substring-order-sensitive (`1d_array` before `1d`, `cube_array` before `cube`)
|
||||
/// and matches exactly what the interface pass decorates the emitted image type with; `multisampled`
|
||||
/// is an additive flag the emit path ignores.
|
||||
/// and matches what the interface pass uses to construct the emitted image type, including its
|
||||
/// multisample operand.
|
||||
pub fn texture_shape_from_name(name: &str) -> TextureShape {
|
||||
let (writable, array_ref) = texture_access_from_name(name);
|
||||
let array_length = fixed_texture_array_length(name);
|
||||
let shape_name = if array_ref {
|
||||
name.find("texture")
|
||||
.or_else(|| name.find("depth"))
|
||||
.and_then(|start| name.get(start..))
|
||||
.unwrap_or(name)
|
||||
} else {
|
||||
@@ -165,10 +180,24 @@ pub fn texture_shape_from_name(name: &str) -> TextureShape {
|
||||
component,
|
||||
writable,
|
||||
array_ref,
|
||||
array_length,
|
||||
storage_format,
|
||||
}
|
||||
}
|
||||
|
||||
fn fixed_texture_array_length(name: &str) -> Option<u32> {
|
||||
let compact = name
|
||||
.chars()
|
||||
.filter(|ch| !ch.is_whitespace())
|
||||
.collect::<String>();
|
||||
if !compact.starts_with("array<texture") && !compact.starts_with("array<depth") {
|
||||
return None;
|
||||
}
|
||||
let end = compact.rfind('>')?;
|
||||
let before_end = &compact[..end];
|
||||
before_end.rsplit_once(',')?.1.parse().ok()
|
||||
}
|
||||
|
||||
/// The storage-image texel format a write-capable texture lowers to, from its scalar precision. A
|
||||
/// `half`/`ushort` scalar narrows the format; the default is the full-width form.
|
||||
fn storage_format_from_name(name: &str, component: TextureComponent) -> TextureFormat {
|
||||
@@ -217,7 +246,10 @@ fn texture_access_from_name(name: &str) -> (bool, bool) {
|
||||
.chars()
|
||||
.filter(|ch| !ch.is_ascii_whitespace())
|
||||
.collect::<String>();
|
||||
let array_ref = compact.contains("array_ref<texture") || compact.contains("array<texture");
|
||||
let array_ref = compact.contains("array_ref<texture")
|
||||
|| compact.contains("array<texture")
|
||||
|| compact.contains("array_ref<depth")
|
||||
|| compact.contains("array<depth");
|
||||
let Some((_, rest)) = name.split_once('<') else {
|
||||
return (false, array_ref);
|
||||
};
|
||||
|
||||
+3
-3
@@ -1,9 +1,9 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// A reconstructed AIR aggregate type, built from a buffer's `air.struct_type_info` metadata. Used to
|
||||
/// rebuild the ORIGINAL struct for a buffer the llc Vulkan backend collapsed into a bare element
|
||||
/// A reconstructed AIR aggregate type built from a buffer's `air.struct_type_info` metadata. It
|
||||
/// restores the source layout when an emitted buffer parameter is represented as a bare element
|
||||
/// pointer (homogeneous/nested aggregates → `T*` with physical/multi-level access chains). The
|
||||
/// collapsed access-chain indices are valid struct-navigation indices for this reconstructed type.
|
||||
/// access-chain indices are valid struct-navigation indices for this reconstructed type.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum AirType {
|
||||
|
||||
@@ -34,9 +34,9 @@ struct AsyncCopyCall {
|
||||
result: String,
|
||||
}
|
||||
|
||||
/// Rewrite every `air.simdgroup_async_copy_2d` / `air.is_null_simdgroup_event` /
|
||||
/// `air.wait_simdgroup_events` in `san_ll`. Returns the text unchanged when the module does not call
|
||||
/// the async-copy intrinsic (the common case).
|
||||
/// Rewrite every `air.simdgroup_async_copy_2d` / `air.get_null_simdgroup_event` /
|
||||
/// `air.is_null_simdgroup_event` / `air.wait_simdgroup_events` in `san_ll`. Returns the text unchanged
|
||||
/// when the module does not call the async-copy intrinsic (the common case).
|
||||
pub(crate) fn lower_simdgroup_async_copy(san_ll: &str) -> String {
|
||||
if !san_ll.contains("air.simdgroup_async_copy_2d") {
|
||||
return san_ll.to_string();
|
||||
@@ -71,6 +71,15 @@ pub(crate) fn lower_simdgroup_async_copy(san_ll: &str) -> String {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if trimmed.contains("air.get_null_simdgroup_event") && trimmed.contains("call") {
|
||||
// AIR's explicit null-event constructor is the null pointer value. Keep the pointer
|
||||
// carrier because event structs store it, while eliminating the now-unsupported call.
|
||||
if let Some(res) = call_result_id(trimmed) {
|
||||
let indent = &line[..line.len() - trimmed.len()];
|
||||
out.push(format!("{indent}{res} = inttoptr i64 0 to ptr"));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if trimmed.contains("air.wait_simdgroup_events") && trimmed.contains("call") {
|
||||
// The copy is already complete in every thread; publish the threadgroup tile with a barrier.
|
||||
let indent = &line[..line.len() - trimmed.len()];
|
||||
@@ -275,3 +284,23 @@ fn call_result_id(line: &str) -> Option<String> {
|
||||
fn fresh_counter(_san_ll: &str) -> u64 {
|
||||
0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::lower_simdgroup_async_copy;
|
||||
|
||||
#[test]
|
||||
fn explicit_null_event_lowers_with_the_async_copy_family() {
|
||||
let ll = concat!(
|
||||
"%null = call ptr @air.get_null_simdgroup_event()\n",
|
||||
"%event = call ptr @air.simdgroup_async_copy_2d.p3i8.p1i8(i64 2, i64 2, ptr addrspace(3) %dst, i64 8, i64 1, <2 x i64> <i64 4, i64 4>, ptr addrspace(1) %src, i64 8, i64 1, <2 x i64> <i64 4, i64 4>, <2 x i64> zeroinitializer, i32 0)\n",
|
||||
"%is_null = call i1 @air.is_null_simdgroup_event(ptr %event)\n",
|
||||
"call void @air.wait_simdgroup_events(i32 1, ptr %event)\n",
|
||||
);
|
||||
let lowered = lower_simdgroup_async_copy(ll);
|
||||
assert!(lowered.contains("%null = inttoptr i64 0 to ptr"));
|
||||
assert!(lowered.contains("%event = inttoptr i64 1 to ptr"));
|
||||
assert!(lowered.contains("%is_null = icmp ne i64 0, 0"));
|
||||
assert!(!lowered.contains("call ptr @air.get_null_simdgroup_event"));
|
||||
}
|
||||
}
|
||||
+916
-139
File diff suppressed because it is too large.
Load diff
@@ -270,6 +270,7 @@ pub(in crate::native) fn privatize_trivial(
|
||||
for b in out.iter_mut() {
|
||||
if redirect.contains(&b.name) {
|
||||
if let Some(t) = &mut b.typed {
|
||||
let t = std::sync::Arc::make_mut(t);
|
||||
t.redirect_successor(arm, &arm_clone);
|
||||
}
|
||||
}
|
||||
@@ -283,6 +284,7 @@ pub(in crate::native) fn privatize_trivial(
|
||||
for b in out.iter_mut() {
|
||||
if b.name == arm {
|
||||
if let Some(t) = &mut b.typed {
|
||||
let t = std::sync::Arc::make_mut(t);
|
||||
t.rebuild_phi_incomings(|p| !redirect.contains(p));
|
||||
}
|
||||
}
|
||||
@@ -295,6 +297,7 @@ pub(in crate::native) fn privatize_trivial(
|
||||
for b in out.iter_mut() {
|
||||
if b.name == s {
|
||||
if let Some(t) = &mut b.typed {
|
||||
let t = std::sync::Arc::make_mut(t);
|
||||
t.duplicate_phi_incoming(arm, &arm_clone, &rename);
|
||||
}
|
||||
}
|
||||
@@ -308,10 +311,10 @@ pub(in crate::native) fn privatize_trivial(
|
||||
// lists every pred. No module named-types needed — the source resolved them.
|
||||
let role = role_for_name(&arm_clone);
|
||||
let typed = arm_block.typed.as_ref().map(|src| {
|
||||
let mut c = src.clone();
|
||||
let mut c = (**src).clone();
|
||||
c.rebuild_phi_incomings(|p| redirect.contains(p));
|
||||
c.rename(&rename);
|
||||
c
|
||||
c.into()
|
||||
});
|
||||
out.push(BodyBlock {
|
||||
name: arm_clone,
|
||||
|
||||
@@ -37,7 +37,7 @@ pub(in crate::native) fn find_deep_shared_continuations(
|
||||
&& selection.contains_key(&b.name)
|
||||
})
|
||||
.collect();
|
||||
headers.sort_by_key(|b| std::cmp::Reverse(depth(&b.name)));
|
||||
headers.sort_by_cached_key(|b| std::cmp::Reverse(depth(&b.name)));
|
||||
|
||||
let mut found = Vec::new();
|
||||
let mut seen: HashSet<(String, String)> = HashSet::new();
|
||||
@@ -109,7 +109,7 @@ pub(in crate::native) fn find_switch_case_shared_continuations(
|
||||
&& selection.contains_key(&b.name)
|
||||
})
|
||||
.collect();
|
||||
switches.sort_by_key(|b| std::cmp::Reverse(depth(&b.name)));
|
||||
switches.sort_by_cached_key(|b| std::cmp::Reverse(depth(&b.name)));
|
||||
|
||||
let mut found = Vec::new();
|
||||
let mut seen: HashSet<(String, String)> = HashSet::new();
|
||||
|
||||
@@ -92,7 +92,7 @@ mod tests {
|
||||
BodyBlock {
|
||||
name,
|
||||
role: crate::native::cfg::BlockRole::Normal,
|
||||
typed,
|
||||
typed: typed.map(Into::into),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,7 +141,11 @@ mod tests {
|
||||
find_cross_arm(&blocks),
|
||||
Some(("%checkb".to_string(), "%taken".to_string()))
|
||||
);
|
||||
let out = clone_cross_arm_shared(&blocks).expect("should apply a clone");
|
||||
// The complete planner now admits the fully-terminal source directly, so exercise the
|
||||
// cross-arm primitive itself rather than its reject-only retry driver.
|
||||
let mut counter = 0;
|
||||
let out = privatize_region(&blocks, "%checkb", "%taken", &mut counter)
|
||||
.expect("should apply a clone");
|
||||
// A clone of %taken exists; %checkb now branches to it; original %taken keeps the %entry edge.
|
||||
let clone = out
|
||||
.iter()
|
||||
@@ -469,9 +473,8 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Return unification: a divergent void selection (`if(c) ret; else ret`) has no natural merge
|
||||
/// until both rets are routed through one exit. The ordinary ladder still rejects it, while the
|
||||
/// explicitly unified graph is directly structurable.
|
||||
/// Return unification remains a valid normalization for a divergent void selection even though
|
||||
/// the planner can now represent two terminal arms with a disconnected unreachable merge.
|
||||
#[test]
|
||||
fn unify_returns_void_makes_divergent_selection_structurable() {
|
||||
let blocks = vec![
|
||||
@@ -479,10 +482,7 @@ mod tests {
|
||||
blk("a", &["ret void"]),
|
||||
blk("b", &["ret void"]),
|
||||
];
|
||||
assert!(
|
||||
super::super::structured_emit::structured_plan_ladder(&blocks, false).is_none(),
|
||||
"ordinary ladder must retain the pre-C1 reject proxy"
|
||||
);
|
||||
assert!(super::super::structured_emit::structured_plan_ladder(&blocks, false).is_some());
|
||||
let out = unify_returns(&blocks).expect("two rets to unify");
|
||||
// Both arms now branch to the same exit.
|
||||
let a = out.iter().find(|x| x.name == "%a").unwrap();
|
||||
@@ -540,10 +540,7 @@ mod tests {
|
||||
&["%rv = phi i32 [ 1, %entry ], [ 2, %a ]", "ret i32 %rv"],
|
||||
),
|
||||
];
|
||||
assert!(
|
||||
super::super::structured_emit::structured_plan_ladder(&blocks, false).is_none(),
|
||||
"ordinary ladder must retain the divergent-exit reject proxy"
|
||||
);
|
||||
assert!(super::super::structured_emit::structured_plan_ladder(&blocks, false).is_some());
|
||||
let unified =
|
||||
separate_divergent_selection_exits(&blocks).expect("return-like exits must unify");
|
||||
let private = privatize_shared_phi_exit_predecessors(&unified);
|
||||
|
||||
@@ -46,6 +46,7 @@ pub(in crate::native) fn lower_unreachable_to_ret(blocks: &[BodyBlock]) -> Optio
|
||||
if is_unreachable {
|
||||
// Rewrite the `unreachable` -> `ret` terminator on the carrier.
|
||||
if let Some(t) = &mut b.typed {
|
||||
let t = std::sync::Arc::make_mut(t);
|
||||
t.set_terminator_line(&model);
|
||||
}
|
||||
hit = true;
|
||||
@@ -151,6 +152,7 @@ fn unify_return_like_exits(
|
||||
// Rewrite the return-like terminator to a branch to the unified exit (on the carrier, the sole
|
||||
// substrate).
|
||||
if let Some(t) = &mut out[*idx].typed {
|
||||
let t = std::sync::Arc::make_mut(t);
|
||||
t.set_unconditional_branch(&exit);
|
||||
}
|
||||
}
|
||||
@@ -172,7 +174,7 @@ fn unify_return_like_exits(
|
||||
out.push(BodyBlock {
|
||||
name: exit,
|
||||
role,
|
||||
typed,
|
||||
typed: typed.map(Into::into),
|
||||
});
|
||||
Some(out)
|
||||
}
|
||||
|
||||
@@ -289,6 +289,7 @@ pub(in crate::native) fn privatize_region(
|
||||
for b in out.iter_mut() {
|
||||
if b.name == arm {
|
||||
if let Some(t) = &mut b.typed {
|
||||
let t = std::sync::Arc::make_mut(t);
|
||||
t.rebuild_phi_incomings(|pred| !redirect.contains(pred));
|
||||
}
|
||||
}
|
||||
@@ -299,6 +300,7 @@ pub(in crate::native) fn privatize_region(
|
||||
for b in out.iter_mut() {
|
||||
if redirect.contains(&b.name) {
|
||||
if let Some(t) = &mut b.typed {
|
||||
let t = std::sync::Arc::make_mut(t);
|
||||
t.redirect_successor(arm, &arm_clone);
|
||||
}
|
||||
}
|
||||
@@ -339,13 +341,13 @@ pub(in crate::native) fn privatize_region(
|
||||
// A rename-cloned block: its name is the carried identity, so the role tracks the (possibly
|
||||
// still-`texitret`-prefixed, possibly renamed-away) clone name.
|
||||
let role = role_for_name(&clone_name);
|
||||
let mut c = src_carrier.clone();
|
||||
let mut c = (**src_carrier).clone();
|
||||
c.rebuild_phi_incomings(keep);
|
||||
c.rename(&rename);
|
||||
out.push(BodyBlock {
|
||||
name: clone_name,
|
||||
role,
|
||||
typed: Some(c),
|
||||
typed: Some(c.into()),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -476,6 +478,7 @@ pub(in crate::native) fn privatize_dominated_region(
|
||||
for b in out.iter_mut() {
|
||||
if b.name == arm {
|
||||
if let Some(t) = &mut b.typed {
|
||||
let t = std::sync::Arc::make_mut(t);
|
||||
t.rebuild_phi_incomings(|p| !redirect.contains(p));
|
||||
}
|
||||
}
|
||||
@@ -484,6 +487,7 @@ pub(in crate::native) fn privatize_dominated_region(
|
||||
for b in out.iter_mut() {
|
||||
if redirect.contains(&b.name) {
|
||||
if let Some(t) = &mut b.typed {
|
||||
let t = std::sync::Arc::make_mut(t);
|
||||
t.redirect_successor(arm, &arm_clone);
|
||||
}
|
||||
}
|
||||
@@ -494,6 +498,7 @@ pub(in crate::native) fn privatize_dominated_region(
|
||||
for b in out.iter_mut() {
|
||||
if boundary.contains(&b.name) {
|
||||
if let Some(t) = &mut b.typed {
|
||||
let t = std::sync::Arc::make_mut(t);
|
||||
t.mirror_region_incomings(®ion, &rename);
|
||||
}
|
||||
}
|
||||
@@ -523,13 +528,13 @@ pub(in crate::native) fn privatize_dominated_region(
|
||||
}
|
||||
}
|
||||
let role = role_for_name(&clone_name);
|
||||
let mut c = src_carrier.clone();
|
||||
let mut c = (**src_carrier).clone();
|
||||
c.rebuild_phi_incomings(keep);
|
||||
c.rename(&rename);
|
||||
out.push(BodyBlock {
|
||||
name: clone_name,
|
||||
role,
|
||||
typed: Some(c),
|
||||
typed: Some(c.into()),
|
||||
});
|
||||
}
|
||||
Some(out)
|
||||
|
||||
+145
-63
@@ -1,80 +1,162 @@
|
||||
//! Iterative dominator-set analysis over an emitted SPIR-V function's CFG.
|
||||
//! Compact dominance over an emitted SPIR-V function CFG.
|
||||
//!
|
||||
//! Shared by [`super::ssa_demote`] and [`super::loop_split`], which both need emitted-CFG dominance
|
||||
//! (`dominates(a, b)` == `doms[b].contains(a)`) over the reachable subgraph.
|
||||
//! Shared by late native rewrites and the emitter's phi-materialization repair. The immediate-
|
||||
//! dominator tree uses O(V + E) storage and answers dominance with DFS intervals; the former
|
||||
//! `label -> HashSet<all dominators>` representation was O(V²) and drove large translations far
|
||||
//! beyond their resident-memory budget even after those temporary sets were freed.
|
||||
|
||||
use super::graph::spirv_predecessor_ids_by_label;
|
||||
use spirv::Word;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Iterative dominator-set computation (`node -> set of blocks that dominate it`) over the reachable
|
||||
/// subgraph. Standard fixpoint intersection of predecessors' dominators; unreachable blocks are left
|
||||
/// out (they carry no structured-exit meaning). Shared with [`super::ssa_demote`], which needs the same
|
||||
/// emitted-CFG dominance to find defs that no longer dominate their uses.
|
||||
pub(super) fn dominator_sets(
|
||||
entry: Word,
|
||||
labels: &[Word],
|
||||
successors: &HashMap<Word, Vec<Word>>,
|
||||
) -> HashMap<Word, HashSet<Word>> {
|
||||
let preds = spirv_predecessor_ids_by_label(successors);
|
||||
let reachable = reachable_from(entry, successors);
|
||||
let all: HashSet<Word> = labels
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|l| reachable.contains(l))
|
||||
.collect();
|
||||
pub(in crate::native) struct EmittedDominators {
|
||||
index: HashMap<Word, usize>,
|
||||
preorder: Vec<usize>,
|
||||
postorder: Vec<usize>,
|
||||
depth: Vec<usize>,
|
||||
}
|
||||
|
||||
let mut dom: HashMap<Word, HashSet<Word>> = HashMap::new();
|
||||
for &l in labels {
|
||||
if !reachable.contains(&l) {
|
||||
continue;
|
||||
}
|
||||
if l == entry {
|
||||
dom.insert(l, HashSet::from([l]));
|
||||
} else {
|
||||
dom.insert(l, all.clone());
|
||||
}
|
||||
}
|
||||
loop {
|
||||
let mut changed = false;
|
||||
for &l in labels {
|
||||
if l == entry || !reachable.contains(&l) {
|
||||
impl EmittedDominators {
|
||||
pub(in crate::native) fn new(
|
||||
entry: Word,
|
||||
labels: &[Word],
|
||||
successors_by_label: &HashMap<Word, Vec<Word>>,
|
||||
) -> Self {
|
||||
let index = labels
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(idx, label)| (*label, idx))
|
||||
.collect::<HashMap<_, _>>();
|
||||
let mut successors = vec![Vec::new(); labels.len()];
|
||||
let mut predecessors = vec![Vec::new(); labels.len()];
|
||||
for (&label, targets) in successors_by_label {
|
||||
let Some(&from) = index.get(&label) else {
|
||||
continue;
|
||||
}
|
||||
let mut acc: Option<HashSet<Word>> = None;
|
||||
for &p in preds.get(&l).into_iter().flatten() {
|
||||
if !reachable.contains(&p) {
|
||||
};
|
||||
for target in targets {
|
||||
let Some(&to) = index.get(target) else {
|
||||
continue;
|
||||
}
|
||||
match &mut acc {
|
||||
None => acc = Some(dom[&p].clone()),
|
||||
Some(a) => a.retain(|x| dom[&p].contains(x)),
|
||||
}
|
||||
}
|
||||
let mut next = acc.unwrap_or_default();
|
||||
next.insert(l);
|
||||
if dom.get(&l) != Some(&next) {
|
||||
dom.insert(l, next);
|
||||
changed = true;
|
||||
};
|
||||
successors[from].push(to);
|
||||
predecessors[to].push(from);
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
break;
|
||||
|
||||
let mut rpo = Vec::new();
|
||||
if let Some(&entry) = index.get(&entry) {
|
||||
let mut seen = vec![false; labels.len()];
|
||||
let mut stack = vec![(entry, 0usize)];
|
||||
seen[entry] = true;
|
||||
while let Some((node, next)) = stack.last_mut() {
|
||||
if *next < successors[*node].len() {
|
||||
let successor = successors[*node][*next];
|
||||
*next += 1;
|
||||
if !seen[successor] {
|
||||
seen[successor] = true;
|
||||
stack.push((successor, 0));
|
||||
}
|
||||
} else {
|
||||
rpo.push(*node);
|
||||
stack.pop();
|
||||
}
|
||||
}
|
||||
rpo.reverse();
|
||||
}
|
||||
let mut rpo_rank = vec![usize::MAX; labels.len()];
|
||||
for (rank, node) in rpo.iter().copied().enumerate() {
|
||||
rpo_rank[node] = rank;
|
||||
}
|
||||
let mut idom = vec![None; labels.len()];
|
||||
if let Some(&entry) = rpo.first() {
|
||||
idom[entry] = Some(entry);
|
||||
loop {
|
||||
let mut changed = false;
|
||||
for node in rpo.iter().copied().skip(1) {
|
||||
let mut defined = predecessors[node]
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|pred| idom[*pred].is_some());
|
||||
let Some(mut next_idom) = defined.next() else {
|
||||
continue;
|
||||
};
|
||||
for pred in defined {
|
||||
next_idom = intersect(pred, next_idom, &idom, &rpo_rank);
|
||||
}
|
||||
if idom[node] != Some(next_idom) {
|
||||
idom[node] = Some(next_idom);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut children = vec![Vec::new(); labels.len()];
|
||||
for (node, parent) in idom.iter().copied().enumerate() {
|
||||
if let Some(parent) = parent.filter(|parent| *parent != node) {
|
||||
children[parent].push(node);
|
||||
}
|
||||
}
|
||||
let mut preorder = vec![usize::MAX; labels.len()];
|
||||
let mut postorder = vec![usize::MAX; labels.len()];
|
||||
let mut depth = vec![0; labels.len()];
|
||||
if let Some(&entry) = rpo.first() {
|
||||
let mut clock = 0usize;
|
||||
let mut stack = vec![(entry, 0usize)];
|
||||
preorder[entry] = clock;
|
||||
depth[entry] = 1;
|
||||
clock += 1;
|
||||
while let Some((node, next)) = stack.last_mut() {
|
||||
if *next < children[*node].len() {
|
||||
let child = children[*node][*next];
|
||||
*next += 1;
|
||||
preorder[child] = clock;
|
||||
depth[child] = depth[*node] + 1;
|
||||
clock += 1;
|
||||
stack.push((child, 0));
|
||||
} else {
|
||||
postorder[*node] = clock;
|
||||
stack.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
Self {
|
||||
index,
|
||||
preorder,
|
||||
postorder,
|
||||
depth,
|
||||
}
|
||||
}
|
||||
dom
|
||||
|
||||
pub(in crate::native) fn dominates(&self, dominator: Word, node: Word) -> bool {
|
||||
let (Some(&dominator), Some(&node)) = (self.index.get(&dominator), self.index.get(&node))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
self.preorder[dominator] != usize::MAX
|
||||
&& self.preorder[dominator] <= self.preorder[node]
|
||||
&& self.preorder[node] < self.postorder[dominator]
|
||||
}
|
||||
|
||||
pub(in crate::native) fn depth(&self, label: Word) -> usize {
|
||||
self.index.get(&label).map_or(0, |index| self.depth[*index])
|
||||
}
|
||||
}
|
||||
|
||||
fn reachable_from(entry: Word, successors: &HashMap<Word, Vec<Word>>) -> HashSet<Word> {
|
||||
let mut seen = HashSet::new();
|
||||
let mut stack = vec![entry];
|
||||
while let Some(n) = stack.pop() {
|
||||
if !seen.insert(n) {
|
||||
continue;
|
||||
fn intersect(
|
||||
mut left: usize,
|
||||
mut right: usize,
|
||||
idom: &[Option<usize>],
|
||||
rpo_rank: &[usize],
|
||||
) -> usize {
|
||||
while left != right {
|
||||
while rpo_rank[left] > rpo_rank[right] {
|
||||
left = idom[left].expect("defined dominator chain");
|
||||
}
|
||||
for &s in successors.get(&n).into_iter().flatten() {
|
||||
stack.push(s);
|
||||
while rpo_rank[right] > rpo_rank[left] {
|
||||
right = idom[right].expect("defined dominator chain");
|
||||
}
|
||||
}
|
||||
seen
|
||||
left
|
||||
}
|
||||
+48
-92
@@ -100,7 +100,8 @@ impl Cfg {
|
||||
.map(|(i, n)| (n.as_str(), i))
|
||||
.collect();
|
||||
let idom = compute_idom(&self.entry, &self.predecessors, &rpo, &rpo_num);
|
||||
Dominators { idom }
|
||||
let intervals = dominance_intervals(&self.entry, &idom);
|
||||
Dominators { idom, intervals }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,21 +110,23 @@ impl Cfg {
|
||||
pub(in crate::native) struct Dominators {
|
||||
/// Immediate dominator of each block (entry maps to itself).
|
||||
idom: HashMap<String, String>,
|
||||
/// Euler intervals of the immediate-dominator tree. Dominance is interval containment, avoiding
|
||||
/// an O(tree depth) parent walk at every query in large generated CFGs.
|
||||
intervals: HashMap<String, (usize, usize)>,
|
||||
}
|
||||
|
||||
impl Dominators {
|
||||
/// `true` if `dominator` dominates `node` (walking the idom chain).
|
||||
pub(in crate::native) fn dominates(&self, dominator: &str, node: &str) -> bool {
|
||||
let mut cur = node;
|
||||
loop {
|
||||
if cur == dominator {
|
||||
return true;
|
||||
}
|
||||
match self.idom.get(cur) {
|
||||
Some(next) if next != cur => cur = next,
|
||||
_ => return false,
|
||||
}
|
||||
if dominator == node {
|
||||
return true;
|
||||
}
|
||||
let (Some(&(dom_in, dom_out)), Some(&(node_in, node_out))) =
|
||||
(self.intervals.get(dominator), self.intervals.get(node))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
dom_in <= node_in && node_out <= dom_out
|
||||
}
|
||||
|
||||
/// Immediate dominator of `node` (the entry, and any node mapping to itself, returns `None`).
|
||||
@@ -135,6 +138,40 @@ impl Dominators {
|
||||
}
|
||||
}
|
||||
|
||||
fn dominance_intervals(
|
||||
entry: &str,
|
||||
idom: &HashMap<String, String>,
|
||||
) -> HashMap<String, (usize, usize)> {
|
||||
let mut children = HashMap::<&str, Vec<&str>>::new();
|
||||
for (node, parent) in idom {
|
||||
if node != parent {
|
||||
children.entry(parent).or_default().push(node);
|
||||
}
|
||||
}
|
||||
for descendants in children.values_mut() {
|
||||
descendants.sort_unstable();
|
||||
}
|
||||
let mut entered = HashMap::<String, usize>::new();
|
||||
let mut intervals = HashMap::new();
|
||||
let mut clock = 0usize;
|
||||
let mut stack = vec![(entry, false)];
|
||||
while let Some((node, exiting)) = stack.pop() {
|
||||
if exiting {
|
||||
let start = entered[node];
|
||||
intervals.insert(node.to_string(), (start, clock));
|
||||
clock += 1;
|
||||
continue;
|
||||
}
|
||||
entered.insert(node.to_string(), clock);
|
||||
clock += 1;
|
||||
stack.push((node, true));
|
||||
if let Some(descendants) = children.get(node) {
|
||||
stack.extend(descendants.iter().rev().map(|child| (*child, false)));
|
||||
}
|
||||
}
|
||||
intervals
|
||||
}
|
||||
|
||||
/// Reverse postorder of the blocks reachable from `entry`, restricted to `names`.
|
||||
///
|
||||
/// Exposed so the reverse-graph post-dominator computation in [`super::loopforest`]
|
||||
@@ -269,46 +306,6 @@ pub(super) fn reachable_from(
|
||||
seen
|
||||
}
|
||||
|
||||
/// Blocks reachable from `start` (inclusive) without expanding through `forbidden` — the
|
||||
/// `forbidden` node is treated as a sink (visited but never traversed past).
|
||||
pub(super) fn reachable_from_without_revisiting(
|
||||
start: &str,
|
||||
forbidden: &str,
|
||||
successors: &HashMap<String, Vec<String>>,
|
||||
) -> HashSet<String> {
|
||||
let mut seen = HashSet::new();
|
||||
let mut stack = vec![start.to_string()];
|
||||
while let Some(block) = stack.pop() {
|
||||
if block == forbidden || !seen.insert(block.clone()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(next) = successors.get(&block) {
|
||||
stack.extend(next.iter().cloned());
|
||||
}
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
/// Blocks reachable from `start` without crossing `target` — `target` is excluded from the
|
||||
/// result and never expanded, so the walk stays strictly before the merge point.
|
||||
pub(super) fn reachable_before_target(
|
||||
start: &str,
|
||||
target: &str,
|
||||
successors: &HashMap<String, Vec<String>>,
|
||||
) -> HashSet<String> {
|
||||
let mut seen = HashSet::new();
|
||||
let mut stack = vec![start.to_string()];
|
||||
while let Some(node) = stack.pop() {
|
||||
if node == target || !seen.insert(node.clone()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(next) = successors.get(&node) {
|
||||
stack.extend(next.iter().filter(|succ| succ.as_str() != target).cloned());
|
||||
}
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
// --- Owned SPIR-V (`Block`) CFG primitives -------------------------------------------------
|
||||
//
|
||||
// The above operate on the `BodyBlock` source CFG (String labels). The emitter's control-flow
|
||||
@@ -394,47 +391,6 @@ pub(in crate::native) fn spirv_predecessor_ids_by_label(
|
||||
predecessors
|
||||
}
|
||||
|
||||
/// Whether `dominator` dominates `label` in a precomputed Word-keyed dominator-set map
|
||||
/// (`label -> {blocks that dominate it}`).
|
||||
pub(in crate::native) fn spirv_label_dominates(
|
||||
dominators: &HashMap<Word, HashSet<Word>>,
|
||||
dominator: Word,
|
||||
label: Word,
|
||||
) -> bool {
|
||||
dominators
|
||||
.get(&label)
|
||||
.is_some_and(|labels| labels.contains(&dominator))
|
||||
}
|
||||
|
||||
// Dense `[u64]` bitset helpers for the native Word-layer CFG analyses (the dominator-set
|
||||
// fixpoint in the emitter, the reachability walks in cfg/repair). One home so the two former
|
||||
// copies of `set_bit`/`bit_is_set` cannot drift. `bit_is_set` is bounds-checked (out-of-range
|
||||
// index reads as unset) — a no-op for callers whose words always cover the queried index.
|
||||
pub(in crate::native) fn set_bit(bits: &mut [u64], idx: usize) {
|
||||
bits[idx / 64] |= 1 << (idx % 64);
|
||||
}
|
||||
|
||||
pub(in crate::native) fn bit_is_set(bits: &[u64], idx: usize) -> bool {
|
||||
bits.get(idx / 64)
|
||||
.is_some_and(|word| (word & (1 << (idx % 64))) != 0)
|
||||
}
|
||||
|
||||
/// Clear the bits above `valid_bits` in the last word so a full-ones bitset has no stray
|
||||
/// high bits set beyond the valid range.
|
||||
pub(in crate::native) fn clear_unused_bits(words: &mut [u64], valid_bits: usize) {
|
||||
if valid_bits == 0 {
|
||||
return;
|
||||
}
|
||||
let used_in_last = valid_bits % u64::BITS as usize;
|
||||
if used_in_last == 0 {
|
||||
return;
|
||||
}
|
||||
let mask = (1u64 << used_in_last) - 1;
|
||||
if let Some(last) = words.last_mut() {
|
||||
*last &= mask;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -449,7 +405,7 @@ mod tests {
|
||||
BodyBlock {
|
||||
name,
|
||||
role: crate::native::cfg::BlockRole::Normal,
|
||||
typed,
|
||||
typed: typed.map(Into::into),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,8 +25,8 @@
|
||||
//! place (that function stays on the floor, no regression). Decides purely from IR structure (loop
|
||||
//! merges, block edges, dominance), never a shader name.
|
||||
|
||||
use super::exit_check::dominator_sets;
|
||||
use super::graph::{spirv_block_successors_by_label, spirv_predecessor_ids_by_label};
|
||||
use super::EmittedDominators;
|
||||
use crate::spirv_module::Module;
|
||||
use crate::spirv_module::Operand;
|
||||
use crate::spirv_module::{Block, Function, Instruction};
|
||||
@@ -82,9 +82,9 @@ fn split_in_function(function: &mut Function, fresh: &mut impl FnMut() -> Word)
|
||||
let label_set: HashSet<Word> = labels.iter().copied().collect();
|
||||
let successors = spirv_block_successors_by_label(&function.blocks);
|
||||
let preds = spirv_predecessor_ids_by_label(&successors);
|
||||
let doms = dominator_sets(entry, &labels, &successors);
|
||||
let dominates = |a: Word, b: Word| doms.get(&b).is_some_and(|s| s.contains(&a));
|
||||
let depth = |n: Word| doms.get(&n).map(|s| s.len()).unwrap_or(0);
|
||||
let dominators = EmittedDominators::new(entry, &labels, &successors);
|
||||
let dominates = |a: Word, b: Word| dominators.dominates(a, b);
|
||||
let depth = |n: Word| dominators.depth(n);
|
||||
|
||||
// Loop headers (block with OpLoopMerge) → its merge block.
|
||||
let mut loop_merge: HashMap<Word, Word> = HashMap::new();
|
||||
|
||||
@@ -66,6 +66,20 @@ impl LoopForest {
|
||||
/// restructuring (node-splitting) first. This is the planning layer of R2; it does not change
|
||||
/// emission on its own.
|
||||
pub(in crate::native) fn structured_plan(&self) -> Vec<LoopPlan> {
|
||||
self.structured_plan_ignoring_exits(&HashSet::new())
|
||||
}
|
||||
|
||||
/// Build the same loop plan while excluding proven terminal targets from merge selection.
|
||||
///
|
||||
/// A branch to a bare `unreachable` terminates that invocation inside the construct; it is not a
|
||||
/// continuation destination that needs to compete for `OpLoopMerge`. Callers retain the raw exit
|
||||
/// inventory on [`NaturalLoop`] and opt into this projection only after proving the ignored block
|
||||
/// is terminal. If every raw exit is ignored, keep the raw set: a loop with only terminal exits is
|
||||
/// not the same thing as a genuinely non-terminating loop and needs separate construction.
|
||||
pub(in crate::native) fn structured_plan_ignoring_exits(
|
||||
&self,
|
||||
ignored: &HashSet<String>,
|
||||
) -> Vec<LoopPlan> {
|
||||
// Every block that is some loop's latch (a continue target).
|
||||
let all_latches: HashSet<&str> = self
|
||||
.loops
|
||||
@@ -75,27 +89,38 @@ impl LoopForest {
|
||||
self.loops
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let live_exits = l
|
||||
.exits
|
||||
.iter()
|
||||
.filter(|exit| !ignored.contains(*exit))
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
let exits = if live_exits.is_empty() {
|
||||
&l.exits
|
||||
} else {
|
||||
&live_exits
|
||||
};
|
||||
let mut restructure = Vec::new();
|
||||
if l.latches.len() > 1 {
|
||||
restructure.push(Restructure::MultipleLatches);
|
||||
}
|
||||
if l.exits.len() > 1 {
|
||||
if exits.len() > 1 {
|
||||
restructure.push(Restructure::MultipleExits);
|
||||
}
|
||||
// A single exit that is also another loop's continue (the 2647a6f3 overlap): the
|
||||
// structured merge can't be that block; it must be split.
|
||||
if let [exit] = l.exits.as_slice() {
|
||||
if let [exit] = exits.as_slice() {
|
||||
if all_latches.contains(exit.as_str()) {
|
||||
restructure.push(Restructure::MergeIsEnclosingContinue);
|
||||
}
|
||||
}
|
||||
if l.exits.is_empty() {
|
||||
if exits.is_empty() {
|
||||
restructure.push(Restructure::NoExit);
|
||||
}
|
||||
LoopPlan {
|
||||
header: l.header.clone(),
|
||||
continue_block: l.latches.first().cloned(),
|
||||
merge_block: l.exits.first().cloned(),
|
||||
merge_block: exits.first().cloned(),
|
||||
restructure,
|
||||
}
|
||||
})
|
||||
@@ -221,6 +246,25 @@ pub(in crate::native) fn analyze(blocks: &[BodyBlock]) -> LoopForest {
|
||||
forest
|
||||
}
|
||||
|
||||
/// Recompute dominance while retaining a previously proven natural-loop forest.
|
||||
///
|
||||
/// This is for edge-splitting rewrites that only redirect terminal destinations and append acyclic
|
||||
/// leaf/pass-through blocks. Such rewrites cannot create or remove a back-edge, change a loop body,
|
||||
/// or change loop nesting, but their new blocks still need current dominance. Avoiding natural-loop
|
||||
/// rediscovery is material for generated functions with hundreds of nested/overlapping loop records.
|
||||
pub(in crate::native) fn analyze_reusing_natural_loops(
|
||||
blocks: &[BodyBlock],
|
||||
loops: &[NaturalLoop],
|
||||
) -> LoopForest {
|
||||
let Some(cfg) = Cfg::from_blocks(blocks) else {
|
||||
return LoopForest::default();
|
||||
};
|
||||
LoopForest {
|
||||
loops: loops.to_vec(),
|
||||
doms: cfg.dominators(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Natural loop of a back-edge set: header plus every block that can reach a latch without passing
|
||||
/// back through the header.
|
||||
fn natural_loop_body(
|
||||
@@ -497,7 +541,46 @@ pub(in crate::native) fn selection_merges(
|
||||
blocks: &[BodyBlock],
|
||||
forest: &LoopForest,
|
||||
) -> HashMap<String, String> {
|
||||
selection_merges_from_pidom(blocks, forest, &post_idom(blocks))
|
||||
// A switch's terminal `unreachable` case is a structured exit from the selection, not a second
|
||||
// reconvergence path. Switch lowering already applies this rule through `infer_switch_merges`;
|
||||
// apply the same contract to the source-CFG post-dominator analysis so the two planners cannot
|
||||
// disagree and strand an otherwise ordinary switch without an `OpSelectionMerge`.
|
||||
let unreachable_targets: HashSet<&str> = blocks
|
||||
.iter()
|
||||
.filter(|block| {
|
||||
block.typed.as_ref().is_some_and(|typed| {
|
||||
typed.insts.is_empty()
|
||||
&& matches!(
|
||||
typed.terminator,
|
||||
crate::native::tir::TirTerminator::Unreachable
|
||||
)
|
||||
})
|
||||
})
|
||||
.map(|block| block.name.as_str())
|
||||
.collect();
|
||||
let mut terminal_switch_edges = HashSet::new();
|
||||
for block in blocks {
|
||||
let is_switch = block.typed.as_ref().is_some_and(|typed| {
|
||||
matches!(
|
||||
typed.terminator,
|
||||
crate::native::tir::TirTerminator::Switch { .. }
|
||||
)
|
||||
});
|
||||
if !is_switch {
|
||||
continue;
|
||||
}
|
||||
for target in block_successors(block) {
|
||||
if unreachable_targets.contains(target.as_str()) {
|
||||
terminal_switch_edges.insert((block.name.clone(), target));
|
||||
}
|
||||
}
|
||||
}
|
||||
let pidom = if terminal_switch_edges.is_empty() {
|
||||
post_idom(blocks)
|
||||
} else {
|
||||
post_idom_cut(blocks, &terminal_switch_edges)
|
||||
};
|
||||
selection_merges_from_pidom(blocks, forest, &pidom)
|
||||
}
|
||||
|
||||
/// Break-aware [`selection_merges`]: computes each selection header's merge on a post-dominator graph
|
||||
@@ -601,7 +684,7 @@ mod tests {
|
||||
BodyBlock {
|
||||
name,
|
||||
role: crate::native::cfg::BlockRole::Normal,
|
||||
typed,
|
||||
typed: typed.map(Into::into),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -882,6 +965,25 @@ mod tests {
|
||||
assert_eq!(merges.get("%G").map(String::as_str), Some("%gm"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switch_merge_ignores_terminal_unreachable_arm() {
|
||||
// The default arm terminates the invocation and therefore exits the switch construct. The two
|
||||
// live cases still reconverge at m, which is the switch's structured selection merge.
|
||||
let blocks = vec![
|
||||
blk(
|
||||
"sw",
|
||||
"switch i32 %s, label %dead [ i32 0, label %a i32 1, label %b ]",
|
||||
),
|
||||
blk("a", "br label %m"),
|
||||
blk("b", "br label %m"),
|
||||
blk("dead", "unreachable"),
|
||||
blk("m", "ret void"),
|
||||
];
|
||||
let forest = analyze(&blocks);
|
||||
let merges = selection_merges(&blocks, &forest);
|
||||
assert_eq!(merges.get("%sw").map(String::as_str), Some("%m"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_merge_skips_loop_header() {
|
||||
// A loop header's conditional (exit test) is an OpLoopMerge, not an OpSelectionMerge.
|
||||
|
||||
+17
-7
@@ -12,7 +12,8 @@ pub(super) mod loopforest;
|
||||
// byte-identical by construction.
|
||||
pub(super) mod clone_crossarm;
|
||||
mod repair;
|
||||
// Dominator-set analysis over the emitted CFG, consumed by ssa_demote and loop_split.
|
||||
// Compact immediate-dominator analysis over the emitted CFG, shared by late rewrites and emitter
|
||||
// phi-materialization repair.
|
||||
mod exit_check;
|
||||
// Loop-closed-SSA repair on the emitted module: register-demote a value whose def block no longer
|
||||
// dominates a use (the `synth_multi_exit_merge` funnel gap), so the PRIMARY structured emit validates
|
||||
@@ -34,6 +35,7 @@ pub(super) use clone_crossarm::{
|
||||
clone_cross_arm_shared, lower_unreachable_to_ret, privatize_region_cross_arm, rename_tokens,
|
||||
unify_returns,
|
||||
};
|
||||
pub(in crate::native) use exit_check::EmittedDominators;
|
||||
pub(super) use loop_split::split_multientry_loop_selection_exits;
|
||||
pub(super) use ssa_demote::demote_nondominating_values;
|
||||
pub(super) use structured_emit::{
|
||||
@@ -44,8 +46,10 @@ pub(super) use structured_emit::{
|
||||
};
|
||||
|
||||
pub(super) use blocks::{
|
||||
implicit_entry_block_name, infer_branch_merges, infer_loop_merges, infer_switch_merges,
|
||||
lower_unstructured_switches, split_body_blocks,
|
||||
funnel_shared_branch_dispatches, implicit_entry_block_name,
|
||||
infer_bounded_branch_merges_by_header, infer_branch_merges, infer_direct_branch_merges,
|
||||
infer_direct_switch_merges, infer_loop_merges, infer_switch_merges,
|
||||
lower_unstructured_switches, refunnel_one_deep_shared_arm, split_body_blocks,
|
||||
};
|
||||
pub(super) use repair::{block_index_by_label, id_ref_operand};
|
||||
|
||||
@@ -56,9 +60,9 @@ pub(super) struct LoopMergeInfo {
|
||||
}
|
||||
|
||||
/// The structural ROLE of a synthesized block, stamped by the synthesizer that creates it so
|
||||
/// consumers recover the role from a typed tag instead of decoding it from the block's NAME (the
|
||||
/// name-encoded-semantics debt Workstream T3 retires). The synthesized name is still EMITTED (it is
|
||||
/// the block label / `OpName` in the output, byte-identical), but no production DECISION reads it.
|
||||
/// consumers recover the role from a typed tag instead of decoding it from the block's name. The
|
||||
/// synthesized name is still emitted as the block label / `OpName`, but no production decision
|
||||
/// reads it.
|
||||
/// `Normal` is every ordinary block (an AIR label or a synthesized block whose role no consumer yet
|
||||
/// queries); non-`Normal` variants are added as each name-prefix consumer migrates to the tag.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
@@ -102,10 +106,16 @@ pub(super) struct BodyBlock {
|
||||
/// one place block instructions are lexed) and rebuilt via the typed `phi_edit`/terminator primitives
|
||||
/// at every synthesis/mutation site. `None` only for a block whose lines did not lower (no
|
||||
/// terminator); such a block is a fail-visible `build_from_blocks` error, not a re-lower fallback.
|
||||
pub(super) typed: Option<crate::native::tir::TirBlock>,
|
||||
pub(super) typed: Option<std::sync::Arc<crate::native::tir::TirBlock>>,
|
||||
}
|
||||
|
||||
impl BodyBlock {
|
||||
/// Mutable access to the typed carrier with copy-on-write semantics. Planner candidates share
|
||||
/// immutable AIR instruction payload; only a block whose transform actually edits it is cloned.
|
||||
pub(super) fn typed_mut(&mut self) -> Option<&mut crate::native::tir::TirBlock> {
|
||||
self.typed.as_mut().map(std::sync::Arc::make_mut)
|
||||
}
|
||||
|
||||
/// The block's instruction + terminator lines, rendered from its typed carrier (the sole substrate).
|
||||
/// TEST-ONLY: the CFG-restructuring unit tests were written against the retired `.lines` field; this
|
||||
/// reproduces those lines from the carrier so the assertions read structured output as text. Panics
|
||||
|
||||
@@ -22,8 +22,8 @@
|
||||
//! the floor, no regression). Decides purely from IR structure (block edges, dominance, value
|
||||
//! def/use), never a shader name.
|
||||
|
||||
use super::exit_check::dominator_sets;
|
||||
use super::graph::spirv_block_successors_by_label;
|
||||
use super::EmittedDominators;
|
||||
use crate::spirv_module::Operand;
|
||||
use crate::spirv_module::{Function, Instruction, Module};
|
||||
use spirv::{Op, StorageClass, Word};
|
||||
@@ -141,12 +141,10 @@ fn demote_in_function(
|
||||
}
|
||||
}
|
||||
let successors = spirv_block_successors_by_label(&function.blocks);
|
||||
let doms = dominator_sets(entry, &labels, &successors);
|
||||
let dominators = EmittedDominators::new(entry, &labels, &successors);
|
||||
// A block whose dominators were not computed (unreachable) dominates nothing reachable and is
|
||||
// dominated by nothing — treat as non-dominating so its dead uses are left alone.
|
||||
let dominates = |a_label: Word, b_label: Word| -> bool {
|
||||
doms.get(&b_label).is_some_and(|s| s.contains(&a_label))
|
||||
};
|
||||
let dominates = |a_label: Word, b_label: Word| dominators.dominates(a_label, b_label);
|
||||
|
||||
// value id -> (def block index, result type), for every value defined in the function body.
|
||||
let mut def_block: HashMap<Word, usize> = HashMap::new();
|
||||
|
||||
@@ -295,9 +295,11 @@ pub(in crate::native) fn materialize_construct_routes(
|
||||
.map(|step| format!("{ROUTE_PREFIX}{route_index}.{step}"))
|
||||
.collect();
|
||||
if let Some(source) = out[route.edge.from].typed.as_mut() {
|
||||
let source = std::sync::Arc::make_mut(source);
|
||||
source.redirect_successor(&target_name, &route_names[0]);
|
||||
}
|
||||
if let Some(target) = out[route.edge.to].typed.as_mut() {
|
||||
let target = std::sync::Arc::make_mut(target);
|
||||
target.rewrite_phi_predecessor(
|
||||
&source_name,
|
||||
route_names.last().expect("non-empty route"),
|
||||
@@ -337,7 +339,7 @@ mod tests {
|
||||
BodyBlock {
|
||||
name: name.to_string(),
|
||||
role: BlockRole::Normal,
|
||||
typed: tir::lower_block_carrier(name, &lines, &HashMap::new()),
|
||||
typed: tir::lower_block_carrier(name, &lines, &HashMap::new()).map(Into::into),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -43,14 +43,6 @@ struct ValueSlot {
|
||||
next: String,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CaseUpdate {
|
||||
join: String,
|
||||
pc: LlValue,
|
||||
phi_slots: Vec<LlValue>,
|
||||
value_slots: Vec<LlValue>,
|
||||
}
|
||||
|
||||
fn passthrough(name: &str, target: &str) -> BodyBlock {
|
||||
synthetic_block(
|
||||
name.to_string(),
|
||||
@@ -82,7 +74,7 @@ fn carrier_with_phis(
|
||||
Ok(BodyBlock {
|
||||
name: name.to_string(),
|
||||
role,
|
||||
typed: Some(carrier),
|
||||
typed: Some(carrier.into()),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -105,6 +97,7 @@ fn collect_value_locals(value: &LlValue, out: &mut Vec<String>) {
|
||||
collect_value_locals(&index.value, out);
|
||||
}
|
||||
}
|
||||
LlValue::IntToPtr { source, .. } => collect_value_locals(&source.value, out),
|
||||
LlValue::Global(_)
|
||||
| LlValue::Bool(_)
|
||||
| LlValue::Int(_)
|
||||
@@ -146,6 +139,9 @@ fn substitute_cross_slot_value(
|
||||
substitute_cross_slot_value(&mut index.value, value_slots, source);
|
||||
}
|
||||
}
|
||||
LlValue::IntToPtr {
|
||||
source: operand, ..
|
||||
} => substitute_cross_slot_value(&mut operand.value, value_slots, source),
|
||||
LlValue::Global(_)
|
||||
| LlValue::Bool(_)
|
||||
| LlValue::Int(_)
|
||||
@@ -471,24 +467,46 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
BlockRole::ConstructTreeRoute,
|
||||
));
|
||||
|
||||
let mut updates = Vec::with_capacity(blocks.len());
|
||||
let mut pc_updates = Vec::with_capacity(blocks.len());
|
||||
let mut phi_updates = slots
|
||||
.iter()
|
||||
.map(|_| Vec::with_capacity(blocks.len()))
|
||||
.collect::<Vec<_>>();
|
||||
let mut value_update_incoming = value_slots
|
||||
.iter()
|
||||
.map(|_| Vec::with_capacity(blocks.len()))
|
||||
.collect::<Vec<_>>();
|
||||
for (case_index, original) in blocks.iter().enumerate() {
|
||||
let mut case = original.clone();
|
||||
let carrier = case.typed.as_mut().expect("checked above");
|
||||
let carrier = std::sync::Arc::make_mut(case.typed.as_mut().expect("checked above"));
|
||||
carrier.rename(&rename);
|
||||
let substitutions = value_slots
|
||||
// Most cross-case values are irrelevant to any one case. Building the full value-slot map
|
||||
// for every block made this bounded transform allocate O(cases * slots) cloned names and
|
||||
// types before it touched a single operand. Restrict the substitution map to actual uses in
|
||||
// this carrier; the deep typed substitution below remains the sole mutation primitive.
|
||||
let mut used_names = carrier
|
||||
.insts
|
||||
.iter()
|
||||
.filter(|slot| slot.owner != case_index)
|
||||
.map(|slot| {
|
||||
(
|
||||
slot.original.clone(),
|
||||
TypedValue {
|
||||
ty: slot.ty.clone(),
|
||||
value: LlValue::Local(slot.current.clone()),
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect::<HashMap<_, _>>();
|
||||
.filter(|inst| !inst.is_phi())
|
||||
.flat_map(|inst| inst.uses.iter().cloned())
|
||||
.collect::<HashSet<_>>();
|
||||
used_names.extend(terminator_value_uses(&carrier.terminator));
|
||||
let mut substitutions = HashMap::new();
|
||||
for name in used_names {
|
||||
let Some(slot) = value_slot_by_name.get(name.as_str()) else {
|
||||
continue;
|
||||
};
|
||||
if slot.owner == case_index {
|
||||
continue;
|
||||
}
|
||||
substitutions.insert(
|
||||
slot.original.clone(),
|
||||
TypedValue {
|
||||
ty: slot.ty.clone(),
|
||||
value: LlValue::Local(slot.current.clone()),
|
||||
},
|
||||
);
|
||||
}
|
||||
carrier.substitute_values(&substitutions);
|
||||
carrier.insts.retain(|inst| !inst.is_phi());
|
||||
let targets = &successors[case_index];
|
||||
@@ -564,7 +582,7 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
let update = match targets.as_slice() {
|
||||
[] => LlValue::Local(slot.current.clone()),
|
||||
[target] => edge_value(*target)?,
|
||||
_ => {
|
||||
_ if targets.contains(&slot.host) => {
|
||||
let result = format!("{PREFIX}caseslot.{case_index}.{slot_index}");
|
||||
join_phis.push((
|
||||
result.clone(),
|
||||
@@ -579,10 +597,11 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
));
|
||||
LlValue::Local(result)
|
||||
}
|
||||
_ => LlValue::Local(slot.current.clone()),
|
||||
};
|
||||
slot_updates.push(update);
|
||||
}
|
||||
let value_updates = value_slots
|
||||
let case_value_updates: Vec<_> = value_slots
|
||||
.iter()
|
||||
.map(|slot| {
|
||||
if slot.owner == case_index {
|
||||
@@ -598,34 +617,33 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
&join_phis,
|
||||
BlockRole::Normal,
|
||||
)?);
|
||||
updates.push(CaseUpdate {
|
||||
join,
|
||||
pc: pc_update,
|
||||
phi_slots: slot_updates,
|
||||
value_slots: value_updates,
|
||||
});
|
||||
pc_updates.push((pc_update, join.clone()));
|
||||
for (incoming, value) in phi_updates.iter_mut().zip(slot_updates) {
|
||||
incoming.push((value, join.clone()));
|
||||
}
|
||||
for (incoming, value) in value_update_incoming.iter_mut().zip(case_value_updates) {
|
||||
incoming.push((value, join.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
out.push(passthrough(INVALID, MERGE));
|
||||
let mut merge_phis = vec![(
|
||||
NEXT_PC.to_string(),
|
||||
LlType::Int(32),
|
||||
updates
|
||||
.iter()
|
||||
.map(|update| (update.pc.clone(), update.join.clone()))
|
||||
pc_updates
|
||||
.into_iter()
|
||||
.chain(std::iter::once((
|
||||
LlValue::Int(done_state),
|
||||
INVALID.to_string(),
|
||||
)))
|
||||
.collect(),
|
||||
)];
|
||||
for (slot_index, slot) in slots.iter().enumerate() {
|
||||
for (slot, incoming) in slots.iter().zip(phi_updates) {
|
||||
merge_phis.push((
|
||||
slot.next.clone(),
|
||||
slot.ty.clone(),
|
||||
updates
|
||||
.iter()
|
||||
.map(|update| (update.phi_slots[slot_index].clone(), update.join.clone()))
|
||||
incoming
|
||||
.into_iter()
|
||||
.chain(std::iter::once((
|
||||
LlValue::Local(slot.current.clone()),
|
||||
INVALID.to_string(),
|
||||
@@ -633,13 +651,12 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
.collect(),
|
||||
));
|
||||
}
|
||||
for (slot_index, slot) in value_slots.iter().enumerate() {
|
||||
for (slot, incoming) in value_slots.iter().zip(value_update_incoming) {
|
||||
merge_phis.push((
|
||||
slot.next.clone(),
|
||||
slot.ty.clone(),
|
||||
updates
|
||||
.iter()
|
||||
.map(|update| (update.value_slots[slot_index].clone(), update.join.clone()))
|
||||
incoming
|
||||
.into_iter()
|
||||
.chain(std::iter::once((
|
||||
LlValue::Local(slot.current.clone()),
|
||||
INVALID.to_string(),
|
||||
@@ -667,6 +684,32 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
plan.block_bound
|
||||
));
|
||||
}
|
||||
if crate::env_vars::why() {
|
||||
let instructions = out
|
||||
.iter()
|
||||
.filter_map(|block| block.typed.as_ref())
|
||||
.map(|block| block.insts.len())
|
||||
.sum::<usize>();
|
||||
let phis = out
|
||||
.iter()
|
||||
.filter_map(|block| block.typed.as_ref())
|
||||
.flat_map(|block| &block.insts)
|
||||
.filter(|inst| inst.is_phi())
|
||||
.count();
|
||||
let phi_incoming = out
|
||||
.iter()
|
||||
.filter_map(|block| block.typed.as_ref())
|
||||
.flat_map(|block| &block.insts)
|
||||
.filter_map(|inst| inst.phi_incoming.as_ref())
|
||||
.map(|(_, incoming)| incoming.len())
|
||||
.sum::<usize>();
|
||||
eprintln!(
|
||||
"WHY-CONSTRUCT-TREE materialized blocks={} instructions={instructions} phis={phis} phi-incoming={phi_incoming} source-phis={} cross-values={}",
|
||||
out.len(),
|
||||
slots.len(),
|
||||
value_slots.len()
|
||||
);
|
||||
}
|
||||
if super::super::structured_plan(&out).is_none() {
|
||||
let reason =
|
||||
super::super::structured_reject_reason(&out).unwrap_or_else(|| "unknown".to_string());
|
||||
|
||||
@@ -198,7 +198,8 @@ fn typed_blocks(fixture: &Fixture) -> Vec<BodyBlock> {
|
||||
BodyBlock {
|
||||
name: labels[index].clone(),
|
||||
role: BlockRole::Normal,
|
||||
typed: tir::lower_block_carrier(&labels[index], &lines, &HashMap::new()),
|
||||
typed: tir::lower_block_carrier(&labels[index], &lines, &HashMap::new())
|
||||
.map(Into::into),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
|
||||
@@ -12,7 +12,66 @@ fn next_selection_merge_suffix(blocks: &[BodyBlock]) -> usize {
|
||||
.map_or(0, |max| max + 1)
|
||||
}
|
||||
|
||||
fn loop_role_targets_with_passthroughs(
|
||||
/// Give every loop a private merge after an ownership transform introduces an external predecessor
|
||||
/// to the merge selected by the original loop forest.
|
||||
///
|
||||
/// Construct-tree routing can preserve the loop body exactly while making its old exit reachable
|
||||
/// from an enclosing sibling. The loop header then no longer dominates that exit, so it cannot remain
|
||||
/// the loop's declared merge. Reuse the existing phi-aware overlap split to funnel only in-loop exit
|
||||
/// edges through a fresh merge; outside edges and their phi values remain on the old exit.
|
||||
pub(in crate::native) fn privatize_nondominated_loop_merges(
|
||||
blocks: &mut Vec<BodyBlock>,
|
||||
loop_merges: &mut HashMap<String, LoopMergeInfo>,
|
||||
) -> bool {
|
||||
let mut counter = blocks.len();
|
||||
while blocks
|
||||
.iter()
|
||||
.any(|block| block.name == format!("{SPLIT_PREFIX}{counter}"))
|
||||
{
|
||||
counter += 1;
|
||||
}
|
||||
let mut changed = false;
|
||||
loop {
|
||||
let forest = analyze(blocks);
|
||||
let mut polluted = loop_merges
|
||||
.iter()
|
||||
.filter_map(|(header, info)| {
|
||||
let loop_info = forest.loop_for_header(header)?;
|
||||
(!forest.dominates(header, &info.merge)).then_some((
|
||||
loop_info.body.len(),
|
||||
header.clone(),
|
||||
info.merge.clone(),
|
||||
))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
polluted.sort();
|
||||
let Some((_, header, merge)) = polluted.into_iter().next() else {
|
||||
break;
|
||||
};
|
||||
while blocks
|
||||
.iter()
|
||||
.any(|block| block.name == format!("{SPLIT_PREFIX}{counter}"))
|
||||
{
|
||||
counter += 1;
|
||||
}
|
||||
let split = if block_has_phi(blocks, &merge) {
|
||||
split_phi_overlap(blocks, &forest, &header, &merge, &mut counter)
|
||||
} else {
|
||||
split_no_phi_overlap(blocks, &forest, &header, &merge, &mut counter)
|
||||
};
|
||||
let Some(private_merge) = split else {
|
||||
break;
|
||||
};
|
||||
let Some(info) = loop_merges.get_mut(&header) else {
|
||||
break;
|
||||
};
|
||||
info.merge = private_merge;
|
||||
changed = true;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
pub(in crate::native) fn loop_role_targets_with_passthroughs(
|
||||
blocks: &[BodyBlock],
|
||||
loop_merges: &HashMap<String, LoopMergeInfo>,
|
||||
) -> HashSet<String> {
|
||||
@@ -119,7 +178,15 @@ pub(in crate::native) fn forest_loop_merges(
|
||||
multi_exit_clone: bool,
|
||||
) -> (Vec<BodyBlock>, HashMap<String, LoopMergeInfo>) {
|
||||
let forest = analyze(blocks);
|
||||
let plans = forest.structured_plan();
|
||||
// A bare unreachable target terminates the invocation in-place; unlike a live continuation it
|
||||
// does not need to be selected as the loop's unique merge. Keep it in the CFG/construct, but
|
||||
// exclude it from merge-candidate cardinality after proving the exact terminal shape.
|
||||
let terminal_exits = blocks
|
||||
.iter()
|
||||
.filter(|block| block_ends_in_unreachable(blocks, &block.name))
|
||||
.map(|block| block.name.clone())
|
||||
.collect::<HashSet<_>>();
|
||||
let plans = forest.structured_plan_ignoring_exits(&terminal_exits);
|
||||
let mut out_blocks = blocks.to_vec();
|
||||
let mut merges = HashMap::new();
|
||||
let mut split_counter = 0usize;
|
||||
@@ -152,6 +219,15 @@ pub(in crate::native) fn forest_loop_merges(
|
||||
let (Some(continue_target), Some(merge_block)) =
|
||||
(plan.continue_block.clone(), plan.merge_block.clone())
|
||||
else {
|
||||
if crate::env_vars::flm_why() {
|
||||
eprintln!(
|
||||
"[flm-why] header={} restructure={:?} continue={:?} merge={:?} uncovered=missing-role",
|
||||
plan.header,
|
||||
plan.restructure,
|
||||
plan.continue_block,
|
||||
plan.merge_block,
|
||||
);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -323,6 +399,12 @@ pub(in crate::native) fn forest_loop_merges(
|
||||
// Only the lone merge==continue overlap is handled here; anything else is left for the
|
||||
// existing path (and the later increments of the consumer).
|
||||
if plan.restructure.as_slice() != [Restructure::MergeIsEnclosingContinue] {
|
||||
if crate::env_vars::flm_why() {
|
||||
eprintln!(
|
||||
"[flm-why] header={} restructure={:?} continue={} merge={} uncovered=unsupported-combination",
|
||||
plan.header, plan.restructure, continue_target, merge_block,
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let split = if block_has_phi(&out_blocks, &merge_block) {
|
||||
@@ -382,9 +464,14 @@ pub(in crate::native) fn forest_loop_merges(
|
||||
.map(|(h, i)| (h.clone(), i.merge.clone(), i.continue_target.clone()))
|
||||
.collect();
|
||||
header_infos.sort();
|
||||
let final_forest = analyze(&out_blocks);
|
||||
for (h, m, c) in header_infos {
|
||||
split_loop_header_selection(&mut out_blocks, &h, &m, &c, &mut split_counter);
|
||||
split_loop_header_switch(&mut out_blocks, &h, &m, &c, &mut split_counter);
|
||||
let Some(loop_info) = final_forest.loop_for_header(&h) else {
|
||||
continue;
|
||||
};
|
||||
let loop_body = loop_info.body.iter().cloned().collect::<HashSet<_>>();
|
||||
split_loop_header_selection(&mut out_blocks, &h, &m, &c, &loop_body, &mut split_counter);
|
||||
split_loop_header_switch(&mut out_blocks, &h, &m, &c, &loop_body, &mut split_counter);
|
||||
}
|
||||
|
||||
(out_blocks, merges)
|
||||
@@ -448,13 +535,14 @@ pub(in crate::native) fn synth_noexit_self_latch(
|
||||
.map(|mut h| {
|
||||
h.rewrite_phi_predecessor(header, &continue_target);
|
||||
h
|
||||
});
|
||||
})
|
||||
.map(Into::into);
|
||||
blocks.insert(
|
||||
header_idx + 1,
|
||||
BodyBlock {
|
||||
name: body,
|
||||
role: BlockRole::Normal,
|
||||
typed: body_typed,
|
||||
typed: body_typed.map(Into::into),
|
||||
},
|
||||
);
|
||||
let cont_typed = crate::native::tir::lower_block_carrier(
|
||||
@@ -467,7 +555,7 @@ pub(in crate::native) fn synth_noexit_self_latch(
|
||||
BodyBlock {
|
||||
name: continue_target.clone(),
|
||||
role: BlockRole::Normal,
|
||||
typed: cont_typed,
|
||||
typed: cont_typed.map(Into::into),
|
||||
},
|
||||
);
|
||||
// Keep this after the reachable source blocks. `structured_order` appends unreachable blocks, so
|
||||
@@ -480,7 +568,7 @@ pub(in crate::native) fn synth_noexit_self_latch(
|
||||
blocks.push(BodyBlock {
|
||||
name: merge.clone(),
|
||||
role: BlockRole::Normal,
|
||||
typed: merge_typed,
|
||||
typed: merge_typed.map(Into::into),
|
||||
});
|
||||
|
||||
Some((merge, continue_target))
|
||||
@@ -620,6 +708,14 @@ fn unique_selection_merges_with_loop_exit_and_forced_inner(
|
||||
};
|
||||
if loop_exit_selection {
|
||||
refine_loop_exit_selection_merges(blocks, &forest, loop_merges, &mut sel);
|
||||
refine_loop_entry_terminal_selection_merges(blocks, &forest, loop_merges, &mut sel);
|
||||
refine_nested_terminal_selection_merges(
|
||||
blocks,
|
||||
&forest,
|
||||
loop_merges,
|
||||
forced_terminal_merges,
|
||||
&mut sel,
|
||||
);
|
||||
}
|
||||
let loop_headers: HashSet<&str> = forest.loops.iter().map(|l| l.header.as_str()).collect();
|
||||
let loop_roles = loop_role_targets_with_passthroughs(blocks, loop_merges);
|
||||
@@ -687,7 +783,9 @@ fn unique_selection_merges_with_loop_exit_and_forced_inner(
|
||||
&& !break_continue_blocks.contains(&b.name)
|
||||
})
|
||||
.collect();
|
||||
headers.sort_by_key(|b| std::cmp::Reverse(depth(&b.name)));
|
||||
// Dominator depth can be proportional to the function size in generated ladder CFGs. Cache
|
||||
// each header's depth once instead of walking the idom chain again for every sort comparison.
|
||||
headers.sort_by_cached_key(|b| std::cmp::Reverse(depth(&b.name)));
|
||||
|
||||
// Non-construct retries need dominance over the CURRENT blocks, including pass-through merges
|
||||
// synthesized for already-processed (inner) headers. Construct-tree ownership cannot afford to
|
||||
@@ -701,6 +799,7 @@ fn unique_selection_merges_with_loop_exit_and_forced_inner(
|
||||
origins: Vec<String>,
|
||||
}
|
||||
let mut ct_owned_preds: HashMap<(String, String), Vec<CtOwnedPred>> = HashMap::new();
|
||||
let mut construct_tree_bare_loop_role_headers = HashSet::new();
|
||||
let mut stopped_for_growth = false;
|
||||
for b in headers.iter().copied() {
|
||||
if let Some(merge) = forced_terminal_merges.get(&b.name).cloned() {
|
||||
@@ -720,6 +819,7 @@ fn unique_selection_merges_with_loop_exit_and_forced_inner(
|
||||
if let Some((true_target, false_target)) = conditional_branch_targets(b) {
|
||||
if bare_loop_exit_branch(&forest, loop_merges, &b.name, &true_target, &false_target)
|
||||
{
|
||||
construct_tree_bare_loop_role_headers.insert(b.name.clone());
|
||||
continue;
|
||||
}
|
||||
if let Some(exit_target) = enclosing_selection_region_exit_target(
|
||||
@@ -838,7 +938,15 @@ fn unique_selection_merges_with_loop_exit_and_forced_inner(
|
||||
HashSet::new()
|
||||
};
|
||||
let synth = if natural_has_phi {
|
||||
if construct_tree_owned {
|
||||
if construct_tree_owned && !explicit_no_phi_preds.is_empty() {
|
||||
synth_unique_selection_merge_phi_explicit(
|
||||
&mut out,
|
||||
&explicit_no_phi_preds,
|
||||
&natural,
|
||||
&routes_into_natural,
|
||||
&mut counter,
|
||||
)
|
||||
} else if construct_tree_owned {
|
||||
synth_unique_selection_merge_phi(
|
||||
&mut out,
|
||||
&forest,
|
||||
@@ -882,7 +990,12 @@ fn unique_selection_merges_with_loop_exit_and_forced_inner(
|
||||
if selection_synth_growth_exceeds_ladder_cap(blocks.len(), out.len()) {
|
||||
stopped_for_growth = true;
|
||||
} else if !construct_tree_owned {
|
||||
cur_forest = analyze(&out);
|
||||
// A unique-selection merge only splits forward edges with an acyclic
|
||||
// pass-through. Natural loops and their nesting are unchanged; recomputing
|
||||
// every loop body after each of hundreds of nested selection splits made
|
||||
// large generated CFGs revisit the whole graph quadratically. Refresh only
|
||||
// dominance for the newly inserted block and retain the proven loop forest.
|
||||
cur_forest = analyze_reusing_natural_loops(&out, &forest.loops);
|
||||
}
|
||||
if construct_tree_owned && !propagated_origins.is_empty() {
|
||||
for target in &headers {
|
||||
@@ -908,7 +1021,15 @@ fn unique_selection_merges_with_loop_exit_and_forced_inner(
|
||||
}
|
||||
s
|
||||
}
|
||||
None => continue,
|
||||
None => {
|
||||
if crate::env_vars::spi_why() {
|
||||
eprintln!(
|
||||
"[spi-why] selection-synth-decline header={} natural={} phi={} collides={}",
|
||||
b.name, natural, natural_has_phi, collides,
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
natural
|
||||
@@ -927,33 +1048,134 @@ fn unique_selection_merges_with_loop_exit_and_forced_inner(
|
||||
}
|
||||
}
|
||||
if stopped_for_growth {
|
||||
if crate::env_vars::spi_why() {
|
||||
eprintln!(
|
||||
"[spi-why] selection-growth-stop source={} candidate={} last_header={}",
|
||||
blocks.len(),
|
||||
out.len(),
|
||||
b.name,
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if construct_tree_owned && !stopped_for_growth {
|
||||
repair_construct_tree_nondominated_selection_merges(
|
||||
let mut repaired_final_escape = false;
|
||||
if !stopped_for_growth {
|
||||
if construct_tree_owned {
|
||||
while privatize_direct_arm_terminal_returns(&mut out, &header_merges, &mut counter) {}
|
||||
let completed_terminal_convergence = complete_construct_tree_terminal_convergences(
|
||||
&out,
|
||||
loop_merges,
|
||||
forced_terminal_merges,
|
||||
&sel,
|
||||
&mut header_merges,
|
||||
);
|
||||
if completed_terminal_convergence {
|
||||
while privatize_direct_arm_terminal_returns(&mut out, &header_merges, &mut counter)
|
||||
{
|
||||
}
|
||||
}
|
||||
complete_terminal_construct_tree_merges(
|
||||
&mut out,
|
||||
loop_merges,
|
||||
&sel,
|
||||
&mut header_merges,
|
||||
&mut counter,
|
||||
);
|
||||
repair_construct_tree_nondominated_selection_merges(
|
||||
&mut out,
|
||||
loop_merges,
|
||||
&mut header_merges,
|
||||
&mut counter,
|
||||
);
|
||||
}
|
||||
// A nested selection can escape into a sibling region after earlier unique-merge splits have
|
||||
// established the enclosing construct's final private merge. This is a general structured-CFG
|
||||
// invariant, not construct-tree-specific: give the nested header a private pass-through merge
|
||||
// so its escaping edge first leaves through its own declared merge.
|
||||
if crate::env_vars::spi_why() {
|
||||
eprintln!("[spi-why] repair-phase=general");
|
||||
}
|
||||
repaired_final_escape = repair_enclosing_selection_region_escapes(
|
||||
&mut out,
|
||||
loop_merges,
|
||||
&mut header_merges,
|
||||
&mut counter,
|
||||
);
|
||||
repair_construct_tree_enclosing_selection_region_escapes(
|
||||
&mut out,
|
||||
loop_merges,
|
||||
&mut header_merges,
|
||||
&mut counter,
|
||||
);
|
||||
repair_construct_tree_passthrough_selection_merges(&out, loop_merges, &mut header_merges);
|
||||
if construct_tree_owned {
|
||||
repair_construct_tree_bypassed_passthrough_merges(
|
||||
&mut out,
|
||||
&mut header_merges,
|
||||
&mut counter,
|
||||
);
|
||||
drop_pure_enclosing_selection_routes(&out, &mut header_merges);
|
||||
repair_construct_tree_passthrough_selection_merges(
|
||||
&out,
|
||||
loop_merges,
|
||||
&mut header_merges,
|
||||
);
|
||||
if crate::env_vars::spi_why() {
|
||||
eprintln!("[spi-why] repair-phase=post-passthrough");
|
||||
}
|
||||
repaired_final_escape |= repair_enclosing_selection_region_escapes(
|
||||
&mut out,
|
||||
loop_merges,
|
||||
&mut header_merges,
|
||||
&mut counter,
|
||||
);
|
||||
if crate::env_vars::spi_why() {
|
||||
eprintln!("[spi-why] repair-phase=terminal-live");
|
||||
}
|
||||
repaired_final_escape |= repair_terminal_selection_live_escapes(
|
||||
&mut out,
|
||||
loop_merges,
|
||||
&mut header_merges,
|
||||
&mut counter,
|
||||
);
|
||||
repair_construct_tree_bypassed_passthrough_merges(
|
||||
&mut out,
|
||||
&mut header_merges,
|
||||
&mut counter,
|
||||
);
|
||||
if crate::env_vars::spi_why() {
|
||||
eprintln!("[spi-why] repair-phase=final");
|
||||
}
|
||||
repaired_final_escape |= repair_enclosing_selection_region_escapes(
|
||||
&mut out,
|
||||
loop_merges,
|
||||
&mut header_merges,
|
||||
&mut counter,
|
||||
);
|
||||
repaired_final_escape |=
|
||||
finalize_direct_terminal_guard_merges(&mut out, &mut header_merges, &mut counter);
|
||||
while privatize_direct_arm_terminal_returns(&mut out, &header_merges, &mut counter) {
|
||||
repaired_final_escape = true;
|
||||
}
|
||||
repaired_final_escape |=
|
||||
finalize_fully_terminal_switches(&mut out, &mut header_merges, &mut counter);
|
||||
repaired_final_escape |=
|
||||
compose_terminal_parent_nested_merges(&mut out, &mut header_merges, &mut counter);
|
||||
repaired_final_escape |= complete_construct_tree_missing_selection_merges(
|
||||
&mut out,
|
||||
loop_merges,
|
||||
&mut header_merges,
|
||||
&mut counter,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Re-key from final terminators when a later transform can rewrite an already-recorded header. This
|
||||
// is intentionally after the full innermost-first synthesis pass: an enclosing unique-merge split
|
||||
// can redirect a nested header's arm after that nested header was assigned, and the emitter keys
|
||||
// conditional merges by the final target pair rather than the header name.
|
||||
let rekey_all =
|
||||
loop_exit_selection || !forced_terminal_merges.is_empty() || construct_tree_owned;
|
||||
let rekey_all = loop_exit_selection
|
||||
|| !forced_terminal_merges.is_empty()
|
||||
|| construct_tree_owned
|
||||
|| repaired_final_escape;
|
||||
if rekey_all || !break_continue_blocks.is_empty() {
|
||||
let final_forest = analyze(&out);
|
||||
let mut bare_loop_role_headers = Vec::new();
|
||||
for block in &out {
|
||||
if !rekey_all && !break_continue_blocks.contains(&block.name) {
|
||||
continue;
|
||||
@@ -961,12 +1183,53 @@ fn unique_selection_merges_with_loop_exit_and_forced_inner(
|
||||
let Some(merge) = header_merges.get(&block.name).cloned() else {
|
||||
continue;
|
||||
};
|
||||
if crate::env_vars::spi_why() {
|
||||
let merge_block = out.iter().find(|candidate| candidate.name == merge);
|
||||
eprintln!(
|
||||
"[spi-why] final-selection header={} merge={} role={:?} successors={:?}",
|
||||
block.name,
|
||||
merge,
|
||||
merge_block.map(|candidate| candidate.role),
|
||||
merge_block.map(block_successors),
|
||||
);
|
||||
}
|
||||
if is_switch_block(block) {
|
||||
switch.insert(block.name.clone(), merge);
|
||||
} else if let Some((true_target, false_target)) = conditional_branch_targets(block) {
|
||||
let final_bare_loop_role = construct_tree_owned
|
||||
&& (construct_tree_bare_loop_role_headers.contains(&block.name)
|
||||
|| bare_natural_loop_exit_branch(
|
||||
&final_forest,
|
||||
&block.name,
|
||||
&true_target,
|
||||
&false_target,
|
||||
)
|
||||
|| bare_loop_exit_branch_with_passthroughs(
|
||||
&out,
|
||||
&final_forest,
|
||||
loop_merges,
|
||||
&block.name,
|
||||
&true_target,
|
||||
&false_target,
|
||||
));
|
||||
if final_bare_loop_role {
|
||||
// Late selection synthesis may wrap a loop merge/continue arm in a
|
||||
// single-successor gateway after this header was correctly classified as a
|
||||
// bare bottom-test branch. Re-keying it as a selection makes that gateway the
|
||||
// declared merge even though it is reached only from the latch, so it cannot be
|
||||
// dominated by the header. Preserve the loop-role branch as bare in the final
|
||||
// maps as well as during the initial classification.
|
||||
branch.remove(&(true_target.clone(), false_target.clone()));
|
||||
branch.remove(&(false_target.clone(), true_target.clone()));
|
||||
bare_loop_role_headers.push(block.name.clone());
|
||||
continue;
|
||||
}
|
||||
branch.insert((true_target, false_target), merge);
|
||||
}
|
||||
}
|
||||
for header in bare_loop_role_headers {
|
||||
header_merges.remove(&header);
|
||||
}
|
||||
}
|
||||
(out, branch, header_merges, switch)
|
||||
}
|
||||
@@ -1140,6 +1403,246 @@ pub(in crate::native) fn repair_construct_tree_passthrough_selection_merges(
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace a bypassed private pass-through with a phi-aware merge over every header-owned incoming
|
||||
/// to its shared successor.
|
||||
///
|
||||
/// `H -> { old-private -> J, body -> J }` is not structured when outside paths also enter `J`: using
|
||||
/// `old-private` as H's merge lets `body` bypass it, while promoting H directly to `J` would give the
|
||||
/// construct an external entry. Split the H-owned incoming edges to `J` through one fresh private
|
||||
/// merge. [`synth_unique_selection_merge_phi`] preserves `J`'s exact incoming values when it carries
|
||||
/// phis; the no-phi variant performs the same ownership split without data surgery.
|
||||
pub(in crate::native) fn repair_construct_tree_bypassed_passthrough_merges(
|
||||
blocks: &mut Vec<BodyBlock>,
|
||||
header_merges: &mut HashMap<String, String>,
|
||||
counter: &mut usize,
|
||||
) -> bool {
|
||||
let mut changed = false;
|
||||
loop {
|
||||
let forest = analyze(blocks);
|
||||
let by_name = blocks
|
||||
.iter()
|
||||
.map(|block| (block.name.as_str(), block))
|
||||
.collect::<HashMap<_, _>>();
|
||||
let mut assignments = header_merges
|
||||
.iter()
|
||||
.map(|(header, merge)| (header.clone(), merge.clone()))
|
||||
.collect::<Vec<_>>();
|
||||
assignments.sort();
|
||||
let mut repair = None;
|
||||
for (header, merge) in assignments {
|
||||
let Some(merge_block) = by_name.get(merge.as_str()) else {
|
||||
continue;
|
||||
};
|
||||
if merge_block.role != BlockRole::LMerge {
|
||||
continue;
|
||||
}
|
||||
let mut chain = HashSet::new();
|
||||
let mut current = merge.clone();
|
||||
let successor = loop {
|
||||
if !chain.insert(current.clone()) {
|
||||
break None;
|
||||
}
|
||||
let Some(block) = by_name.get(current.as_str()) else {
|
||||
break None;
|
||||
};
|
||||
if block.role != BlockRole::LMerge {
|
||||
break Some(current);
|
||||
}
|
||||
let successors = block_successors(block);
|
||||
let [next] = successors.as_slice() else {
|
||||
break None;
|
||||
};
|
||||
current = next.clone();
|
||||
};
|
||||
let Some(successor) = successor else {
|
||||
continue;
|
||||
};
|
||||
let bypass = blocks.iter().any(|candidate| {
|
||||
!chain.contains(&candidate.name)
|
||||
&& forest.dominates(&header, &candidate.name)
|
||||
&& block_successors(candidate)
|
||||
.iter()
|
||||
.any(|target| target == &successor)
|
||||
});
|
||||
if bypass {
|
||||
repair = Some((header, successor));
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some((header, successor)) = repair else {
|
||||
break;
|
||||
};
|
||||
let private = if block_has_phi(blocks, &successor) {
|
||||
synth_unique_selection_merge_phi(blocks, &forest, &header, &successor, counter)
|
||||
} else {
|
||||
synth_unique_selection_merge(blocks, &forest, &header, &successor, counter)
|
||||
};
|
||||
let Some(private) = private else {
|
||||
break;
|
||||
};
|
||||
if crate::env_vars::spi_why() {
|
||||
eprintln!(
|
||||
"[spi-why] bypass-refunnel header={} successor={} merge={}",
|
||||
header, successor, private,
|
||||
);
|
||||
}
|
||||
header_merges.insert(header, private);
|
||||
changed = true;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Give every remaining ordinary conditional/switch header a unique merge after late ownership
|
||||
/// repair.
|
||||
///
|
||||
/// Earlier passes derive selection merges from the source CFG, then split collisions and repair
|
||||
/// nested escapes. Those edge rewrites can make a previously-unowned child reconverge at a private
|
||||
/// merge now claimed by its parent. The child is absent from `header_merges`, so the emitter would
|
||||
/// otherwise output a bare `OpBranchConditional`. Recompute post-dominance on the final graph and
|
||||
/// handle only those missing headers. Loop headers remain owned exclusively by `OpLoopMerge`.
|
||||
///
|
||||
/// The source forest remains valid for the predecessor refunnel performed here: each synthesis only
|
||||
/// redirects header-dominated edges into the same natural merge through a fresh pass-through. The
|
||||
/// work is one linear scan plus at most one local predecessor rewrite per missing header; it does not
|
||||
/// iterate whole-CFG analysis to a fixed point.
|
||||
pub(in crate::native) fn complete_construct_tree_missing_selection_merges(
|
||||
blocks: &mut Vec<BodyBlock>,
|
||||
loop_merges: &HashMap<String, LoopMergeInfo>,
|
||||
header_merges: &mut HashMap<String, String>,
|
||||
counter: &mut usize,
|
||||
) -> bool {
|
||||
let source_forest = analyze(blocks);
|
||||
let source_natural_merges = selection_merges(blocks, &source_forest);
|
||||
let source_loop_headers = source_forest
|
||||
.loops
|
||||
.iter()
|
||||
.map(|loop_info| loop_info.header.as_str())
|
||||
.collect::<HashSet<_>>();
|
||||
// A missing child's direct arm can itself be a shared phi block reached from a sibling
|
||||
// selection (`H -> shared`, `sibling -> shared`). Refunneling only the later natural-merge
|
||||
// predecessors cannot make H dominate that arm. Privatize the shared direct arm first using the
|
||||
// established merge-preserving region clone; exclude a direct natural-merge arm, which is the
|
||||
// ordinary if-without-else shape and needs no clone.
|
||||
let mut shared_arms = Vec::new();
|
||||
for block in blocks.iter() {
|
||||
let Some(natural) = source_natural_merges.get(&block.name) else {
|
||||
continue;
|
||||
};
|
||||
if source_loop_headers.contains(block.name.as_str())
|
||||
|| header_merges.contains_key(&block.name)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if conditional_branch_targets(block).is_some_and(|(true_target, false_target)| {
|
||||
bare_loop_exit_branch_with_passthroughs(
|
||||
blocks,
|
||||
&source_forest,
|
||||
loop_merges,
|
||||
&block.name,
|
||||
&true_target,
|
||||
&false_target,
|
||||
)
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
for arm in block_successors(block) {
|
||||
if arm != *natural && !source_forest.dominates(&block.name, &arm) {
|
||||
shared_arms.push((block.name.clone(), arm));
|
||||
}
|
||||
}
|
||||
}
|
||||
shared_arms.sort();
|
||||
shared_arms.dedup();
|
||||
|
||||
let mut changed = false;
|
||||
for (header, arm) in shared_arms {
|
||||
let Some(cloned) = super::super::clone_crossarm::privatize_dominated_region(
|
||||
blocks, &header, &arm, counter,
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
if crate::env_vars::spi_why() {
|
||||
eprintln!(
|
||||
"[spi-why] missing-selection-private-arm header={} arm={}",
|
||||
header, arm,
|
||||
);
|
||||
}
|
||||
*blocks = cloned;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
let forest = analyze(blocks);
|
||||
let natural_merges = selection_merges(blocks, &forest);
|
||||
let loop_headers = forest
|
||||
.loops
|
||||
.iter()
|
||||
.map(|loop_info| loop_info.header.as_str())
|
||||
.collect::<HashSet<_>>();
|
||||
let loop_roles = loop_role_targets_with_passthroughs(blocks, loop_merges);
|
||||
let mut claims = header_merges.values().cloned().collect::<HashSet<_>>();
|
||||
let depth = |name: &str| {
|
||||
let mut depth = 0usize;
|
||||
let mut current = name;
|
||||
while let Some(parent) = forest.idom(current) {
|
||||
depth += 1;
|
||||
current = parent;
|
||||
}
|
||||
depth
|
||||
};
|
||||
let mut missing = natural_merges
|
||||
.into_iter()
|
||||
.filter(|(header, _)| {
|
||||
!loop_headers.contains(header.as_str())
|
||||
&& !header_merges.contains_key(header)
|
||||
&& !blocks
|
||||
.iter()
|
||||
.find(|block| block.name == *header)
|
||||
.and_then(conditional_branch_targets)
|
||||
.is_some_and(|(true_target, false_target)| {
|
||||
bare_loop_exit_branch_with_passthroughs(
|
||||
blocks,
|
||||
&forest,
|
||||
loop_merges,
|
||||
header,
|
||||
&true_target,
|
||||
&false_target,
|
||||
)
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
missing.sort_by(|left, right| {
|
||||
depth(&right.0)
|
||||
.cmp(&depth(&left.0))
|
||||
.then_with(|| left.0.cmp(&right.0))
|
||||
});
|
||||
|
||||
for (header, natural) in missing {
|
||||
let merge = if forest.dominates(&header, &natural)
|
||||
&& !claims.contains(&natural)
|
||||
&& !loop_roles.contains(&natural)
|
||||
{
|
||||
Some(natural.clone())
|
||||
} else if block_has_phi(blocks, &natural) {
|
||||
synth_unique_selection_merge_phi(blocks, &forest, &header, &natural, counter)
|
||||
} else {
|
||||
synth_unique_selection_merge(blocks, &forest, &header, &natural, counter)
|
||||
};
|
||||
let Some(merge) = merge else {
|
||||
continue;
|
||||
};
|
||||
if crate::env_vars::spi_why() {
|
||||
eprintln!(
|
||||
"[spi-why] missing-selection-complete header={} natural={} merge={}",
|
||||
header, natural, merge,
|
||||
);
|
||||
}
|
||||
claims.insert(merge.clone());
|
||||
header_merges.insert(header, merge);
|
||||
changed = true;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn synth_unique_selection_merge_no_phi_explicit(
|
||||
blocks: &mut Vec<BodyBlock>,
|
||||
preds: &[String],
|
||||
@@ -1167,7 +1670,7 @@ fn synth_unique_selection_merge_no_phi_explicit(
|
||||
*counter += 1;
|
||||
for (pred, old_target) in &redirect {
|
||||
if let Some(block) = blocks.iter_mut().find(|block| &block.name == pred) {
|
||||
if let Some(typed) = &mut block.typed {
|
||||
if let Some(typed) = block.typed_mut() {
|
||||
typed.redirect_successor(old_target, &new_name);
|
||||
}
|
||||
}
|
||||
@@ -1199,7 +1702,8 @@ mod tests {
|
||||
name,
|
||||
&["ret void".to_string()],
|
||||
&HashMap::new(),
|
||||
),
|
||||
)
|
||||
.map(Into::into),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -74,7 +74,7 @@ pub(in crate::native) fn split_multi_exit_critical_edges(
|
||||
|
||||
let source_block = blocks.iter_mut().find(|b| b.name == source)?;
|
||||
// Redirect the terminator on the carrier (typed dual of the former string redirect).
|
||||
if let Some(t) = &mut source_block.typed {
|
||||
if let Some(t) = source_block.typed_mut() {
|
||||
for (index, edge) in &edges {
|
||||
t.redirect_successor(&exits[*index], edge);
|
||||
}
|
||||
@@ -82,7 +82,7 @@ pub(in crate::native) fn split_multi_exit_critical_edges(
|
||||
|
||||
for (index, edge) in &edges {
|
||||
let exit = blocks.iter_mut().find(|b| b.name == exits[*index])?;
|
||||
if let Some(t) = &mut exit.typed {
|
||||
if let Some(t) = exit.typed_mut() {
|
||||
t.rewrite_phi_predecessor(&source, edge);
|
||||
}
|
||||
let edge_lines = vec![format!("br label {}", exits[*index])];
|
||||
@@ -91,7 +91,8 @@ pub(in crate::native) fn split_multi_exit_critical_edges(
|
||||
edge,
|
||||
&edge_lines,
|
||||
&std::collections::HashMap::new(),
|
||||
),
|
||||
)
|
||||
.map(Into::into),
|
||||
name: edge.clone(),
|
||||
role: role_for_name(edge),
|
||||
});
|
||||
@@ -160,7 +161,7 @@ pub(in crate::native) fn synth_multi_exit_merge(
|
||||
// Redirect every in-loop exit edge directly to the merge.
|
||||
for b in blocks.iter_mut() {
|
||||
if let Some((_, idx)) = preds.iter().find(|(n, _)| n == &b.name) {
|
||||
if let Some(t) = &mut b.typed {
|
||||
if let Some(t) = b.typed_mut() {
|
||||
t.redirect_successor(&exits[*idx], &merge);
|
||||
}
|
||||
}
|
||||
@@ -251,7 +252,7 @@ pub(in crate::native) fn synth_multi_exit_merge(
|
||||
typed_value_phis.push((merged, cty, merged_typed));
|
||||
}
|
||||
}
|
||||
if let Some(t) = &mut blocks[exit_idx].typed {
|
||||
if let Some(t) = blocks[exit_idx].typed_mut() {
|
||||
for (dst, kept_plus) in &exit_typed_merges {
|
||||
t.set_phi_incomings(dst, kept_plus);
|
||||
}
|
||||
@@ -283,7 +284,7 @@ pub(in crate::native) fn synth_multi_exit_merge(
|
||||
let merge_block = BodyBlock {
|
||||
name: merge.clone(),
|
||||
role: role_for_name(&merge),
|
||||
typed: Some(blk),
|
||||
typed: Some(blk.into()),
|
||||
};
|
||||
// Place it just before the first exit target so it sits in a natural position.
|
||||
let insert_at = blocks
|
||||
@@ -380,7 +381,7 @@ pub(in crate::native) fn synth_multi_latch_continue(
|
||||
typed_value_phis.push((merged, cty, merged_typed));
|
||||
}
|
||||
}
|
||||
if let Some(t) = &mut blocks[hidx].typed {
|
||||
if let Some(t) = blocks[hidx].typed_mut() {
|
||||
for (dst, kept_plus) in &header_typed_merges {
|
||||
t.set_phi_incomings(dst, kept_plus);
|
||||
}
|
||||
@@ -389,7 +390,7 @@ pub(in crate::native) fn synth_multi_latch_continue(
|
||||
// Redirect each latch's header edge to the new single latch `L`.
|
||||
for l in &latches {
|
||||
if let Some(b) = blocks.iter_mut().find(|b| &b.name == l) {
|
||||
if let Some(t) = &mut b.typed {
|
||||
if let Some(t) = b.typed_mut() {
|
||||
t.redirect_successor(header, &new_latch);
|
||||
}
|
||||
}
|
||||
@@ -413,7 +414,7 @@ pub(in crate::native) fn synth_multi_latch_continue(
|
||||
BodyBlock {
|
||||
name: new_latch.clone(),
|
||||
role: role_for_name(&new_latch),
|
||||
typed: Some(blk),
|
||||
typed: Some(blk.into()),
|
||||
}
|
||||
};
|
||||
blocks.insert(insert_at, latch_block);
|
||||
|
||||
@@ -69,7 +69,7 @@ fn carrier_with_phis(
|
||||
Ok(BodyBlock {
|
||||
name: name.to_string(),
|
||||
role: BlockRole::Normal,
|
||||
typed: Some(carrier),
|
||||
typed: Some(carrier.into()),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -379,8 +379,7 @@ fn regional_candidate(witness: Witness) -> Result<Vec<BodyBlock>, String> {
|
||||
&mut synthetic,
|
||||
);
|
||||
blocks[outer]
|
||||
.typed
|
||||
.as_mut()
|
||||
.typed_mut()
|
||||
.expect("carrier")
|
||||
.redirect_successor(target_name, &first);
|
||||
outer_incoming.push((LlValue::Int(state), synthetic.last().unwrap().name.clone()));
|
||||
@@ -393,8 +392,7 @@ fn regional_candidate(witness: Witness) -> Result<Vec<BodyBlock>, String> {
|
||||
synthetic
|
||||
.last_mut()
|
||||
.unwrap()
|
||||
.typed
|
||||
.as_mut()
|
||||
.typed_mut()
|
||||
.expect("carrier")
|
||||
.set_terminator_line(&format!(
|
||||
"switch i32 {OUTER_PC}, label {OUTER_PASS} [ i32 0, label {} ]",
|
||||
@@ -423,8 +421,7 @@ fn regional_candidate(witness: Witness) -> Result<Vec<BodyBlock>, String> {
|
||||
&mut synthetic,
|
||||
);
|
||||
blocks[header]
|
||||
.typed
|
||||
.as_mut()
|
||||
.typed_mut()
|
||||
.expect("carrier")
|
||||
.redirect_successor(target_name, &first);
|
||||
inner_incoming.push((LlValue::Int(state), synthetic.last().unwrap().name.clone()));
|
||||
@@ -499,8 +496,7 @@ fn regional_candidate(witness: Witness) -> Result<Vec<BodyBlock>, String> {
|
||||
synthetic
|
||||
.last_mut()
|
||||
.unwrap()
|
||||
.typed
|
||||
.as_mut()
|
||||
.typed_mut()
|
||||
.expect("carrier")
|
||||
.set_terminator_line(&format!(
|
||||
"switch i32 {COMMON_PC}, label {} [ i32 0, label {} ]",
|
||||
@@ -511,7 +507,7 @@ fn regional_candidate(witness: Witness) -> Result<Vec<BodyBlock>, String> {
|
||||
.iter()
|
||||
.map(|(source, _, carried)| (source.clone(), carried.clone()))
|
||||
.collect::<HashMap<_, _>>();
|
||||
blocks[index].typed.as_mut().expect("carrier").rename(&map);
|
||||
blocks[index].typed_mut().expect("carrier").rename(&map);
|
||||
}
|
||||
|
||||
// Funnel every exact region exit through one private final gateway. Natural-merge phi payloads
|
||||
@@ -550,8 +546,7 @@ fn regional_candidate(witness: Witness) -> Result<Vec<BodyBlock>, String> {
|
||||
for (edge, (source, _)) in exit_edges.iter().copied().enumerate() {
|
||||
let tail = format!("{PREFIX}final.route.{edge}");
|
||||
blocks[source]
|
||||
.typed
|
||||
.as_mut()
|
||||
.typed_mut()
|
||||
.expect("carrier")
|
||||
.redirect_successor(&natural_name, &tail);
|
||||
synthetic.push(passthrough(&tail, FINAL));
|
||||
@@ -592,8 +587,7 @@ fn regional_candidate(witness: Witness) -> Result<Vec<BodyBlock>, String> {
|
||||
.collect::<Vec<_>>();
|
||||
kept.push((LlValue::Local(payload), FINAL.to_string()));
|
||||
blocks[natural]
|
||||
.typed
|
||||
.as_mut()
|
||||
.typed_mut()
|
||||
.expect("carrier")
|
||||
.set_phi_incomings(result, &kept);
|
||||
}
|
||||
@@ -702,7 +696,7 @@ mod tests {
|
||||
BodyBlock {
|
||||
name: name.to_string(),
|
||||
role: BlockRole::Normal,
|
||||
typed: tir::lower_block_carrier(name, &lines, &HashMap::new()),
|
||||
typed: tir::lower_block_carrier(name, &lines, &HashMap::new()).map(Into::into),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -104,7 +104,7 @@ pub(in crate::native) fn split_phi_overlap(
|
||||
exit_rewrites.push((dst, kept_plus));
|
||||
}
|
||||
}
|
||||
if let Some(t) = &mut blocks[exit_idx].typed {
|
||||
if let Some(t) = blocks[exit_idx].typed_mut() {
|
||||
for (dst, kept_plus) in &exit_rewrites {
|
||||
t.set_phi_incomings(dst, kept_plus);
|
||||
}
|
||||
@@ -113,7 +113,7 @@ pub(in crate::native) fn split_phi_overlap(
|
||||
// Redirect the inner-loop predecessors' terminators from `exit` to the pass-through.
|
||||
for b in blocks.iter_mut() {
|
||||
if preds.iter().any(|p| p == &b.name) {
|
||||
if let Some(t) = &mut b.typed {
|
||||
if let Some(t) = b.typed_mut() {
|
||||
t.redirect_successor(exit, &new_name);
|
||||
}
|
||||
}
|
||||
@@ -139,7 +139,7 @@ pub(in crate::native) fn split_phi_overlap(
|
||||
BodyBlock {
|
||||
name: new_name.clone(),
|
||||
role: role_for_name(&new_name),
|
||||
typed: Some(blk),
|
||||
typed: Some(blk.into()),
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -31,8 +31,8 @@ pub(in crate::native) const EXIT_SEL_PREFIX: &str = "%metal2vulkan.exitsel.";
|
||||
/// True when `name` is a synthesized terminal-exit private-return merge block
|
||||
/// (`%metal2vulkan.lmerge.texitret*`). No production DECISION calls this any more (the convergence
|
||||
/// matcher and the single-exit-return synthesizer read the typed [`BlockRole::TerminalExitReturn`]
|
||||
/// tag instead of the name — Workstream T3); it survives only as the tag-assignment seam
|
||||
/// [`role_for_name`] uses to stamp a block whose name is the carried identity across a clone/rename.
|
||||
/// tag instead of the name); it survives only as the tag-assignment seam [`role_for_name`] uses to
|
||||
/// stamp a block whose name is the carried identity across a clone/rename.
|
||||
pub(in crate::native) fn is_terminal_exit_return_name(name: &str) -> bool {
|
||||
name.strip_prefix(SPLIT_PREFIX)
|
||||
.is_some_and(|rest| rest.starts_with(TEXITRET_TOKEN))
|
||||
@@ -57,10 +57,9 @@ pub(in crate::native) fn role_for_name(name: &str) -> BlockRole {
|
||||
}
|
||||
}
|
||||
|
||||
/// The full structured plan for a function: forest-augmented + structured-ordered blocks plus the
|
||||
/// loop/branch/switch merge maps the emitter consumes. The R2 emission consumer (modules 1+2+order)
|
||||
/// assembled; module 4's repair-FREE path consumes this. (Measured: not yet floor-safe without module
|
||||
/// 3's per-block cleanup — see the journal; kept as the plan generator + tested unit.)
|
||||
/// Full structured plan for a function: forest-augmented, structured-ordered blocks plus the
|
||||
/// loop/branch/switch merge maps consumed by emission. The retained-module cleanup remains part of
|
||||
/// the production pipeline after this primary by-construction plan.
|
||||
pub(in crate::native) struct StructuredPlan {
|
||||
pub(in crate::native) blocks: Vec<BodyBlock>,
|
||||
pub(in crate::native) loop_merges: HashMap<String, LoopMergeInfo>,
|
||||
@@ -77,12 +76,10 @@ pub(in crate::native) struct StructuredPlan {
|
||||
/// loop and every conditional/switch header has a unique merge, so the emitter emits a complete
|
||||
/// structured CFG; the kept post-hoc repair then normalizes rather than repairs.
|
||||
/// Block-count ceiling for the cross-arm-EDGE machinery (self-check 3 + the 9th-attempt clone). A pure
|
||||
/// PERFORMANCE bound (in the family of `MAX_REGION_BLOCKS`/`MAX_ROUNDS`): the self-check's edge walk and
|
||||
/// the clone's per-round dominator recompute are super-linear in block count and are re-invoked per
|
||||
/// retry tier, so on a several-thousand-block function (e.g. a runtime-descriptor-index selection giant)
|
||||
/// the retry cascade grinds for minutes. Every landed cross-arm-edge win is a small function (<=126
|
||||
/// emitted blocks), so gating the machinery to modest functions keeps all wins while leaving large
|
||||
/// functions byte-identical to before this attempt (skipped → they admit/reject exactly as they did).
|
||||
/// PERFORMANCE bound for cross-arm cloning and its repeated planner invocations. The final
|
||||
/// cross-arm correctness check itself is never size-gated: a large function must reject an invalid
|
||||
/// plan just as reliably as a small one. Every landed clone win is a small function (<=126 emitted
|
||||
/// blocks), so only the mutation/replanning machinery is kept to modest candidates.
|
||||
pub(in crate::native) const CROSS_ARM_EDGE_MAX_BLOCKS: usize = 300;
|
||||
|
||||
/// Reject-only loop-exit selection planning is intentionally bounded to modest CFGs. It walks a
|
||||
@@ -107,10 +104,9 @@ pub(in crate::native) const REGION_CROSS_ARM_LADDER_MAX_BLOCKS: usize = 300;
|
||||
pub(in crate::native) const SHARED_CONTINUATION_LADDER_MAX_BLOCKS: usize = 300;
|
||||
|
||||
/// Selection-merge synthesis can turn compact straight-line decision trees into hundreds of
|
||||
/// `%metal2vulkan.lmerge.sel*` pass-through blocks. That growth is useful for modest CFGs, but an
|
||||
/// oversized synthesized candidate is then fed into repeated dominator/loop-forest analyses. Cap the
|
||||
/// number of blocks added by synthesis, not the total candidate size, so already-large functions do
|
||||
/// not fall to the slow relooper path for one required merge split.
|
||||
/// `%metal2vulkan.lmerge.sel*` pass-through blocks. Keep a fixed allowance for modest CFGs and a
|
||||
/// one-block-per-source-block allowance for generated CFGs: a large function can legitimately need
|
||||
/// more than 300 private selection merges, while superlinear growth still indicates a runaway retry.
|
||||
pub(in crate::native) const SELECTION_SYNTH_GROWTH_MAX_BLOCKS: usize = 300;
|
||||
|
||||
/// Hard ceiling for the source-CFG structured planner. The ordinary reject path emits inferred merges
|
||||
@@ -163,6 +159,9 @@ pub(in crate::native) fn structured_plan(blocks: &[BodyBlock]) -> Option<Structu
|
||||
return Some(plan);
|
||||
}
|
||||
}
|
||||
// The helper returns an owned no-op clone when no ladder repair applies. Do not retain that
|
||||
// second full CFG through every later retry of a large function.
|
||||
drop(deep_shared);
|
||||
|
||||
// Two full passes of the attempt ladder. The FIRST runs with `allow_bare_exit=false` — byte-identical
|
||||
// to the pre-lever behavior, so every currently-admitting function is untouched. Only if the whole
|
||||
@@ -175,11 +174,20 @@ pub(in crate::native) fn structured_plan(blocks: &[BodyBlock]) -> Option<Structu
|
||||
// merge-inloop function often needs a cross-arm/synth CLONE first, then the bare-exit skip on the
|
||||
// residual latch. The second pass is byte-neutral for admitting functions (never reached) and its only
|
||||
// new admissions are functions that today fall through to the fallback.
|
||||
if let Some(plan) = structured_plan_ladder(blocks, false) {
|
||||
return Some(plan);
|
||||
}
|
||||
if let Some(plan) = structured_plan_ladder(blocks, true) {
|
||||
return Some(plan);
|
||||
if blocks.len() > TERMINAL_EXIT_SELECTION_MAX_BLOCKS {
|
||||
// Large generated CFGs go directly to the whole-CFG construct-tree/relooper fallback.
|
||||
// Even one speculative source-CFG candidate can coexist with the fallback's ownership graph
|
||||
// long enough to exceed the per-translation live-memory budget. The global path is the only
|
||||
// tier capable of resolving compound straddle/cross-arm ownership anyway, so a preliminary
|
||||
// local candidate adds cost without broadening support.
|
||||
return None;
|
||||
} else {
|
||||
if let Some(plan) = structured_plan_ladder(blocks, false) {
|
||||
return Some(plan);
|
||||
}
|
||||
if let Some(plan) = structured_plan_ladder(blocks, true) {
|
||||
return Some(plan);
|
||||
}
|
||||
}
|
||||
// Reject-only shared-merge separation: when divergent return-like exits are the structural reason
|
||||
// a conditional has no natural merge, route them through one synthesized function exit and rerun
|
||||
@@ -213,6 +221,43 @@ pub(in crate::native) fn structured_plan_divergent_exit(
|
||||
None
|
||||
}
|
||||
|
||||
/// Try the terminal-return policy matrix while sharing its rewritten CFG and fixed-point merge map.
|
||||
/// Keeping this as one ladder rung makes the relatively expensive preparation both explicit and
|
||||
/// impossible to duplicate accidentally when retry ordering changes.
|
||||
fn structured_plan_terminal_attempts(
|
||||
blocks: &[BodyBlock],
|
||||
allow_bare_exit: bool,
|
||||
) -> Option<StructuredPlan> {
|
||||
// On large CFGs, the full terminal ownership matrix composes a source-linear return split with
|
||||
// six complete loop/selection replans. That is not a bounded-memory operation: deeply generated
|
||||
// control flow can add hundreds of terminal owners before every variant rejects for an unrelated
|
||||
// cross-arm defect. Leave those functions to the construct-tree/relooper retry, which owns the
|
||||
// whole CFG and can resolve both relationships in one pass. The exact linear terminal primitive
|
||||
// itself remains available to the dedicated planner entry point and its regression coverage.
|
||||
if blocks.len() > TERMINAL_EXIT_SELECTION_MAX_BLOCKS {
|
||||
return None;
|
||||
}
|
||||
let prepared_terminal = prepare_terminal_exit_selection(blocks);
|
||||
for loop_exit_selection in [true, false] {
|
||||
for (converge, break_aware) in [(false, false), (true, false), (true, true)] {
|
||||
if let Some(plan) = structured_plan_inner8(
|
||||
blocks,
|
||||
converge,
|
||||
break_aware,
|
||||
false,
|
||||
allow_bare_exit,
|
||||
loop_exit_selection,
|
||||
true,
|
||||
false,
|
||||
prepared_terminal.as_ref(),
|
||||
) {
|
||||
return Some(plan);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub(in crate::native) fn structured_plan_ladder(
|
||||
blocks: &[BodyBlock],
|
||||
allow_bare_exit: bool,
|
||||
@@ -241,16 +286,17 @@ pub(in crate::native) fn structured_plan_ladder(
|
||||
return Some(plan);
|
||||
}
|
||||
}
|
||||
// Trivial privatization returns an owned no-op clone on the common decline path. Its only
|
||||
// consumer is the attempt above; retaining it beside `region` multiplies peak CFG memory.
|
||||
drop(privatized);
|
||||
// Third attempt: the merge-PRESERVING dominated-region clone for multi-successor / def-carrying
|
||||
// cross-arm shared arms (`privatize_region_cross_arm`). Unlike the trivial pass-through clone it
|
||||
// duplicates a whole dominated subtree up to its reconvergence boundary, so it rescues the dominant
|
||||
// `selection:cross-arm-shared` class. Applied AFTER the trivial pre-pass and computed on the
|
||||
// ORIGINAL blocks: this ordering, together with the existing plan self-checks in
|
||||
// `structured_plan_inner`, is floor-safe on the whole banked+frontier private capture set (G4 frontier byte-gate
|
||||
// empty, G5 banked floor 62 held). It does NOT reach the over-admitting shapes a chained
|
||||
// region-on-trivial variant hit (which needed a structured-exit completeness self-check that a
|
||||
// dominance model cannot express — see the journal). The clone also stays wired into the
|
||||
// spirv-val-gated `cfg_restructure` retry for the residual cross-arm shapes this does not admit.
|
||||
// ORIGINAL blocks. This avoids chaining the broad region clone onto an already cloned graph,
|
||||
// where a dominance-only model cannot prove structured-exit completeness. Existing plan
|
||||
// self-checks still gate adoption, and the clone also remains available in the spirv-val-gated
|
||||
// `cfg_restructure` retry for residual cross-arm shapes.
|
||||
let region = privatize_region_cross_arm_for_ladder(blocks);
|
||||
if region.len() != blocks.len() {
|
||||
if let Some(plan) =
|
||||
@@ -290,26 +336,13 @@ pub(in crate::native) fn structured_plan_ladder(
|
||||
{
|
||||
return Some(plan);
|
||||
}
|
||||
}
|
||||
// Terminal-return guards are not ordinary post-dominator selections: one arm may legitimately
|
||||
// exit through a shared function `ret`, while the other must continue through a private merge.
|
||||
// This reject-only attempt derives those continuation merges structurally, then reuses the normal
|
||||
// completeness and self-check gates. It is bounded to the same small CFGs as the other cross-arm
|
||||
// attempts, so a large descriptor kernel stays on its established fallback path.
|
||||
if blocks.len() <= TERMINAL_EXIT_SELECTION_MAX_BLOCKS {
|
||||
for &(converge, break_aware) in &[(false, false), (true, false), (true, true)] {
|
||||
if let Some(plan) = structured_plan_inner6(
|
||||
blocks,
|
||||
converge,
|
||||
break_aware,
|
||||
false,
|
||||
allow_bare_exit,
|
||||
false,
|
||||
true,
|
||||
) {
|
||||
return Some(plan);
|
||||
}
|
||||
}
|
||||
} else if let Some(plan) =
|
||||
structured_plan_inner5(blocks, true, false, false, allow_bare_exit, true)
|
||||
{
|
||||
// The general convergence refinement remains internally capped, but the linear loop-entry
|
||||
// terminal proof is valid at any size. Large graphs skip only switch lowering and the
|
||||
// expensive candidate search, not this exact structural retry.
|
||||
return Some(plan);
|
||||
}
|
||||
// Guard: skip the 5th/6th attempts for functions containing a SWITCH. The merge-inloop fix targets
|
||||
// conditional (2-arm) guarded breaks; these attempts only ADMIT the function, and an admitted switch
|
||||
@@ -320,7 +353,9 @@ pub(in crate::native) fn structured_plan_ladder(
|
||||
// the M1b default (`switch_gate_excludes`) excludes just an in-loop switch with a loop-exiting arm;
|
||||
// a loop-free switch (or an in-loop switch whose arms all stay in the loop) is safe to admit.
|
||||
if switch_gate_excludes(blocks) {
|
||||
return None;
|
||||
// The switch guard excludes the straddle and cross-arm retry families below, but a shared
|
||||
// function return is an independent structural exit and remains safe to prove here.
|
||||
return structured_plan_terminal_attempts(blocks, allow_bare_exit);
|
||||
}
|
||||
// Fifth attempt (Keystone 2): converge PLUS break-aware selection merges. The 4th attempt gives an
|
||||
// in-loop-collided loop a distinct merge and rotates its do-while latch to `{merge, continue}`, but
|
||||
@@ -487,6 +522,14 @@ pub(in crate::native) fn structured_plan_ladder(
|
||||
}
|
||||
}
|
||||
}
|
||||
// Terminal-return planning builds a fixed point and then evaluates several loop-policy variants.
|
||||
// Keep it as the true last resort: straddle and cross-arm repairs operate on the compact source CFG
|
||||
// and directly address their corresponding self-check classes, whereas terminal ownership can
|
||||
// expand deeply nested early-return control flow substantially without removing either defect.
|
||||
// Already-admitted functions returned above, so this ordering changes only rejected-CFG work.
|
||||
if let Some(plan) = structured_plan_terminal_attempts(blocks, allow_bare_exit) {
|
||||
return Some(plan);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
@@ -527,7 +570,8 @@ pub(in crate::native) fn selection_synth_growth_exceeds_ladder_cap(
|
||||
source_blocks: usize,
|
||||
synthesized_blocks: usize,
|
||||
) -> bool {
|
||||
synthesized_blocks.saturating_sub(source_blocks) > SELECTION_SYNTH_GROWTH_MAX_BLOCKS
|
||||
let allowed_growth = SELECTION_SYNTH_GROWTH_MAX_BLOCKS.max(source_blocks);
|
||||
synthesized_blocks.saturating_sub(source_blocks) > allowed_growth
|
||||
}
|
||||
|
||||
pub(in crate::native) fn is_switch_block(b: &BodyBlock) -> bool {
|
||||
|
||||
@@ -110,7 +110,17 @@ pub(in crate::native) fn plan_self_check_reason(
|
||||
// reaches it directly without passing through this header — the header does not dominate it and
|
||||
// the selection/switch "exits the selection ... but not via a structured exit" (banked
|
||||
// `e848bc87`/`72cbab44`). The repair path re-nests these; reject and fall back.
|
||||
if !plan_forest.dominates(&b.name, m) {
|
||||
let unreachable_terminal_merge = ordered
|
||||
.iter()
|
||||
.find(|block| block.name == *m)
|
||||
.is_some_and(|block| block.role == BlockRole::LMerge && is_bare_unreachable(block));
|
||||
if !plan_forest.dominates(&b.name, m) && !unreachable_terminal_merge {
|
||||
if crate::env_vars::spi_why() {
|
||||
eprintln!(
|
||||
"[spi-why] merge-not-dominated header={} merge={}",
|
||||
b.name, m,
|
||||
);
|
||||
}
|
||||
return Some("selection:merge-not-dominated");
|
||||
}
|
||||
for a in block_successors(b) {
|
||||
@@ -140,58 +150,62 @@ pub(in crate::native) fn plan_self_check_reason(
|
||||
// rejected. Computed edge-wise via idom walk (O(edges * dom-depth), NOT O(headers * blocks)): for a
|
||||
// NON-forward edge B->S, walk B's idom chain; at each selection-header ancestor H whose arm target
|
||||
// taken by B is `child`, the OTHER arm target `t1` making `dominates(t1, S)` true is the sibling arm.
|
||||
if ordered.len() <= CROSS_ARM_EDGE_MAX_BLOCKS {
|
||||
// header -> its two conditional branch targets. ONLY blocks with an assigned selection merge
|
||||
// (`header_merge`) are real OpSelectionMerge constructs; a conditional without one emits no
|
||||
// merge instruction, so its arms are not structured arms and a cross-arm edge on it is not a
|
||||
// structured-exit violation (matching self-check 2, which also keys on `header_merge`). Loops
|
||||
// and switches are excluded (a break/continue is a legal exit, not a cross-arm jump).
|
||||
let targets: HashMap<&str, (String, String)> = ordered
|
||||
.iter()
|
||||
.filter(|h| !plan_loop_headers.contains(h.name.as_str()))
|
||||
.filter_map(|h| {
|
||||
let m = header_merge.get(&h.name)?;
|
||||
let (t0, t1) = conditional_branch_targets(h)?;
|
||||
// Skip an if with an EMPTY arm (an arm target == the merge): the only exits are the real
|
||||
// arm and the merge, so there is no sibling arm to cross into and a branch to the merge
|
||||
// is a legal exit, not a cross-arm jump (matches the O(H*B) `&t == m` skip).
|
||||
if &t0 == m || &t1 == m || t0 == t1 {
|
||||
return None;
|
||||
}
|
||||
Some((h.name.as_str(), (t0, t1)))
|
||||
})
|
||||
.collect();
|
||||
for b in ordered {
|
||||
for s in block_successors(b) {
|
||||
// Forward edge (S in B's own subtree) is always a legal in-arm edge.
|
||||
if plan_forest.dominates(&b.name, &s) {
|
||||
continue;
|
||||
}
|
||||
// Walk B's dominator chain; `child` is the arm target of the header `cur` that B entered.
|
||||
let mut child: &str = &b.name;
|
||||
while let Some(cur) = plan_forest.idom(child) {
|
||||
if let Some((x, y)) = targets.get(cur) {
|
||||
let sibling = if child == x {
|
||||
Some(y)
|
||||
} else if child == y {
|
||||
Some(x)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(t1) = sibling {
|
||||
if plan_forest.dominates(t1, &s) {
|
||||
if crate::env_vars::spi_why() {
|
||||
eprintln!(
|
||||
// header -> its two conditional branch targets. ONLY blocks with an assigned selection merge
|
||||
// (`header_merge`) are real OpSelectionMerge constructs; a conditional without one emits no
|
||||
// merge instruction, so its arms are not structured arms and a cross-arm edge on it is not a
|
||||
// structured-exit violation (matching self-check 2, which also keys on `header_merge`). Loops
|
||||
// and switches are excluded (a break/continue is a legal exit, not a cross-arm jump).
|
||||
let targets: HashMap<&str, (String, String)> = ordered
|
||||
.iter()
|
||||
.filter(|h| !plan_loop_headers.contains(h.name.as_str()))
|
||||
.filter_map(|h| {
|
||||
let m = header_merge.get(&h.name)?;
|
||||
let (t0, t1) = conditional_branch_targets(h)?;
|
||||
// Skip an if with an EMPTY arm (an arm target == the merge): the only exits are the real
|
||||
// arm and the merge, so there is no sibling arm to cross into and a branch to the merge
|
||||
// is a legal exit, not a cross-arm jump (matches the O(H*B) `&t == m` skip).
|
||||
if &t0 == m || &t1 == m || t0 == t1 {
|
||||
return None;
|
||||
}
|
||||
Some((h.name.as_str(), (t0, t1)))
|
||||
})
|
||||
.collect();
|
||||
for b in ordered {
|
||||
for s in block_successors(b) {
|
||||
// A function return or unreachable target exits every enclosing selection; it is not a
|
||||
// sibling-arm entry. Fully terminal selections deliberately keep their source returns
|
||||
// and use a private disconnected unreachable merge.
|
||||
if block_ends_in_void_return(ordered, &s) || block_ends_in_unreachable(ordered, &s) {
|
||||
continue;
|
||||
}
|
||||
// Forward edge (S in B's own subtree) is always a legal in-arm edge.
|
||||
if plan_forest.dominates(&b.name, &s) {
|
||||
continue;
|
||||
}
|
||||
// Walk B's dominator chain; `child` is the arm target of the header `cur` that B entered.
|
||||
let mut child: &str = &b.name;
|
||||
while let Some(cur) = plan_forest.idom(child) {
|
||||
if let Some((x, y)) = targets.get(cur) {
|
||||
let sibling = if child == x {
|
||||
Some(y)
|
||||
} else if child == y {
|
||||
Some(x)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(t1) = sibling {
|
||||
if plan_forest.dominates(t1, &s) {
|
||||
if crate::env_vars::spi_why() {
|
||||
eprintln!(
|
||||
"[spi-why] cross-arm-edge header={} sibling={} block={} -> {}",
|
||||
cur, t1, b.name, s
|
||||
);
|
||||
}
|
||||
return Some("selection:cross-arm-edge");
|
||||
}
|
||||
return Some("selection:cross-arm-edge");
|
||||
}
|
||||
}
|
||||
child = cur;
|
||||
}
|
||||
child = cur;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -316,14 +330,24 @@ pub(in crate::native) fn structured_reject_reason(blocks: &[BodyBlock]) -> Optio
|
||||
if admits {
|
||||
return None;
|
||||
}
|
||||
} else if structured_plan_inner5(blocks, true, false, false, false, true).is_some() {
|
||||
return None;
|
||||
}
|
||||
if blocks.len() <= TERMINAL_EXIT_SELECTION_MAX_BLOCKS
|
||||
&& [(false, false), (true, false), (true, true)]
|
||||
.into_iter()
|
||||
.any(|(converge, break_aware)| {
|
||||
structured_plan_inner6(blocks, converge, break_aware, false, false, false, true)
|
||||
.is_some()
|
||||
})
|
||||
if [(false, false), (true, false), (true, true)]
|
||||
.into_iter()
|
||||
.any(|(converge, break_aware)| {
|
||||
structured_plan_inner6(blocks, converge, break_aware, false, false, true, true)
|
||||
.is_some()
|
||||
})
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if [(false, false), (true, false), (true, true)]
|
||||
.into_iter()
|
||||
.any(|(converge, break_aware)| {
|
||||
structured_plan_inner6(blocks, converge, break_aware, false, false, false, true)
|
||||
.is_some()
|
||||
})
|
||||
{
|
||||
return None;
|
||||
}
|
||||
@@ -1254,7 +1278,8 @@ mod tests {
|
||||
BodyBlock {
|
||||
name: name.to_string(),
|
||||
role,
|
||||
typed: crate::native::tir::lower_block_carrier(name, &lines, &HashMap::new()),
|
||||
typed: crate::native::tir::lower_block_carrier(name, &lines, &HashMap::new())
|
||||
.map(Into::into),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -87,6 +87,30 @@ pub(in crate::native) fn structured_plan_inner6(
|
||||
pub(in crate::native) fn structured_plan_construct_tree(
|
||||
blocks: &[BodyBlock],
|
||||
) -> Option<StructuredPlan> {
|
||||
// Prefer the immutable whole-CFG ownership proof. It can close ordinary, loop-exit, and terminal
|
||||
// switch constructs without duplicating their regions. Direct cross-arm privatization is a last
|
||||
// resort: on generated CFGs it can clone several nested copies before discovering that the raw
|
||||
// tree already owned the route, multiplying both planner work and live carrier memory.
|
||||
if let Some(plan) =
|
||||
structured_plan_inner7(blocks, false, false, false, true, false, false, true)
|
||||
{
|
||||
return Some(plan);
|
||||
}
|
||||
for (converge_inloop, break_aware) in [(true, false), (true, true), (false, false)] {
|
||||
if let Some(plan) = structured_plan_inner7(
|
||||
blocks,
|
||||
converge_inloop,
|
||||
break_aware,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
) {
|
||||
return Some(plan);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(cloned) = privatize_direct_construct_tree_cross_arm(blocks) {
|
||||
let shared_private =
|
||||
privatize_direct_construct_tree_shared_continuations(&cloned).unwrap_or(cloned);
|
||||
@@ -105,11 +129,6 @@ pub(in crate::native) fn structured_plan_construct_tree(
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(plan) =
|
||||
structured_plan_inner7(blocks, false, false, false, true, false, false, true)
|
||||
{
|
||||
return Some(plan);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
@@ -244,6 +263,31 @@ fn structured_plan_inner7(
|
||||
loop_exit_selection: bool,
|
||||
terminal_exit_selection: bool,
|
||||
construct_tree_owned: bool,
|
||||
) -> Option<StructuredPlan> {
|
||||
structured_plan_inner8(
|
||||
blocks,
|
||||
converge_inloop,
|
||||
break_aware,
|
||||
multi_exit_clone,
|
||||
allow_bare_exit,
|
||||
loop_exit_selection,
|
||||
terminal_exit_selection,
|
||||
construct_tree_owned,
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(in crate::native) fn structured_plan_inner8(
|
||||
blocks: &[BodyBlock],
|
||||
converge_inloop: bool,
|
||||
break_aware: bool,
|
||||
multi_exit_clone: bool,
|
||||
allow_bare_exit: bool,
|
||||
loop_exit_selection: bool,
|
||||
terminal_exit_selection: bool,
|
||||
construct_tree_owned: bool,
|
||||
prepared_terminal: Option<&TerminalExitSelectionPlan>,
|
||||
) -> Option<StructuredPlan> {
|
||||
let spi = crate::env_vars::spi_why();
|
||||
let tag = blocks.first().map(|b| b.name.clone()).unwrap_or_default();
|
||||
@@ -266,22 +310,22 @@ fn structured_plan_inner7(
|
||||
// loop. Give that loop a private return first: the prefix can then structure its own early
|
||||
// exits without claiming the loop's merge, and the loop retains a private, ordinary merge.
|
||||
// This is only a seed for the terminal retry; a seed with no terminal plan is discarded below.
|
||||
let terminal_seed = if terminal_exit_selection {
|
||||
let terminal_seed = if terminal_exit_selection && prepared_terminal.is_none() {
|
||||
privatize_single_loop_return_exit(blocks)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let terminal_input = terminal_seed.as_deref().unwrap_or(blocks);
|
||||
let terminal = if terminal_exit_selection {
|
||||
let computed_terminal = if terminal_exit_selection && prepared_terminal.is_none() {
|
||||
terminal_exit_selection_merges(terminal_input)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let terminal = prepared_terminal.or(computed_terminal.as_ref());
|
||||
let terminal_blocks = terminal
|
||||
.as_ref()
|
||||
.map(|plan| plan.blocks.as_slice())
|
||||
.unwrap_or(terminal_input);
|
||||
let (base_lblocks, loop_merges) =
|
||||
let (base_lblocks, mut loop_merges) =
|
||||
forest_loop_merges(terminal_blocks, converge_inloop, multi_exit_clone);
|
||||
let terminal_dispatch = if terminal_exit_selection {
|
||||
terminal_unreachable_selection_merges(&base_lblocks)
|
||||
@@ -292,23 +336,44 @@ fn structured_plan_inner7(
|
||||
spi_reject!("terminal-exit-no-candidate");
|
||||
return None;
|
||||
}
|
||||
let lblocks = terminal_dispatch
|
||||
let mut lblocks = terminal_dispatch
|
||||
.as_ref()
|
||||
.map(|plan| plan.blocks.clone())
|
||||
.unwrap_or(base_lblocks);
|
||||
let mut terminal_merges = HashMap::new();
|
||||
if let Some(plan) = &terminal {
|
||||
if let Some(plan) = terminal {
|
||||
terminal_merges.extend(plan.merges.clone());
|
||||
}
|
||||
if let Some(plan) = &terminal_dispatch {
|
||||
terminal_merges.extend(plan.merges.clone());
|
||||
}
|
||||
// The general terminal planner is intentionally bounded to modest CFGs, but a direct
|
||||
// `guard -> {continuation, ret}` is a local ownership relation. Compose those guards into the
|
||||
// construct-tree candidate with two edge splits each, so large generated functions do not fall
|
||||
// through to the enclosing-region repair and mistake the shared return for an ordinary merge.
|
||||
if construct_tree_owned {
|
||||
if let Some(plan) = direct_terminal_exit_selection_merges(&lblocks, &terminal_merges) {
|
||||
lblocks = plan.blocks;
|
||||
terminal_merges.extend(plan.merges);
|
||||
}
|
||||
coalesce_sibling_conditional_dispatches(&mut lblocks);
|
||||
// Regional ownership can add an enclosing predecessor to a loop's former exit after the
|
||||
// loop forest first selected it. Privatize that merge before selection synthesis so every
|
||||
// downstream role/collision map sees the final loop edge and cannot retain a stale key.
|
||||
privatize_nondominated_loop_merges(&mut lblocks, &mut loop_merges);
|
||||
}
|
||||
// Completeness: every natural loop must be covered by the forest loop-merge map (directly-
|
||||
// structurable, merge==continue split, or the narrow pure-self-latch NoExit split); every other
|
||||
// MultipleLatches/MultipleExits/NoExit shape still falls back.
|
||||
let lforest = analyze(&lblocks);
|
||||
for l in &lforest.loops {
|
||||
if !loop_merges.contains_key(&l.header) {
|
||||
if crate::env_vars::spi_why() {
|
||||
eprintln!(
|
||||
"[spi-why] uncovered-loop header={} latches={:?} exits={:?} parent={:?}",
|
||||
l.header, l.latches, l.exits, l.parent,
|
||||
);
|
||||
}
|
||||
spi_reject!(format!("loop-uncovered header={}", l.header));
|
||||
return None;
|
||||
}
|
||||
@@ -397,14 +462,26 @@ fn structured_plan_inner7(
|
||||
};
|
||||
if construct_tree_owned
|
||||
&& allow_bare_exit
|
||||
&& bare_loop_exit_branch_with_passthroughs(
|
||||
&& (bare_loop_exit_branch_with_passthroughs(
|
||||
&sblocks,
|
||||
&forest,
|
||||
&loop_merges,
|
||||
&b.name,
|
||||
&t,
|
||||
&f,
|
||||
)
|
||||
) || bare_enclosing_selection_region_escape(
|
||||
&sblocks,
|
||||
&forest,
|
||||
&branch_merges_by_header,
|
||||
&b.name,
|
||||
&t,
|
||||
) || bare_enclosing_selection_region_escape(
|
||||
&sblocks,
|
||||
&forest,
|
||||
&branch_merges_by_header,
|
||||
&b.name,
|
||||
&f,
|
||||
))
|
||||
{
|
||||
// The construct-tree candidate already owns inter-construct routes. A branch whose arm is
|
||||
// an enclosing loop role (merge/continue), or a sibling arm of an enclosing construct-tree
|
||||
@@ -431,26 +508,46 @@ fn structured_plan_inner7(
|
||||
{
|
||||
cont
|
||||
} else if allow_bare_exit
|
||||
&& bare_loop_exit_branch_with_passthroughs(
|
||||
&& (bare_loop_exit_branch_with_passthroughs(
|
||||
&sblocks,
|
||||
&forest,
|
||||
&loop_merges,
|
||||
&b.name,
|
||||
&t,
|
||||
&f,
|
||||
)
|
||||
) || bare_enclosing_selection_region_escape(
|
||||
&sblocks,
|
||||
&forest,
|
||||
&branch_merges_by_header,
|
||||
&b.name,
|
||||
&t,
|
||||
) || bare_enclosing_selection_region_escape(
|
||||
&sblocks,
|
||||
&forest,
|
||||
&branch_merges_by_header,
|
||||
&b.name,
|
||||
&f,
|
||||
))
|
||||
{
|
||||
// A bare structured break/continue or enclosing-selection sibling exit: no
|
||||
// OpSelectionMerge is needed. Skip the block (leave it out of `header_merge` → the
|
||||
// emitter writes a bare OpBranchConditional; self-checks 2/3 also skip it).
|
||||
skipped_bare_exit = true;
|
||||
continue;
|
||||
} else if construct_tree_owned && allow_bare_exit {
|
||||
// The construct tree is the ownership proof for inter-construct divergent
|
||||
// routes. A conditional left without an ordinary post-dominator after all
|
||||
// local merge/loop-role checks is a tree exit, not an incomplete local
|
||||
// selection. Emit it bare; this retry-only candidate is adopted only after the
|
||||
// finished module independently passes spirv-val.
|
||||
skipped_bare_exit = true;
|
||||
continue;
|
||||
} else {
|
||||
spi_reject!(format!(
|
||||
"branch-no-merge header={} arms=({},{})",
|
||||
b.name, t, f
|
||||
));
|
||||
if spi {
|
||||
if spi && sblocks.len() <= CROSS_ARM_EDGE_MAX_BLOCKS {
|
||||
eprintln!("[spi-why] --- sblocks skeleton (name -> terminator) ---");
|
||||
for sb in &sblocks {
|
||||
// Diagnostics-only skeleton print: source the phi count + terminator from the
|
||||
@@ -1300,6 +1397,7 @@ fn collect_llvalue_locals(value: &crate::native::ir::LlValue, out: &mut Vec<Stri
|
||||
collect_llvalue_locals(&index.value, out);
|
||||
}
|
||||
}
|
||||
LlValue::IntToPtr { source, .. } => collect_llvalue_locals(&source.value, out),
|
||||
LlValue::Global(_)
|
||||
| LlValue::Bool(_)
|
||||
| LlValue::Int(_)
|
||||
@@ -1500,7 +1598,20 @@ pub(in crate::native) fn privatize_synthesized_cross_arm_shared(
|
||||
let mut cur: Vec<BodyBlock> = blocks.to_vec();
|
||||
let mut counter = 2_000_000usize;
|
||||
const ROUNDS: usize = 16;
|
||||
let cap = blocks.len() + 512;
|
||||
// The ladder can only consume candidates within CROSS_ARM_EDGE_MAX_BLOCKS. Do not build (and,
|
||||
// critically, do not re-derive dominators/loop forests for) a larger candidate that the caller
|
||||
// will immediately discard. The former `blocks.len() + 512` private cap let a 20-block helper
|
||||
// grow beyond 500 blocks for another expensive detection round even though the public ladder's
|
||||
// 300-block gate made that work unobservable.
|
||||
let cap = (blocks.len() + 512).min(CROSS_ARM_EDGE_MAX_BLOCKS);
|
||||
// A block-count cap alone does not bound cloning cost: optimized AIR commonly has a few dozen
|
||||
// very large blocks, and duplicating their typed instruction payload several times can turn a
|
||||
// 25-block helper into hundreds of megabytes while every candidate still remains below 300
|
||||
// blocks. A successful dominated-region privatization needs at most a bounded number of copies
|
||||
// of the source payload; stop the reject-only attempt if compound cloning exceeds four source
|
||||
// payloads plus room for small synthesized blocks.
|
||||
let source_instructions = typed_instruction_count(blocks);
|
||||
let instruction_cap = source_instructions.saturating_mul(4).saturating_add(256);
|
||||
for _ in 0..ROUNDS {
|
||||
if cur.len() > cap {
|
||||
break;
|
||||
@@ -1516,10 +1627,31 @@ pub(in crate::native) fn privatize_synthesized_cross_arm_shared(
|
||||
break;
|
||||
};
|
||||
cur = next;
|
||||
if typed_instruction_count(&cur) > instruction_cap {
|
||||
// Return the source graph, not a partially cloned candidate: equality is the caller's
|
||||
// established signal that this optional ladder attempt made no consumable change.
|
||||
return blocks.to_vec();
|
||||
}
|
||||
if cur.len() > cap {
|
||||
// Preserve the oversized result so the caller's existing size check rejects it, but
|
||||
// avoid feeding it through another synthesis/forest round first.
|
||||
break;
|
||||
}
|
||||
}
|
||||
cur
|
||||
}
|
||||
|
||||
fn typed_instruction_count(blocks: &[BodyBlock]) -> usize {
|
||||
blocks.iter().fold(0usize, |count, block| {
|
||||
count.saturating_add(
|
||||
block
|
||||
.typed
|
||||
.as_ref()
|
||||
.map_or(1, |typed| typed.insts.len().saturating_add(1)),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -1532,7 +1664,8 @@ mod tests {
|
||||
BodyBlock {
|
||||
name: name.to_string(),
|
||||
role: BlockRole::Normal,
|
||||
typed: crate::native::tir::lower_block_carrier(name, &lines, &HashMap::new()),
|
||||
typed: crate::native::tir::lower_block_carrier(name, &lines, &HashMap::new())
|
||||
.map(Into::into),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -130,7 +130,7 @@ fn carrier_with_phis(
|
||||
Ok(BodyBlock {
|
||||
name: name.to_string(),
|
||||
role,
|
||||
typed: Some(carrier),
|
||||
typed: Some(carrier.into()),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -149,6 +149,7 @@ fn collect_value_locals(value: &LlValue, out: &mut Vec<String>) {
|
||||
collect_value_locals(&index.value, out);
|
||||
}
|
||||
}
|
||||
LlValue::IntToPtr { source, .. } => collect_value_locals(&source.value, out),
|
||||
LlValue::Global(_)
|
||||
| LlValue::Bool(_)
|
||||
| LlValue::Int(_)
|
||||
@@ -190,6 +191,9 @@ fn substitute_cross_slot_value(
|
||||
substitute_cross_slot_value(&mut index.value, value_slots, source);
|
||||
}
|
||||
}
|
||||
LlValue::IntToPtr {
|
||||
source: operand, ..
|
||||
} => substitute_cross_slot_value(&mut operand.value, value_slots, source),
|
||||
LlValue::Global(_)
|
||||
| LlValue::Bool(_)
|
||||
| LlValue::Int(_)
|
||||
@@ -730,7 +734,7 @@ fn regional_candidate(witness: Witness) -> Result<Vec<BodyBlock>, String> {
|
||||
let mut updates = Vec::new();
|
||||
for (case_index, &global) in ordered.iter().enumerate() {
|
||||
let mut case = blocks[global].clone();
|
||||
let carrier = case.typed.as_mut().expect("checked above");
|
||||
let carrier = std::sync::Arc::make_mut(case.typed.as_mut().expect("checked above"));
|
||||
carrier.rename(&rename);
|
||||
let substitutions = value_slots
|
||||
.iter()
|
||||
@@ -1189,8 +1193,7 @@ fn rewrite_entry_and_exit_phis(
|
||||
.map(|block| block.name.clone())
|
||||
.collect::<Vec<_>>();
|
||||
blocks[entry_from]
|
||||
.typed
|
||||
.as_mut()
|
||||
.typed_mut()
|
||||
.expect("checked above")
|
||||
.redirect_successor(&entry_to_name, PRE);
|
||||
|
||||
@@ -1203,7 +1206,7 @@ fn rewrite_entry_and_exit_phis(
|
||||
}
|
||||
for (&(target, phi), slots) in &payload_by_target_phi {
|
||||
let target_name = block_names[target].clone();
|
||||
let carrier = blocks[target].typed.as_mut().expect("checked above");
|
||||
let carrier = blocks[target].typed_mut().expect("checked above");
|
||||
let inst = carrier
|
||||
.insts
|
||||
.iter()
|
||||
@@ -1274,7 +1277,7 @@ mod tests {
|
||||
BodyBlock {
|
||||
name: name.to_string(),
|
||||
role: BlockRole::Normal,
|
||||
typed: tir::lower_block_carrier(name, &lines, &HashMap::new()),
|
||||
typed: tir::lower_block_carrier(name, &lines, &HashMap::new()).map(Into::into),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,12 +1,9 @@
|
||||
//! R2 relooper — structured block ordering (module 1 of the structured-by-construction emitter).
|
||||
//!
|
||||
//! The clean rewrite of CFG handling replaces the order-heuristic merges + the 14-pass post-hoc
|
||||
//! `repair_structured_merges` fixpoint with a structured-by-construction emitter. Four measured
|
||||
//! disproofs (journal 2026-06-25, AIR2VK-R2-INCR3/4/5 + the bf16 finding) established that the repair
|
||||
//! cannot be bypassed incrementally: it is entangled with block ordering, single-predecessor cleanup,
|
||||
//! and merge placement, so any partial wiring regresses the `--banked` floor. The emitter must
|
||||
//! therefore produce SPIR-V that is *already* structured-valid — which begins with emitting blocks in
|
||||
//! a structured order.
|
||||
//! Primary CFG emission is structured by construction. Block ordering, single-predecessor cleanup,
|
||||
//! and merge placement are coupled, so the planner produces a complete plan rather than incrementally
|
||||
//! bypassing individual retained-module repairs. This begins with emitting blocks in a structured
|
||||
//! order.
|
||||
//!
|
||||
//! This module is that ordering. SPIR-V's structured CFG requires every block to appear after its
|
||||
//! dominator and every construct's merge block to appear after the whole construct. [`structured_order`]
|
||||
@@ -16,15 +13,10 @@
|
||||
//! calls it (module 1 of the structured-by-construction consumer), so the order it returns is the order
|
||||
//! blocks are emitted in.
|
||||
//!
|
||||
//! Known gap (2026-06-27): on a few MPS kernels a loop body's inner `OpSelectionMerge` block is ordered
|
||||
//! BEFORE the loop header that dominates it, so a use precedes its def ("ID has not been defined", 9
|
||||
//! frontier cases — `02/ab4c2598`, `04/37318cb2`). The merge is deferred at `idom(merge)`, which here
|
||||
//! lands on a pre-loop block. This is NOT fixable by changing the deferral node: `idom(merge)` does not
|
||||
//! dominate the construct header (the extra predecessor is a genuine non-dominating pre-loop edge into
|
||||
//! the merge), the legacy repair path mis-orders it identically, and forcing the merge into the loop
|
||||
//! only surfaces the real blocker — the merge is reachable from inside AND outside the loop, so it
|
||||
//! cannot be that selection's merge without node duplication / splitting. The fix is the structurizer
|
||||
//! node-split rewrite, not a reorder. (See `kb/metal2vulkan-conformance.md`, frontier invalid-spirv clusters.)
|
||||
//! A merge reachable from both inside and outside a loop cannot legally serve as an inner
|
||||
//! selection's merge without node duplication or splitting. In that shape `idom(merge)` can lie
|
||||
//! before the loop, and changing only the deferral node cannot restore dominance. The planner must
|
||||
//! reject it for a structural retry rather than pretending an ordering change is sufficient.
|
||||
|
||||
use super::loopforest::LoopForest;
|
||||
use super::BodyBlock;
|
||||
@@ -45,9 +37,8 @@ use std::collections::{HashMap, HashSet};
|
||||
/// merge's idom IS its header (so this is unchanged for selections), but a loop's exit (merge) is
|
||||
/// frequently dominated by an in-body exit guard rather than the header. Deferring only at the header
|
||||
/// would leave such a merge as an ordinary child of the guard, where it can be emitted before later
|
||||
/// body blocks dominated by that guard — the `OpLoopMerge`-merge-before-dominating-body class
|
||||
/// (journal `00/f927b9f7`). Deferring at the guard (its idom) makes the merge that guard's last child,
|
||||
/// after the rest of the loop body.
|
||||
/// body blocks dominated by that guard. Deferring at the guard (its idom) makes the merge that
|
||||
/// guard's last child, after the rest of the loop body.
|
||||
///
|
||||
/// Iterative (explicit stack) to bound stack depth on the thousand-block MPS kernels.
|
||||
pub(in crate::native) fn structured_order(
|
||||
@@ -182,7 +173,7 @@ mod tests {
|
||||
BodyBlock {
|
||||
name,
|
||||
role: crate::native::cfg::BlockRole::Normal,
|
||||
typed,
|
||||
typed: typed.map(Into::into),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -450,7 +450,38 @@ pub(in crate::native) fn dce_preserving(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::spirv_module::ModuleHeader;
|
||||
use crate::spirv_module::{Block, Function, ModuleHeader};
|
||||
|
||||
#[test]
|
||||
fn single_incoming_phi_substitutes_its_concrete_value() {
|
||||
let mut block = Block::new();
|
||||
block.label = Some(Instruction::new(Op::Label, None, Some(7), vec![]));
|
||||
block.instructions = vec![
|
||||
// The deliberately stale result type models an interface-refined image value still
|
||||
// wrapped in the pointer carrier recorded before CFG edge splitting.
|
||||
Instruction::new(
|
||||
Op::Phi,
|
||||
Some(2),
|
||||
Some(10),
|
||||
vec![Operand::IdRef(5), Operand::IdRef(7)],
|
||||
),
|
||||
Instruction::new(
|
||||
Op::SampledImage,
|
||||
Some(3),
|
||||
Some(11),
|
||||
vec![Operand::IdRef(10), Operand::IdRef(6)],
|
||||
),
|
||||
];
|
||||
let mut function = Function::new();
|
||||
function.blocks.push(block);
|
||||
|
||||
assert!(collapse_trivial_phis(&mut function));
|
||||
assert_eq!(function.blocks[0].instructions.len(), 1);
|
||||
assert_eq!(
|
||||
function.blocks[0].instructions[0].operands.first(),
|
||||
Some(&Operand::IdRef(5))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dce_keeps_only_typed_sidecar_rooted_dead_global() {
|
||||
|
||||
@@ -376,7 +376,7 @@ fn accumulate_tir_soundness(
|
||||
/// actually sees. Built and validated alongside the string path; NOT yet consumed by emission (the
|
||||
/// byte gate guards consumption). Mirrors `emit_function`'s pre-loop exactly: split → lower
|
||||
/// unstructured switches → `structured_plan` (and on a structurizer reject, validate the lowered blocks
|
||||
/// the legacy-repair path would walk).
|
||||
/// the fallback merge-repair path would walk).
|
||||
pub fn tir_structured_self_check(san_ll: &str) -> Result<TirCheckStats, String> {
|
||||
let parsed = LlModule::parse(san_ll)?;
|
||||
let mut stats = TirCheckStats::default();
|
||||
|
||||
+23
-10
@@ -106,14 +106,11 @@ fn emit_vulkan_spirv_inner(
|
||||
buffer_layouts: Option<&HashMap<u32, meta::AirType>>,
|
||||
) -> Result<crate::emit_sidecar::EmittedSpirv, String> {
|
||||
// Lower `air.simdgroup_async_copy_2d` (+ its event/wait pair) to an explicit strided tile copy
|
||||
// before parse. Unconditional and byte-VERIFIED: the only regression case
|
||||
// (12/6ed53a6a `structuredSparse_2_4_1d`) now translates and runs byte-EXACT against Apple's golden
|
||||
// on this Mac's GPU via MoltenVK. Its SECOND wall (a Private-demoted pointer arm over-indexed as an
|
||||
// array) is fixed by the FC-promote/prune/PSB retry tiers, which see this lowering because the
|
||||
// production entry (`translate_sanitized_native_with_options`) applies it up front to `san_ll`
|
||||
// before the retries re-emit. This entry's own copy is retained for direct callers; already-lowered
|
||||
// text is a no-op guard. See `async_copy` + journal AIR2VK-ASYNC-COPY-CLEAR. floor-safe: only fires
|
||||
// on async-copy modules, which fail the emitter outright otherwise.
|
||||
// before parse. Modules that also need pointer cleanup are handled by the ordinary retry tiers,
|
||||
// which see this lowering because the production entry applies it before re-emission. This
|
||||
// entry's copy is retained for direct callers; already-lowered text is a no-op guard. See
|
||||
// `async_copy` and its structural regression tests. Floor-safe: only fires on async-copy modules,
|
||||
// which fail the emitter outright otherwise.
|
||||
let san_ll = async_copy::lower_simdgroup_async_copy(san_ll);
|
||||
// Scalarize any scalar/vector pointer-merge before parse (floor-safe: a no-op unless the module
|
||||
// carries a `<N x T>*`/`T*` merge the emitter rejects outright). See `vec_scalar_merge`.
|
||||
@@ -144,7 +141,7 @@ fn finalize_emission(
|
||||
/// SROA store-forwards the staging away, leaving the device buffer pointer used directly — a shape the
|
||||
/// emitter accepts. Byte-neutral (inlining + store-forwarding preserve semantics exactly) and
|
||||
/// floor-safe (an adopt-if-validates retry tier; both passes are no-ops on a module lacking the shape).
|
||||
/// See [`inline`] and [`sroa`].
|
||||
/// See the internal `inline` and `sroa` modules.
|
||||
pub fn emit_vulkan_spirv_inline_sroa(san_ll: &str) -> Result<Vec<u8>, String> {
|
||||
let kern = meta::parse_air_kernel_meta(san_ll);
|
||||
let entry_name = meta::entry_name(san_ll, "kernel");
|
||||
@@ -170,6 +167,21 @@ pub(crate) fn emit_vulkan_spirv_inline_sroa_with_sidecar(
|
||||
finalize_emission(Emitter::new(parsed), buffer_layouts)
|
||||
}
|
||||
|
||||
pub(crate) fn emit_vulkan_spirv_pointer_select_consumer_inline_with_sidecar(
|
||||
san_ll: &str,
|
||||
selected_pointer: &str,
|
||||
kern: Option<&meta::KernMeta>,
|
||||
entry_name: Option<&str>,
|
||||
buffer_layouts: Option<&HashMap<u32, meta::AirType>>,
|
||||
) -> Result<crate::emit_sidecar::EmittedSpirv, String> {
|
||||
let inlined = inline::inline_pointer_select_consumer(san_ll, entry_name, selected_pointer);
|
||||
let parsed = LlModule::parse_with_stage_meta(&inlined, kern, entry_name)?;
|
||||
// Inserting a multiblock helper at a callsite can make the ordinary structurizer's local clone
|
||||
// heuristics expand a large entry CFG. Emit the exact rewritten blocks as a bounded relooper feed;
|
||||
// the retry owns the whole-module structurization and adopts only validating output.
|
||||
finalize_emission(Emitter::new(parsed).with_relooper_feed(), buffer_layouts)
|
||||
}
|
||||
|
||||
/// Like [`emit_vulkan_spirv_inline_sroa`], but ALSO models every device/constant buffer raw (the
|
||||
/// word-`RuntimeArray` byte-offset model) before emission. After inlining + SROA collapse the helper
|
||||
/// boundary, the surviving device buffers are byte-addressed (`i8*`/`RuntimeArray<uchar>`) and the
|
||||
@@ -351,7 +363,8 @@ pub(crate) fn emit_vulkan_spirv_all_buffers_raw_relooper_feed_with_sidecar(
|
||||
/// emit gap). Byte-correct by construction: the stored bytes are the exact loaded address, the deref
|
||||
/// is `address + offset` with no tag-bit manipulation (verified across the cluster), and the address
|
||||
/// is a real Vulkan device address under `buffer_device_address`. The default Logical emit is never
|
||||
/// altered (this is an adopt-if-validates retry tier). See [`Emitter::with_bda_device_pointers`].
|
||||
/// altered (this is an adopt-if-validates retry tier). The internal emitter's
|
||||
/// `with_bda_device_pointers` mode owns the address conversion.
|
||||
pub fn emit_vulkan_spirv_all_buffers_raw_bda(san_ll: &str) -> Result<Vec<u8>, String> {
|
||||
let kern = meta::parse_air_kernel_meta(san_ll);
|
||||
let entry_name = meta::entry_name(san_ll, "kernel");
|
||||
|
||||
@@ -430,7 +430,15 @@ impl Emitter {
|
||||
return Ok(ids);
|
||||
}
|
||||
let args = self.function_call_args_for_params(call, &callee_params)?;
|
||||
let mut ids = Vec::with_capacity(args.len());
|
||||
let nullness_args = args
|
||||
.iter()
|
||||
.filter(|(index, _, _)| {
|
||||
self.function_param_nullness
|
||||
.contains(&(call.callee.clone(), *index))
|
||||
})
|
||||
.map(|(_, argument, _)| argument.value.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let mut ids = Vec::with_capacity(args.len() + nullness_args.len());
|
||||
for (index, arg, (param_name, param_ty)) in args {
|
||||
if let Some(id) = self.raw_workgroup_call_arg_id(
|
||||
&call.callee,
|
||||
@@ -466,9 +474,24 @@ impl Emitter {
|
||||
}
|
||||
ids.push(self.value_id_in(&arg.value, &arg.ty, instructions)?);
|
||||
}
|
||||
for value in &nullness_args {
|
||||
ids.push(self.pointer_call_arg_nullness_id(value)?);
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
fn pointer_call_arg_nullness_id(&mut self, value: &LlValue) -> Result<Word, String> {
|
||||
match value {
|
||||
LlValue::Zero => self.const_bool(true),
|
||||
LlValue::Local(name) => self.pointer_nullness.get(name).copied().ok_or_else(|| {
|
||||
format!("native emitter: pointer nullness is not tracked for call argument {name}")
|
||||
}),
|
||||
LlValue::Global(_) => self.const_bool(false),
|
||||
LlValue::Gep(gep) => self.pointer_call_arg_nullness_id(&gep.base.value),
|
||||
_ => Err("native emitter: helper pointer nullness requires a pointer value".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn function_call_args_for_params(
|
||||
&self,
|
||||
call: &LlCall,
|
||||
@@ -636,6 +659,18 @@ impl Emitter {
|
||||
let Some(raw) = self.raw_offsets.get(arg_name).cloned() else {
|
||||
return Ok(None);
|
||||
};
|
||||
if self.bda_device_pointers && raw.addrspace == 1 && !raw.unmodelable {
|
||||
let mut address_raw = raw.clone();
|
||||
if address_raw.device_addr_base.is_none() {
|
||||
let Some(base) = self.bda_direct_addresses.get(&raw.root).copied() else {
|
||||
return Ok(None);
|
||||
};
|
||||
address_raw.device_addr_base = Some(base);
|
||||
}
|
||||
return self
|
||||
.materialize_device_address(&address_raw, instructions)
|
||||
.map(Some);
|
||||
}
|
||||
if raw.addrspace != 1
|
||||
|| !raw.dyn_terms.is_empty()
|
||||
|| raw.unmodelable
|
||||
|
||||
@@ -198,6 +198,7 @@ impl Emitter {
|
||||
) {
|
||||
if !ops.is_empty() {
|
||||
let gep = LlGep {
|
||||
inbounds: inst.gep.as_ref().is_some_and(|gep| gep.inbounds),
|
||||
source_ty: source_ty.clone(),
|
||||
base: ops[0].clone(),
|
||||
indices: ops[1..].to_vec(),
|
||||
@@ -375,7 +376,7 @@ impl Emitter {
|
||||
// exactly as before — no side-table ownership move needed. Reaches the fail-visible
|
||||
// unmigrated-opcode `Err` below only when the carrier is absent (a malformed bitcast —
|
||||
// unreachable in well-formed AIR).
|
||||
if let Some((src, dst_text)) = &inst.bitcast {
|
||||
if let Some((src, dst_text)) = inst.bitcast.as_deref() {
|
||||
let (name, src, dst_text) = (name.clone(), src.clone(), dst_text.clone());
|
||||
return self.emit_bitcast_resolved(src, &dst_text, name, instructions);
|
||||
}
|
||||
@@ -387,7 +388,7 @@ impl Emitter {
|
||||
// Reaches the fail-visible unmigrated-opcode `Err` below only when the carrier is absent
|
||||
// (an indirect call, which `parse_call` rejects — unreachable in well-formed AIR for a value call).
|
||||
if let Some(call) = &inst.call {
|
||||
let (name, call) = (name.clone(), call.clone());
|
||||
let (name, call) = (name.clone(), (**call).clone());
|
||||
return self.emit_value_call_resolved(name, call, instructions);
|
||||
}
|
||||
if let Some(err) = &inst.value_call_error {
|
||||
@@ -405,7 +406,7 @@ impl Emitter {
|
||||
return self.emit_store_resolved(object, ptr, inst.mem_align, instructions);
|
||||
}
|
||||
}
|
||||
if let Some((object, ptr)) = &inst.store {
|
||||
if let Some((object, ptr)) = inst.store.as_deref() {
|
||||
let (object, ptr) = (object.clone(), ptr.clone());
|
||||
return self.emit_store_resolved(object, ptr, inst.mem_align, instructions);
|
||||
}
|
||||
@@ -426,7 +427,7 @@ impl Emitter {
|
||||
}
|
||||
}
|
||||
if let Some(call) = &inst.call {
|
||||
let (mut call, line) = (call.clone(), line.clone());
|
||||
let (mut call, line) = ((**call).clone(), line.clone());
|
||||
self.apply_tir_inst_void_call_args(inst, &mut call);
|
||||
return self.emit_void_call_body(call, &line, instructions);
|
||||
}
|
||||
@@ -451,6 +452,29 @@ impl Emitter {
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<(), String> {
|
||||
let resolved_ty = self.resolve_type(&argument.ty)?;
|
||||
// A cross-storage pointer select deliberately has no single Logical-SPIR-V pointer value or
|
||||
// storage class. Typed helper inlining must therefore forward its deferred carrier, not ask
|
||||
// `pointer_storage_for` to fabricate one for the synthetic parameter. The cloned helper's
|
||||
// GEP/load consumers replay the two concrete arms in the value domain exactly as direct
|
||||
// caller uses do. No placeholder substitution is needed because every supported use is
|
||||
// intercepted by the selected-pointer machinery; an escaping use still fails visibly.
|
||||
if let (LlType::Ptr(_), LlValue::Local(source)) = (&resolved_ty, &argument.value) {
|
||||
if let Some(selected) = self.selected_pointers.get(source).cloned() {
|
||||
self.selected_pointers.insert(name.to_string(), selected);
|
||||
self.direct_param_values.insert(name.to_string());
|
||||
self.param_values.insert(name.to_string());
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(selected) = self.selected_load_pointers.get(source).cloned() {
|
||||
self.pointer_pointees
|
||||
.insert(name.to_string(), selected.pointee.clone());
|
||||
self.selected_load_pointers
|
||||
.insert(name.to_string(), selected);
|
||||
self.direct_param_values.insert(name.to_string());
|
||||
self.param_values.insert(name.to_string());
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
// Preserve a descriptor-backed raw buffer's byte cursor across helper inlining. A non-zero
|
||||
// GEP of a raw device buffer has a Private placeholder as its ordinary SSA value, while its
|
||||
// real descriptor root and byte offset live in `raw_offsets`. Binding the helper parameter
|
||||
@@ -459,9 +483,11 @@ impl Emitter {
|
||||
// callee's existing raw load/store lowering then reapplies the offset structurally.
|
||||
let inline_raw = if self.raw_buffer_params.contains(name) {
|
||||
match &argument.value {
|
||||
LlValue::Local(source) => self.raw_offsets.get(source).cloned().filter(|raw| {
|
||||
raw.addrspace == 1 && !raw.unmodelable && raw.device_addr_base.is_none()
|
||||
}),
|
||||
LlValue::Local(source) => self
|
||||
.raw_offsets
|
||||
.get(source)
|
||||
.cloned()
|
||||
.filter(|raw| raw.addrspace == 1 && !raw.unmodelable),
|
||||
_ => None,
|
||||
}
|
||||
} else {
|
||||
@@ -503,6 +529,19 @@ impl Emitter {
|
||||
self.param_values.insert(name.to_string());
|
||||
|
||||
if let Some((addrspace, storage, pointee, nullness)) = pointer_facts {
|
||||
if self.bda_device_pointers {
|
||||
if let LlValue::Local(source) = &argument.value {
|
||||
let address = self.bda_direct_addresses.get(source).copied().or_else(|| {
|
||||
self.raw_offsets.get(source).and_then(|raw| {
|
||||
raw.device_addr_base
|
||||
.or_else(|| self.bda_direct_addresses.get(&raw.root).copied())
|
||||
})
|
||||
});
|
||||
if let Some(address) = address {
|
||||
self.bda_direct_addresses.insert(name.to_string(), address);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.pointer_storage.insert(name.to_string(), storage);
|
||||
if let Some(pointee) = pointee {
|
||||
self.pointer_pointees.insert(name.to_string(), pointee);
|
||||
@@ -1063,6 +1102,16 @@ impl Emitter {
|
||||
let src_id = self.value_id(&src.value, &src.ty)?;
|
||||
if self.bda_device_pointers && addrspace == 1 {
|
||||
self.used_device_address = true;
|
||||
let bool_ty = self.type_id(&LlType::Bool)?;
|
||||
let zero = self.const_signed_int(64, 0)?;
|
||||
let is_null = self.result_id(&pointer_null_name(&name), &LlType::Bool)?;
|
||||
_instructions.push(Self::inst(
|
||||
Op::IEqual,
|
||||
Some(bool_ty),
|
||||
Some(is_null),
|
||||
vec![Operand::IdRef(src_id), Operand::IdRef(zero)],
|
||||
));
|
||||
self.pointer_nullness.insert(name.clone(), is_null);
|
||||
let mut dev = RawBufferOffset::root(format!(".bda_inttoptr_{src_id}"), 1);
|
||||
dev.device_addr_base = Some(src_id);
|
||||
self.raw_offsets.insert(name.clone(), dev);
|
||||
@@ -1078,6 +1127,46 @@ impl Emitter {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn combine_pointer_payload_words(
|
||||
&mut self,
|
||||
low: Word,
|
||||
high: Word,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<Word, String> {
|
||||
let i64_ty = LlType::Int(64);
|
||||
let result_type = self.type_id(&i64_ty)?;
|
||||
let low64 = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::UConvert,
|
||||
Some(result_type),
|
||||
Some(low64),
|
||||
vec![Operand::IdRef(low)],
|
||||
));
|
||||
let high64 = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::UConvert,
|
||||
Some(result_type),
|
||||
Some(high64),
|
||||
vec![Operand::IdRef(high)],
|
||||
));
|
||||
let shifted_high = self.fresh();
|
||||
let shift = self.const_signed_int(64, 32)?;
|
||||
instructions.push(Self::inst(
|
||||
Op::ShiftLeftLogical,
|
||||
Some(result_type),
|
||||
Some(shifted_high),
|
||||
vec![Operand::IdRef(high64), Operand::IdRef(shift)],
|
||||
));
|
||||
let address = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::BitwiseOr,
|
||||
Some(result_type),
|
||||
Some(address),
|
||||
vec![Operand::IdRef(low64), Operand::IdRef(shifted_high)],
|
||||
));
|
||||
Ok(address)
|
||||
}
|
||||
|
||||
/// The operand-resolved core of the `ptrtoint` handler (see `emit_inttoptr_resolved`). Driven from
|
||||
/// `TirInst.operands[0]` (pointer source) + `TirInst.result_ty` (integer dest).
|
||||
pub(in crate::native::emitter) fn emit_ptrtoint_resolved(
|
||||
@@ -1260,6 +1349,16 @@ impl Emitter {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
// A local pointer field uses an integer placeholder in Logical SPIR-V, but its typed source
|
||||
// must survive in the sidecar for post-interface recovery. Give that exact structural case
|
||||
// first refusal: generic raw-byte reinterpretation can represent the placeholder store, but
|
||||
// cannot preserve which bound buffer/image pointer was stored there.
|
||||
if let Some(pointee) = self.pointer_pointee_for_value(&ptr.value)? {
|
||||
let pointee = self.resolve_type(&pointee)?;
|
||||
if self.emit_pointer_to_local_field_store(&object, &ptr, &pointee, instructions)? {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if let Some(raw) = self.byte_array_reinterpret_raw_pointer(&ptr.value)? {
|
||||
let object_id = self.value_id_in(&object.value, &object.ty, instructions)?;
|
||||
self.emit_raw_store(&object.ty, object_id, &raw, align, instructions)?;
|
||||
@@ -1274,11 +1373,6 @@ impl Emitter {
|
||||
if let Some(pointee) = self.pointer_pointee_for_value(&ptr.value)? {
|
||||
let pointee = self.resolve_type(&pointee)?;
|
||||
let object_ty = self.resolve_type(&object.ty)?;
|
||||
if !types_compatible(&pointee, &object_ty)
|
||||
&& self.emit_pointer_to_local_field_store(&object, &ptr, &pointee, instructions)?
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
if !types_compatible(&pointee, &object_ty)
|
||||
&& self.emit_i64_to_i32_pair_struct_store(&object, &ptr, &pointee, instructions)?
|
||||
{
|
||||
@@ -1328,6 +1422,11 @@ impl Emitter {
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
if !types_compatible(&pointee, &object_ty)
|
||||
&& self.emit_vector_as_scalar_array_store(&object, &ptr, &pointee, instructions)?
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
if !types_compatible(&pointee, &object_ty)
|
||||
&& self.emit_vector_to_scalar_stores(&object, &ptr, &pointee, instructions)?
|
||||
{
|
||||
@@ -1730,6 +1829,47 @@ impl Emitter {
|
||||
}
|
||||
self.emit_raw_load(result, &result_ty, &raw, load.align, instructions)?;
|
||||
if let LlType::Ptr(_) = result_ty {
|
||||
let parameter_root = self
|
||||
.direct_param_values
|
||||
.contains(&raw.root)
|
||||
.then(|| self.values.get(&raw.root).map(|(id, _)| *id))
|
||||
.flatten();
|
||||
if raw.device_addr_base.is_none()
|
||||
&& raw.dyn_terms.is_empty()
|
||||
&& raw.const_off >= 0
|
||||
{
|
||||
// Keep the emitted parameter id, including for internal helpers. The
|
||||
// emitted-function inliner substitutes that id with the caller argument
|
||||
// (recursively up to the entry parameter), and remaps this sidecar fact by
|
||||
// the same map. A parameter ordinal is only meaningful in its defining
|
||||
// function and therefore cannot survive nested helper inlining.
|
||||
if let Some(root) = parameter_root {
|
||||
self.emit_sidecar.buffer_pointer_field_loads.push(
|
||||
crate::emit_sidecar::BufferPointerFieldLoad {
|
||||
id: result,
|
||||
root,
|
||||
byte_offset: raw.const_off as u64,
|
||||
},
|
||||
);
|
||||
}
|
||||
} else if raw.device_addr_base.is_none() && raw.const_off >= 0 {
|
||||
if let (Some(root), [(index, 8)]) =
|
||||
(parameter_root, raw.dyn_terms.as_slice())
|
||||
{
|
||||
// AIR's opaque texture handle is one 64-bit element. Preserve the
|
||||
// logical GEP element selector rather than its byte-scaled raw offset so
|
||||
// the final descriptor-array binding can materialize exactly that image.
|
||||
let index = self.value_id_in(&index.value, &index.ty, instructions)?;
|
||||
self.emit_sidecar.buffer_pointer_dynamic_field_loads.push(
|
||||
crate::emit_sidecar::BufferPointerDynamicFieldLoad {
|
||||
id: result,
|
||||
root,
|
||||
byte_offset: raw.const_off as u64,
|
||||
index,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
self.pointer_storage
|
||||
.insert(name.clone(), StorageClass::Private);
|
||||
self.pointer_pointees.insert(name.clone(), LlType::Int(8));
|
||||
@@ -1824,6 +1964,15 @@ impl Emitter {
|
||||
)? {
|
||||
return Ok(());
|
||||
}
|
||||
if self.emit_scalar_array_as_vector_load(
|
||||
result,
|
||||
&pointee,
|
||||
&result_ty,
|
||||
ptr,
|
||||
instructions,
|
||||
)? {
|
||||
return Ok(());
|
||||
}
|
||||
if self.emit_first_pointer_aggregate_reinterpret_load(
|
||||
&name,
|
||||
result,
|
||||
|
||||
@@ -66,17 +66,9 @@ impl Emitter {
|
||||
}
|
||||
}
|
||||
if let Some(selected) = self.selected_load_pointers.get(base_name).cloned() {
|
||||
let storage = self
|
||||
.pointer_storage
|
||||
.get(base_name)
|
||||
.copied()
|
||||
.ok_or_else(|| {
|
||||
format!("native emitter: selected pointer GEP {base_name} missing storage")
|
||||
})?;
|
||||
if self.emit_selected_load_pointer_gep(
|
||||
name,
|
||||
&selected,
|
||||
storage,
|
||||
&parsed_source_ty,
|
||||
&gep.indices,
|
||||
instructions,
|
||||
@@ -636,6 +628,51 @@ impl Emitter {
|
||||
if indices.len() == 1 {
|
||||
self.materialize_reserved_pointer_index(name, &indices[0], instructions)?;
|
||||
}
|
||||
let fact_source_ty = if entry_metadata_indices.is_some() {
|
||||
base_pointee.clone().unwrap_or_else(|| source_ty.clone())
|
||||
} else {
|
||||
source_ty.clone()
|
||||
};
|
||||
let fact_indices = entry_metadata_indices
|
||||
.clone()
|
||||
.unwrap_or_else(|| indices.clone());
|
||||
let raw = self.apply_raw_gep(
|
||||
RawBufferOffset::root(String::new(), provenance_addrspace),
|
||||
&fact_source_ty,
|
||||
&fact_indices,
|
||||
)?;
|
||||
if !raw.unmodelable && raw.const_off >= 0 {
|
||||
if raw.dyn_terms.is_empty() {
|
||||
self.emit_sidecar.buffer_access_offsets.push(
|
||||
crate::emit_sidecar::BufferAccessOffset {
|
||||
id: result,
|
||||
root,
|
||||
byte_offset: raw.const_off as u64,
|
||||
},
|
||||
);
|
||||
} else if raw.dyn_terms.iter().all(|(_, stride)| *stride >= 0) {
|
||||
let terms = raw
|
||||
.dyn_terms
|
||||
.iter()
|
||||
.map(|(index, stride)| {
|
||||
Ok((
|
||||
self.value_id(&index.value, &index.ty)?,
|
||||
u64::try_from(*stride).map_err(|_| {
|
||||
"native emitter: negative affine buffer stride".to_string()
|
||||
})?,
|
||||
))
|
||||
})
|
||||
.collect::<Result<Vec<_>, String>>()?;
|
||||
self.emit_sidecar.buffer_access_affine_offsets.push(
|
||||
crate::emit_sidecar::BufferAccessAffineOffset {
|
||||
id: result,
|
||||
root,
|
||||
constant: raw.const_off as u64,
|
||||
terms,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
self.gep_provenance.insert(
|
||||
name.to_string(),
|
||||
GepProvenance {
|
||||
@@ -1070,24 +1107,6 @@ impl Emitter {
|
||||
Ok(Some(current))
|
||||
}
|
||||
|
||||
/// True only for a pointer whose decoded GEP provenance originates at the emitter-owned
|
||||
/// imageblock scratch variable. This permits a private complete cell's first scalar member to
|
||||
/// be addressed structurally without broadening aggregate-reinterpret stores elsewhere.
|
||||
pub(in crate::native::emitter) fn is_imageblock_scratch_pointer(
|
||||
&self,
|
||||
pointer: &LlValue,
|
||||
) -> bool {
|
||||
let LlValue::Local(name) = pointer else {
|
||||
return false;
|
||||
};
|
||||
let Some(provenance) = self.gep_provenance.get(name) else {
|
||||
return false;
|
||||
};
|
||||
self.imageblock_data_scratch
|
||||
.as_ref()
|
||||
.is_some_and(|(root, _)| provenance.root == *root)
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn byte_array_reinterpret_raw_gep(
|
||||
&self,
|
||||
base_value: &LlValue,
|
||||
@@ -1101,9 +1120,6 @@ impl Emitter {
|
||||
if !matches!(base_storage, StorageClass::Function | StorageClass::Private) {
|
||||
return Ok(None);
|
||||
}
|
||||
if !matches!(source_ty, LlType::Array(_, _) | LlType::Struct(_)) {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(root) = self
|
||||
.byte_array_reinterpret_root(base_value, base_pointee)
|
||||
.or_else(|| self.byte_array_reinterpret_root_for_id(base_id))
|
||||
@@ -1394,6 +1410,18 @@ impl Emitter {
|
||||
let LlValue::Local(name) = value else {
|
||||
return Ok(None);
|
||||
};
|
||||
if let Some(root) = self.byte_array_reinterpret_root(value, self.pointer_pointees.get(name))
|
||||
{
|
||||
let addrspace = self
|
||||
.values
|
||||
.get(name)
|
||||
.and_then(|(_, ty)| match ty {
|
||||
LlType::Ptr(addrspace) => Some(*addrspace),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(0);
|
||||
return Ok(Some(RawBufferOffset::root(root, addrspace)));
|
||||
}
|
||||
let Some(provenance) = self.gep_provenance.get(name) else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
@@ -852,6 +852,24 @@ impl Emitter {
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
// A named AIR wrapper can contain the exact aggregate copied into a bare local array
|
||||
// (`metal::matrix<T>` -> its `[N x vector<T>]` storage). Descend through the source's
|
||||
// offset-zero field just as the symmetric destination-wrapper path below does. The helper's
|
||||
// extent guard keeps this honest when a struct has trailing fields or padding covered by the
|
||||
// requested byte count.
|
||||
if matches!(src_pointee, LlType::Struct(_))
|
||||
&& self.emit_prefix_source_struct_memcpy(
|
||||
&call.args[0],
|
||||
&call.args[1],
|
||||
&dst_pointee,
|
||||
&src_pointee,
|
||||
len,
|
||||
instructions,
|
||||
)?
|
||||
{
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
if let (LlType::Struct(dst_fields), LlType::Struct(src_fields)) =
|
||||
(&dst_pointee, &src_pointee)
|
||||
{
|
||||
@@ -1062,6 +1080,10 @@ impl Emitter {
|
||||
if !types_compatible(&dst_pointee, &src_field) {
|
||||
return Ok(false);
|
||||
}
|
||||
let (field_size, _) = self.raw_type_size_align(&src_field)?;
|
||||
if len > field_size {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let LlType::Ptr(dst_addrspace) = self.resolve_type(&dst_arg.ty)? else {
|
||||
return Ok(false);
|
||||
|
||||
@@ -147,9 +147,8 @@ impl Emitter {
|
||||
pointee: &LlType,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<bool, String> {
|
||||
if !local_pointer_field_pointee(pointee)
|
||||
|| !matches!(self.resolve_type(&object.ty)?, LlType::Ptr(_))
|
||||
{
|
||||
let object_ty = self.resolve_type(&object.ty)?;
|
||||
if !local_pointer_field_pointee(pointee) || !matches!(object_ty, LlType::Ptr(_)) {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(key) = self.local_pointer_field_key(ptr)? else {
|
||||
@@ -170,6 +169,8 @@ impl Emitter {
|
||||
crate::emit_sidecar::LocalPointerFieldStore {
|
||||
id: zero,
|
||||
source: object_id,
|
||||
root: key.root,
|
||||
indices: key.indices.clone(),
|
||||
},
|
||||
);
|
||||
instructions.push(Self::inst(
|
||||
@@ -247,6 +248,19 @@ impl Emitter {
|
||||
Some(result),
|
||||
vec![Operand::IdRef(source)],
|
||||
));
|
||||
// This is only a pointer-typed copy until interface binding gives an opaque AIR resource
|
||||
// parameter its final SPIR-V image/sampler type. Preserve the field identity even on the
|
||||
// emitter's fast path so `recover_inlined_local_pointer_fields` can replace the copy with
|
||||
// its stored source before that retyping. Without this fact, binding a texture held in a
|
||||
// private aggregate rewrites only the operand to an OpTypeImage and leaves an invalid
|
||||
// pointer-typed OpCopyObject behind.
|
||||
self.emit_sidecar.local_pointer_field_loads.push(
|
||||
crate::emit_sidecar::LocalPointerFieldLoad {
|
||||
id: result,
|
||||
root: key.root,
|
||||
indices: key.indices.clone(),
|
||||
},
|
||||
);
|
||||
self.pointer_storage
|
||||
.insert(result_name.to_string(), storage);
|
||||
self.pointer_pointees
|
||||
@@ -275,7 +289,13 @@ impl Emitter {
|
||||
};
|
||||
let Some((root, prefix, index, suffix)) = self.local_pointer_dynamic_field_index(ptr)?
|
||||
else {
|
||||
return Ok(false);
|
||||
return self.emit_pointer_from_local_multidynamic_field_load(
|
||||
result_name,
|
||||
result,
|
||||
result_ty,
|
||||
ptr,
|
||||
instructions,
|
||||
);
|
||||
};
|
||||
let values = self
|
||||
.local_pointer_fields
|
||||
@@ -289,21 +309,21 @@ impl Emitter {
|
||||
.then(|| (key.indices[prefix.len()], value.clone()))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let index_id = self.value_id_in(&index.value, &index.ty, instructions)?;
|
||||
self.emit_sidecar.local_pointer_dynamic_field_loads.push(
|
||||
crate::emit_sidecar::LocalPointerDynamicFieldLoad {
|
||||
id: result,
|
||||
root,
|
||||
prefix: prefix.clone(),
|
||||
index: index_id,
|
||||
suffix: suffix.clone(),
|
||||
},
|
||||
);
|
||||
if values.is_empty() {
|
||||
let LlType::Ptr(addrspace) = result_ty else {
|
||||
return Ok(false);
|
||||
};
|
||||
let index_id = self.value_id_in(&index.value, &index.ty, instructions)?;
|
||||
self.emit_unmodeled_byte_pointer_copy(result_name, result, *addrspace, instructions)?;
|
||||
self.emit_sidecar.local_pointer_dynamic_field_loads.push(
|
||||
crate::emit_sidecar::LocalPointerDynamicFieldLoad {
|
||||
id: result,
|
||||
root,
|
||||
prefix,
|
||||
index: index_id,
|
||||
suffix,
|
||||
},
|
||||
);
|
||||
return Ok(true);
|
||||
}
|
||||
let mut values = values;
|
||||
@@ -327,7 +347,6 @@ impl Emitter {
|
||||
let LlType::Int(index_bits) = index_ty else {
|
||||
return Ok(false);
|
||||
};
|
||||
let index_id = self.value_id_in(&index.value, &index.ty, instructions)?;
|
||||
let result_type = self.pointer_aware_type_id(result_ty, Some(&pointer_meta))?;
|
||||
let bool_type = self.type_id(&LlType::Bool)?;
|
||||
|
||||
@@ -374,7 +393,8 @@ impl Emitter {
|
||||
self.dynamic_pointer_tables.insert(
|
||||
result_name.to_string(),
|
||||
DynamicPointerTable {
|
||||
index: index.clone(),
|
||||
selector: index_id,
|
||||
selector_bits: index_bits,
|
||||
entries: values,
|
||||
},
|
||||
);
|
||||
@@ -385,6 +405,183 @@ impl Emitter {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Load from a local pointer table addressed by two or more dynamic aggregate indices. Each
|
||||
/// concrete stored field is selected by the conjunction of its per-dimension index comparisons.
|
||||
/// This is the multidimensional counterpart of `emit_pointer_from_local_dynamic_field_load`:
|
||||
/// it uses only exact store facts for the same aggregate root and never infers an unstored arm.
|
||||
pub(in crate::native::emitter) fn emit_pointer_from_local_multidynamic_field_load(
|
||||
&mut self,
|
||||
result_name: &str,
|
||||
result: Word,
|
||||
result_ty: &LlType,
|
||||
ptr: &TypedValue,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<bool, String> {
|
||||
let LlType::Ptr(_) = result_ty else {
|
||||
return Ok(false);
|
||||
};
|
||||
let LlValue::Local(pointer_name) = &ptr.value else {
|
||||
return Ok(false);
|
||||
};
|
||||
let Some(provenance) = self.gep_provenance.get(pointer_name).cloned() else {
|
||||
return Ok(false);
|
||||
};
|
||||
let LlType::Ptr(addrspace) = self.resolve_type(&ptr.ty)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
if self.pointer_storage_for(&ptr.value, addrspace)? != StorageClass::Function {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut indices = provenance.indices;
|
||||
if indices.len() > 1 && const_index(indices.first()) == Some(0) {
|
||||
indices.remove(0);
|
||||
}
|
||||
let dynamic_positions = indices
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(position, index)| const_index(Some(index)).is_none().then_some(position))
|
||||
.collect::<Vec<_>>();
|
||||
if dynamic_positions.len() < 2 {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let mut values = self
|
||||
.local_pointer_fields
|
||||
.iter()
|
||||
.filter_map(|(key, value)| {
|
||||
if key.root != provenance.root || key.indices.len() != indices.len() {
|
||||
return None;
|
||||
}
|
||||
let matches_constants = indices.iter().enumerate().all(|(position, index)| {
|
||||
const_index(Some(index)).is_none()
|
||||
|| const_index(Some(index)) == Some(key.indices[position])
|
||||
});
|
||||
matches_constants.then(|| (key.indices.clone(), value.clone()))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if values.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
values.sort_by(|(left, _), (right, _)| left.cmp(right));
|
||||
|
||||
let value_refs = values
|
||||
.iter()
|
||||
.map(|(_, value)| &value.value)
|
||||
.collect::<Vec<_>>();
|
||||
let Some(pointer_meta) = self.pointer_merge_meta(&value_refs, result_ty)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
if !matches!(
|
||||
pointer_meta.storage,
|
||||
StorageClass::StorageBuffer | StorageClass::UniformConstant | StorageClass::Workgroup
|
||||
) {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let mut dynamic_ids = Vec::with_capacity(dynamic_positions.len());
|
||||
for &position in &dynamic_positions {
|
||||
let index = &indices[position];
|
||||
let LlType::Int(bits) = self.resolve_type(&index.ty)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
let id = self.value_id_in(&index.value, &index.ty, instructions)?;
|
||||
dynamic_ids.push((position, id, bits));
|
||||
}
|
||||
let result_type = self.pointer_aware_type_id(result_ty, Some(&pointer_meta))?;
|
||||
let bool_type = self.type_id(&LlType::Bool)?;
|
||||
let selector_bits = 32;
|
||||
let selector_type = self.type_id(&LlType::Int(selector_bits))?;
|
||||
let mut current = self.value_id_in(&values[0].1.value, &values[0].1.ty, instructions)?;
|
||||
let mut selector = self.const_int(selector_bits, 0)?;
|
||||
|
||||
for (ordinal, (stored_key, stored_value)) in values.iter().enumerate().skip(1) {
|
||||
let stored_id =
|
||||
self.value_id_in(&stored_value.value, &stored_value.ty, instructions)?;
|
||||
let mut condition = None;
|
||||
for &(position, index_id, index_bits) in &dynamic_ids {
|
||||
let expected = self.const_int(index_bits, stored_key[position] as u64)?;
|
||||
let equal = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::IEqual,
|
||||
Some(bool_type),
|
||||
Some(equal),
|
||||
vec![Operand::IdRef(index_id), Operand::IdRef(expected)],
|
||||
));
|
||||
condition = Some(match condition {
|
||||
None => equal,
|
||||
Some(previous) => {
|
||||
let both = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::LogicalAnd,
|
||||
Some(bool_type),
|
||||
Some(both),
|
||||
vec![Operand::IdRef(previous), Operand::IdRef(equal)],
|
||||
));
|
||||
both
|
||||
}
|
||||
});
|
||||
}
|
||||
let condition = condition.expect("multidynamic field load has at least two indices");
|
||||
let selected = if ordinal + 1 == values.len() {
|
||||
result
|
||||
} else {
|
||||
self.fresh()
|
||||
};
|
||||
instructions.push(Self::inst(
|
||||
Op::Select,
|
||||
Some(result_type),
|
||||
Some(selected),
|
||||
vec![
|
||||
Operand::IdRef(condition),
|
||||
Operand::IdRef(stored_id),
|
||||
Operand::IdRef(current),
|
||||
],
|
||||
));
|
||||
current = selected;
|
||||
|
||||
let ordinal_id = self.const_int(selector_bits, ordinal as u64)?;
|
||||
let selected_ordinal = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::Select,
|
||||
Some(selector_type),
|
||||
Some(selected_ordinal),
|
||||
vec![
|
||||
Operand::IdRef(condition),
|
||||
Operand::IdRef(ordinal_id),
|
||||
Operand::IdRef(selector),
|
||||
],
|
||||
));
|
||||
selector = selected_ordinal;
|
||||
}
|
||||
if values.len() == 1 {
|
||||
instructions.push(Self::inst(
|
||||
Op::CopyObject,
|
||||
Some(result_type),
|
||||
Some(result),
|
||||
vec![Operand::IdRef(current)],
|
||||
));
|
||||
}
|
||||
|
||||
self.record_pointer_meta(result_name.to_string(), pointer_meta);
|
||||
self.dynamic_pointer_tables.insert(
|
||||
result_name.to_string(),
|
||||
DynamicPointerTable {
|
||||
selector,
|
||||
selector_bits,
|
||||
entries: values
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(ordinal, (_, value))| (ordinal as u32, value))
|
||||
.collect(),
|
||||
},
|
||||
);
|
||||
if !self.pointer_phi_values.is_empty() && !self.pointer_nullness.contains_key(result_name) {
|
||||
let is_null = self.const_bool(false)?;
|
||||
self.record_pointer_nullness(result_name.to_string(), is_null);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn emit_dynamic_pointer_table_gep(
|
||||
&mut self,
|
||||
name: &str,
|
||||
@@ -431,11 +628,6 @@ impl Emitter {
|
||||
return Ok(false);
|
||||
};
|
||||
|
||||
let index_ty = self.resolve_type(&table.index.ty)?;
|
||||
let LlType::Int(index_bits) = index_ty else {
|
||||
return Ok(false);
|
||||
};
|
||||
let index_id = self.value_id_in(&table.index.value, &table.index.ty, instructions)?;
|
||||
let result_type = self.ptr_type_id(storage, &pointee)?;
|
||||
let bool_type = self.type_id(&LlType::Bool)?;
|
||||
let result = self.result_id(name, &LlType::Ptr(addrspace))?;
|
||||
@@ -461,13 +653,13 @@ impl Emitter {
|
||||
indices,
|
||||
instructions,
|
||||
)?;
|
||||
let index_const = self.const_int(index_bits, *stored_index as u64)?;
|
||||
let index_const = self.const_int(table.selector_bits, *stored_index as u64)?;
|
||||
let is_entry = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::IEqual,
|
||||
Some(bool_type),
|
||||
Some(is_entry),
|
||||
vec![Operand::IdRef(index_id), Operand::IdRef(index_const)],
|
||||
vec![Operand::IdRef(table.selector), Operand::IdRef(index_const)],
|
||||
));
|
||||
let selected = if entry_idx + 1 == table.entries.len() {
|
||||
result
|
||||
|
||||
@@ -3,6 +3,107 @@
|
||||
use super::*;
|
||||
|
||||
impl Emitter {
|
||||
pub(in crate::native::emitter) fn emit_vector_as_scalar_array_store(
|
||||
&mut self,
|
||||
object: &TypedValue,
|
||||
ptr: &TypedValue,
|
||||
pointee: &LlType,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<bool, String> {
|
||||
let object_ty = self.resolve_type(&object.ty)?;
|
||||
let (LlType::Vector(vector_elem, vector_len), LlType::Array(array_elem, array_len)) =
|
||||
(&object_ty, pointee)
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
if vector_len != array_len || !types_compatible(vector_elem, array_elem) {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
// LLVM permits a vector store through an opaque pointer whose allocation is an equivalent
|
||||
// fixed scalar array. Rebuild the array value lane-for-lane so the SPIR-V store's object
|
||||
// type exactly matches its pointer pointee.
|
||||
let object_id = self.value_id_in(&object.value, &object.ty, instructions)?;
|
||||
let elem_type = self.type_id(vector_elem)?;
|
||||
let mut elements = Vec::with_capacity(*vector_len as usize);
|
||||
for lane in 0..*vector_len {
|
||||
let value = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::CompositeExtract,
|
||||
Some(elem_type),
|
||||
Some(value),
|
||||
vec![Operand::IdRef(object_id), Operand::LiteralBit32(lane)],
|
||||
));
|
||||
elements.push(Operand::IdRef(value));
|
||||
}
|
||||
let array_type = self.type_id(pointee)?;
|
||||
let array = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::CompositeConstruct,
|
||||
Some(array_type),
|
||||
Some(array),
|
||||
elements,
|
||||
));
|
||||
let ptr_id = self.value_id(&ptr.value, &ptr.ty)?;
|
||||
instructions.push(Self::inst(
|
||||
Op::Store,
|
||||
None,
|
||||
None,
|
||||
vec![Operand::IdRef(ptr_id), Operand::IdRef(array)],
|
||||
));
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn emit_scalar_array_as_vector_load(
|
||||
&mut self,
|
||||
result: Word,
|
||||
pointee: &LlType,
|
||||
result_ty: &LlType,
|
||||
ptr: Word,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<bool, String> {
|
||||
let (LlType::Array(array_elem, array_len), LlType::Vector(vector_elem, vector_len)) =
|
||||
(pointee, result_ty)
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
if array_len != vector_len || !types_compatible(array_elem, vector_elem) {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
// LLVM permits a vector load through an opaque pointer whose allocation is an equivalent
|
||||
// fixed scalar array. Logical SPIR-V cannot bitcast the pointer or the aggregate value, so
|
||||
// load the array and rebuild the vector lane-for-lane.
|
||||
let array_type = self.type_id(pointee)?;
|
||||
let loaded = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::Load,
|
||||
Some(array_type),
|
||||
Some(loaded),
|
||||
vec![Operand::IdRef(ptr)],
|
||||
));
|
||||
let elem_type = self.type_id(vector_elem)?;
|
||||
let mut lanes = Vec::with_capacity(*vector_len as usize);
|
||||
for lane in 0..*vector_len {
|
||||
let value = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::CompositeExtract,
|
||||
Some(elem_type),
|
||||
Some(value),
|
||||
vec![Operand::IdRef(loaded), Operand::LiteralBit32(lane)],
|
||||
));
|
||||
lanes.push(Operand::IdRef(value));
|
||||
}
|
||||
let vector_type = self.type_id(result_ty)?;
|
||||
instructions.push(Self::inst(
|
||||
Op::CompositeConstruct,
|
||||
Some(vector_type),
|
||||
Some(result),
|
||||
lanes,
|
||||
));
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn emit_narrowing_vector_store(
|
||||
&mut self,
|
||||
object: &TypedValue,
|
||||
@@ -703,10 +804,10 @@ impl Emitter {
|
||||
))
|
||||
}
|
||||
};
|
||||
if storage != StorageClass::Function
|
||||
&& storage != StorageClass::Workgroup
|
||||
&& !(storage == StorageClass::Private && self.is_imageblock_scratch_pointer(&ptr.value))
|
||||
{
|
||||
if !matches!(
|
||||
storage,
|
||||
StorageClass::Function | StorageClass::Workgroup | StorageClass::Private
|
||||
) {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some((scalar_ty, access_path)) = first_scalar_access_path(pointee) else {
|
||||
|
||||
@@ -41,7 +41,7 @@ impl Emitter {
|
||||
.as_ref()
|
||||
.and_then(|block| self.branch_merges_by_header.get(block))
|
||||
.cloned();
|
||||
let merge = if self.construct_tree {
|
||||
let merge = if self.branch_merges_header_only {
|
||||
header_merge
|
||||
} else {
|
||||
header_merge.or_else(|| {
|
||||
|
||||
@@ -2,82 +2,24 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(in crate::native::emitter) fn block_dominators(
|
||||
pub(in crate::native::emitter) fn emitted_block_dominators(
|
||||
blocks: &[Block],
|
||||
) -> HashMap<Word, HashSet<Word>> {
|
||||
) -> crate::native::cfg::EmittedDominators {
|
||||
let labels = blocks
|
||||
.iter()
|
||||
.filter_map(|block| block.label.as_ref()?.result_id)
|
||||
.collect::<Vec<_>>();
|
||||
let Some(entry) = labels.first().copied() else {
|
||||
return HashMap::new();
|
||||
};
|
||||
let label_indices = labels
|
||||
let entry = labels.first().copied().unwrap_or_default();
|
||||
let successors = blocks
|
||||
.iter()
|
||||
.copied()
|
||||
.enumerate()
|
||||
.map(|(idx, label)| (label, idx))
|
||||
.filter_map(|block| {
|
||||
Some((
|
||||
block.label.as_ref()?.result_id?,
|
||||
cloned_block_successors(block),
|
||||
))
|
||||
})
|
||||
.collect::<HashMap<_, _>>();
|
||||
let word_len = labels.len().div_ceil(u64::BITS as usize);
|
||||
let mut full = vec![u64::MAX; word_len];
|
||||
clear_unused_bits(&mut full, labels.len());
|
||||
let mut predecessors = vec![Vec::<usize>::new(); labels.len()];
|
||||
for block in blocks {
|
||||
let Some(label) = block.label.as_ref().and_then(|label| label.result_id) else {
|
||||
continue;
|
||||
};
|
||||
let Some(label_idx) = label_indices.get(&label).copied() else {
|
||||
continue;
|
||||
};
|
||||
for successor in cloned_block_successors(block) {
|
||||
if let Some(successor_idx) = label_indices.get(&successor).copied() {
|
||||
predecessors[successor_idx].push(label_idx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut dominators = vec![full.clone(); labels.len()];
|
||||
dominators[0] = vec![0; word_len];
|
||||
set_bit(&mut dominators[0], 0);
|
||||
|
||||
loop {
|
||||
let mut changed = false;
|
||||
for idx in 1..labels.len() {
|
||||
let mut next = if let Some((first, rest)) = predecessors[idx].split_first() {
|
||||
let mut out = dominators[*first].clone();
|
||||
for pred in rest {
|
||||
for word in 0..word_len {
|
||||
out[word] &= dominators[*pred][word];
|
||||
}
|
||||
}
|
||||
out
|
||||
} else {
|
||||
vec![0; word_len]
|
||||
};
|
||||
set_bit(&mut next, idx);
|
||||
if dominators[idx] != next {
|
||||
dominators[idx] = next;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let mut out = HashMap::new();
|
||||
for (idx, label) in labels.iter().copied().enumerate() {
|
||||
let mut doms = HashSet::new();
|
||||
for (candidate_idx, candidate_label) in labels.iter().copied().enumerate() {
|
||||
if bit_is_set(&dominators[idx], candidate_idx) {
|
||||
doms.insert(candidate_label);
|
||||
}
|
||||
}
|
||||
out.insert(label, doms);
|
||||
}
|
||||
debug_assert!(out
|
||||
.get(&entry)
|
||||
.is_some_and(|doms| doms == &HashSet::from([entry])));
|
||||
out
|
||||
crate::native::cfg::EmittedDominators::new(entry, &labels, &successors)
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn block_value_defs(blocks: &[Block]) -> HashMap<Word, Word> {
|
||||
@@ -168,7 +110,7 @@ pub(in crate::native::emitter) fn materialization_operands_dominate_pred(
|
||||
target_label: Word,
|
||||
pred: Word,
|
||||
defs: &HashMap<Word, Word>,
|
||||
dominators: &HashMap<Word, HashSet<Word>>,
|
||||
dominators: &crate::native::cfg::EmittedDominators,
|
||||
) -> bool {
|
||||
for operand in &inst.operands {
|
||||
let Some(id) = id_ref_operand(operand) else {
|
||||
@@ -180,7 +122,7 @@ pub(in crate::native::emitter) fn materialization_operands_dominate_pred(
|
||||
let Some(def_label) = defs.get(&id).copied() else {
|
||||
continue;
|
||||
};
|
||||
if def_label == target_label || !label_dominates(dominators, def_label, pred) {
|
||||
if def_label == target_label || !dominators.dominates(def_label, pred) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,8 +15,12 @@ impl Emitter {
|
||||
&mut self,
|
||||
blocks: &mut [Block],
|
||||
) {
|
||||
// Relocating an instruction changes its defining block but never changes the CFG. Build the
|
||||
// compact dominator tree once; only the much smaller value-definition map must be refreshed
|
||||
// after a move. The former full dominator-set map was O(V^2) and rebuilt for every relocated
|
||||
// materialization, leaving hundreds of MiB of allocator high-water pages on large functions.
|
||||
let dominators = emitted_block_dominators(blocks);
|
||||
loop {
|
||||
let dominators = block_dominators(blocks);
|
||||
let defs = block_value_defs(blocks);
|
||||
let mut moved = false;
|
||||
'scan: for target_idx in 0..blocks.len() {
|
||||
@@ -75,5 +79,24 @@ impl Emitter {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// A non-phi instruction can remain between phis even when it is not itself a phi incoming
|
||||
// materialization (for example, index arithmetic rematerialized for an earlier pointer phi in
|
||||
// the same block). Every OpPhi semantically executes at block entry and its operands come from
|
||||
// predecessor edges, so stable-partitioning the residual phis ahead of ordinary instructions is
|
||||
// the canonical SPIR-V order. Materializations that actually feed a phi were relocated by the
|
||||
// dominance-checked loop above first; any unsupported same-block dependency remains invalid and
|
||||
// is still rejected by the caller's module-level validation gate.
|
||||
for block in blocks {
|
||||
if !has_non_leading_phi(block) {
|
||||
continue;
|
||||
}
|
||||
let instructions = std::mem::take(&mut block.instructions);
|
||||
let (mut phis, rest): (Vec<_>, Vec<_>) = instructions
|
||||
.into_iter()
|
||||
.partition(|inst| inst.class.opcode == Op::Phi);
|
||||
phis.extend(rest);
|
||||
block.instructions = phis;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,5 @@
|
||||
use super::*;
|
||||
use crate::native::cfg::graph::{
|
||||
bit_is_set, clear_unused_bits, set_bit, spirv_block_successors as cloned_block_successors,
|
||||
spirv_label_dominates as label_dominates,
|
||||
};
|
||||
use crate::native::cfg::graph::spirv_block_successors as cloned_block_successors;
|
||||
|
||||
mod loop_continue;
|
||||
mod merge_helpers;
|
||||
|
||||
+214
-20
@@ -39,6 +39,8 @@ impl Emitter {
|
||||
.map(|((_func, name), pointee)| (name.clone(), pointee.clone()))
|
||||
.collect();
|
||||
self.pointer_nullness.clear();
|
||||
self.bda_inttoptr_sources.clear();
|
||||
self.bda_direct_addresses.clear();
|
||||
self.pointer_payload_words.clear();
|
||||
self.pointer_payload_values.clear();
|
||||
self.pointer_phi_values.clear();
|
||||
@@ -85,7 +87,24 @@ impl Emitter {
|
||||
.enumerate()
|
||||
.map(|(index, (name, ty))| self.param_type_id(&f.name, index, name, ty))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let fn_ty = self.function_type_id(ret_id, ¶m_types);
|
||||
let nullness_params = f
|
||||
.params
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(index, _)| {
|
||||
self.function_param_nullness
|
||||
.contains(&(f.name.clone(), *index))
|
||||
})
|
||||
.map(|(index, (name, _))| (index, name.clone()))
|
||||
.collect::<Vec<_>>();
|
||||
let bool_type = (!nullness_params.is_empty())
|
||||
.then(|| self.type_id(&LlType::Bool))
|
||||
.transpose()?;
|
||||
let mut function_param_types = param_types.clone();
|
||||
if let Some(bool_type) = bool_type {
|
||||
function_param_types.extend(std::iter::repeat_n(bool_type, nullness_params.len()));
|
||||
}
|
||||
let fn_ty = self.function_type_id(ret_id, &function_param_types);
|
||||
|
||||
let func_id = *self
|
||||
.function_ids
|
||||
@@ -100,7 +119,7 @@ impl Emitter {
|
||||
Operand::LiteralString(f.name.clone()),
|
||||
],
|
||||
));
|
||||
let mut params = Vec::with_capacity(f.params.len());
|
||||
let mut params = Vec::with_capacity(function_param_types.len());
|
||||
for (param_index, ((name, ty), type_id)) in
|
||||
f.params.iter().zip(param_types.iter()).enumerate()
|
||||
{
|
||||
@@ -163,6 +182,15 @@ impl Emitter {
|
||||
.cloned()
|
||||
.unwrap_or_else(|| RawBufferOffset::root(name.clone(), addrspace));
|
||||
raw.root = name.clone();
|
||||
if self.bda_device_pointers
|
||||
&& addrspace == 1
|
||||
&& !self.ir.entry_functions.contains(&f.name)
|
||||
{
|
||||
raw.device_addr_base = Some(id);
|
||||
self.used_device_address = true;
|
||||
self.pointer_storage
|
||||
.insert(name.clone(), StorageClass::PhysicalStorageBuffer);
|
||||
}
|
||||
self.raw_offsets.insert(name.clone(), raw);
|
||||
}
|
||||
}
|
||||
@@ -173,6 +201,16 @@ impl Emitter {
|
||||
}
|
||||
self.param_values.insert(name.clone());
|
||||
}
|
||||
for (_, name) in nullness_params {
|
||||
let id = self.fresh();
|
||||
params.push(Self::inst(
|
||||
Op::FunctionParameter,
|
||||
bool_type,
|
||||
Some(id),
|
||||
vec![],
|
||||
));
|
||||
self.record_pointer_nullness(name, id);
|
||||
}
|
||||
|
||||
// T5/T8 keystone: seed every block's typed carrier from its lines at SPLIT time — BEFORE
|
||||
// `lower_unstructured_switches` — so no window exists in which a structurizer reader sees an
|
||||
@@ -201,13 +239,27 @@ impl Emitter {
|
||||
// intermediate bypasses them.
|
||||
let relooper_feed = self.relooper_feed;
|
||||
if crate::env_vars::why() && !relooper_feed {
|
||||
match crate::native::cfg::structured_reject_reason(&body_blocks) {
|
||||
None => eprintln!("WHY ADMIT"),
|
||||
Some(r) => eprintln!("WHY REJECT {r}"),
|
||||
if body_blocks.len() <= crate::native::cfg::CROSS_ARM_EDGE_MAX_BLOCKS {
|
||||
match crate::native::cfg::structured_reject_reason(&body_blocks) {
|
||||
None => eprintln!("WHY ADMIT"),
|
||||
Some(r) => eprintln!("WHY REJECT {r}"),
|
||||
}
|
||||
} else {
|
||||
eprintln!(
|
||||
"WHY LARGE-CFG blocks={} local-reject-replay=skipped",
|
||||
body_blocks.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
let mut structured_active = false;
|
||||
let mut construct_tree_plan = None;
|
||||
// Planning is pure for a fixed `body_blocks` graph and can dominate translation time on
|
||||
// generated functions. Carry the result through the decision tree and invalidate it only
|
||||
// when a retry actually rewrites the CFG; do not re-run the full ladder merely to ask the
|
||||
// same admission question at a later branch.
|
||||
let mut ordinary_plan = (!relooper_feed)
|
||||
.then(|| crate::native::cfg::structured_plan(&body_blocks))
|
||||
.flatten();
|
||||
if !relooper_feed {
|
||||
// R2 cross-arm restructure — produces a CANDIDATE, adopted at the translate level ONLY if
|
||||
// the whole module then passes spirv-val (`self.cfg_restructure`, set by the
|
||||
@@ -221,16 +273,26 @@ impl Emitter {
|
||||
// which is exactly why adoption is gated on spirv-val at the caller, not on admission here.
|
||||
// The DEFAULT emit leaves `cfg_restructure` false, so a reject emits its inferred merges
|
||||
// unrepaired (post-W4) and an admitting case can never be hijacked.
|
||||
if (self.cfg_restructure || self.construct_tree)
|
||||
&& body_blocks.len() <= crate::native::cfg::CROSS_ARM_EDGE_MAX_BLOCKS
|
||||
&& crate::native::cfg::structured_plan(&body_blocks).is_none()
|
||||
if (self.construct_tree
|
||||
|| (self.cfg_restructure
|
||||
&& body_blocks.len() <= crate::native::cfg::CROSS_ARM_EDGE_MAX_BLOCKS))
|
||||
&& ordinary_plan.is_none()
|
||||
{
|
||||
let mut candidate = body_blocks.clone();
|
||||
let mut candidate_changed = false;
|
||||
let mut construct_tree_applied = false;
|
||||
if self.construct_tree {
|
||||
// The own-arm/straddle recognizers are local clone prepasses. Each begins by running
|
||||
// the full source-CFG reject classifier and can retain rewritten candidates; on a
|
||||
// large graph that duplicates the very planner work the global ownership tier exists
|
||||
// to replace. Keep those bounded like the other local clone machinery and send large
|
||||
// functions straight to the raw construct tree below.
|
||||
if self.construct_tree
|
||||
&& body_blocks.len() <= crate::native::cfg::CROSS_ARM_EDGE_MAX_BLOCKS
|
||||
{
|
||||
match crate::native::cfg::renest_cond_phi_shared_own_arm(&candidate) {
|
||||
Ok(Some(renested)) => {
|
||||
candidate = renested;
|
||||
candidate_changed = true;
|
||||
construct_tree_applied = true;
|
||||
construct_tree_plan =
|
||||
crate::native::cfg::structured_plan_construct_tree(&candidate);
|
||||
@@ -249,6 +311,7 @@ impl Emitter {
|
||||
match crate::native::cfg::renest_straddle_loop_merge(&candidate) {
|
||||
Ok(Some(renested)) => {
|
||||
candidate = renested;
|
||||
candidate_changed = true;
|
||||
construct_tree_applied = true;
|
||||
construct_tree_plan =
|
||||
crate::native::cfg::structured_plan_construct_tree(&candidate);
|
||||
@@ -265,6 +328,37 @@ impl Emitter {
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.construct_tree && !construct_tree_applied {
|
||||
// The global ownership planner is useful even when neither optional pre-renesting
|
||||
// transform changes the graph, and it is the primary path for large CFGs whose
|
||||
// local recognizers are deliberately skipped above.
|
||||
construct_tree_plan =
|
||||
crate::native::cfg::structured_plan_construct_tree(&candidate);
|
||||
if crate::env_vars::why() {
|
||||
if let Some(plan) = &construct_tree_plan {
|
||||
eprintln!(
|
||||
"WHY-CONSTRUCT-TREE function={} raw plan-admit blocks={} switches={}",
|
||||
f.name,
|
||||
plan.blocks.len(),
|
||||
plan.switch_merges.len()
|
||||
);
|
||||
} else {
|
||||
eprintln!("WHY-CONSTRUCT-TREE function={} raw plan-decline", f.name);
|
||||
}
|
||||
}
|
||||
if crate::env_vars::why() && construct_tree_plan.is_none() {
|
||||
// The detailed witness deliberately replays several planner variants. Keep it
|
||||
// for the small graphs it was built to explain; on a global CFG the SPI
|
||||
// breadcrumbs already identify the exact rejecting header.
|
||||
if candidate.len() <= crate::native::cfg::CROSS_ARM_EDGE_MAX_BLOCKS {
|
||||
for witness in
|
||||
crate::native::cfg::construct_tree_gate_witness_lines(&candidate)
|
||||
{
|
||||
eprintln!("WHY-CONSTRUCT-TREE {witness}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Straddle-loop-merge restructure first: give a loop whose exit merge straddles an
|
||||
// enclosing early-return guard its OWN pass-through merge, so the construct boundaries
|
||||
// no longer invert (05/MPSRNNBreakUpToOutputVecs). Runs before the cross-arm passes so
|
||||
@@ -274,6 +368,7 @@ impl Emitter {
|
||||
crate::native::cfg::restructure_straddle_loop_merges(&candidate)
|
||||
{
|
||||
candidate = destraddled;
|
||||
candidate_changed = true;
|
||||
}
|
||||
}
|
||||
// Merge-PRESERVING dominated-region privatization first: clones each cross-arm's
|
||||
@@ -287,49 +382,93 @@ impl Emitter {
|
||||
crate::native::cfg::privatize_region_cross_arm(&candidate);
|
||||
if region_privatized.len() != candidate.len() {
|
||||
candidate = region_privatized;
|
||||
candidate_changed = true;
|
||||
}
|
||||
if let Some(cloned) = crate::native::cfg::clone_cross_arm_shared(&candidate) {
|
||||
candidate = cloned;
|
||||
candidate_changed = true;
|
||||
}
|
||||
if let Some(lowered) = crate::native::cfg::lower_unreachable_to_ret(&candidate)
|
||||
{
|
||||
candidate = lowered;
|
||||
candidate_changed = true;
|
||||
}
|
||||
if let Some(unified) = crate::native::cfg::unify_returns(&candidate) {
|
||||
candidate = unified;
|
||||
candidate_changed = true;
|
||||
}
|
||||
}
|
||||
if crate::env_vars::why() {
|
||||
if crate::env_vars::why()
|
||||
&& candidate.len() <= crate::native::cfg::CROSS_ARM_EDGE_MAX_BLOCKS
|
||||
{
|
||||
match crate::native::cfg::structured_reject_reason(&candidate) {
|
||||
None => eprintln!("WHY-CANDIDATE ADMIT"),
|
||||
Some(r) => eprintln!("WHY-CANDIDATE REJECT {r}"),
|
||||
}
|
||||
}
|
||||
if construct_tree_plan.is_some()
|
||||
|| crate::native::cfg::structured_plan(&candidate).is_some()
|
||||
{
|
||||
let candidate_plan = (construct_tree_plan.is_none() && candidate_changed)
|
||||
.then(|| crate::native::cfg::structured_plan(&candidate))
|
||||
.flatten();
|
||||
if construct_tree_plan.is_some() || candidate_plan.is_some() {
|
||||
body_blocks = candidate;
|
||||
ordinary_plan = candidate_plan;
|
||||
}
|
||||
}
|
||||
if let Some(plan) =
|
||||
construct_tree_plan.or_else(|| crate::native::cfg::structured_plan(&body_blocks))
|
||||
{
|
||||
let construct_tree_active = construct_tree_plan.is_some();
|
||||
if let Some(plan) = construct_tree_plan.or(ordinary_plan) {
|
||||
body_blocks = plan.blocks;
|
||||
self.block_labels.clear();
|
||||
self.branch_merges = plan.branch_merges;
|
||||
self.branch_merges_by_header = plan.branch_merges_by_header;
|
||||
self.branch_merges_header_only = construct_tree_active;
|
||||
self.loop_merges = plan.loop_merges;
|
||||
self.switch_merges = plan.switch_merges;
|
||||
structured_active = true;
|
||||
}
|
||||
}
|
||||
if !structured_active {
|
||||
self.branch_merges_header_only = false;
|
||||
self.block_labels.clear();
|
||||
self.branch_merges_by_header.clear();
|
||||
if relooper_feed {
|
||||
self.branch_merges.clear();
|
||||
self.branch_merges = infer_direct_branch_merges(&body_blocks);
|
||||
self.loop_merges.clear();
|
||||
self.switch_merges = infer_switch_merges(&body_blocks);
|
||||
} else if body_blocks.len() > crate::native::cfg::CROSS_ARM_EDGE_MAX_BLOCKS {
|
||||
// Large rejected CFGs are owned by the construct-tree retry. Building heuristic
|
||||
// branch/loop transitive-closure maps here can exceed the memory budget before the
|
||||
// validator gets a chance to request that global structurizer. Preserve only branch
|
||||
// and switch ownership proved by direct local reconvergence; these linear subsets
|
||||
// handle ordinary case blocks and lowered switch ladders without restoring the
|
||||
// transitive-closure analysis. The intermediate is only a validation probe and cannot
|
||||
// be returned unless it independently passes.
|
||||
body_blocks = funnel_shared_branch_dispatches(&body_blocks);
|
||||
let mut refunnel_counter = body_blocks.len();
|
||||
if let Some(refunnelled) =
|
||||
refunnel_one_deep_shared_arm(&body_blocks, &mut refunnel_counter)
|
||||
{
|
||||
let plan = crate::native::cfg::structured_plan(&refunnelled).or_else(|| {
|
||||
crate::native::cfg::structured_plan_construct_tree(&refunnelled)
|
||||
});
|
||||
if let Some(plan) = plan {
|
||||
body_blocks = plan.blocks;
|
||||
self.block_labels.clear();
|
||||
self.branch_merges = plan.branch_merges;
|
||||
self.branch_merges
|
||||
.extend(infer_direct_branch_merges(&body_blocks));
|
||||
self.branch_merges_by_header = plan.branch_merges_by_header;
|
||||
self.loop_merges = plan.loop_merges;
|
||||
self.switch_merges = plan.switch_merges;
|
||||
structured_active = true;
|
||||
}
|
||||
}
|
||||
if !structured_active {
|
||||
self.branch_merges_by_header =
|
||||
infer_bounded_branch_merges_by_header(&body_blocks);
|
||||
self.branch_merges.clear();
|
||||
self.loop_merges.clear();
|
||||
self.switch_merges = infer_direct_switch_merges(&body_blocks);
|
||||
}
|
||||
} else {
|
||||
self.branch_merges = infer_branch_merges(&body_blocks);
|
||||
self.loop_merges = infer_loop_merges(&body_blocks);
|
||||
@@ -373,6 +512,16 @@ impl Emitter {
|
||||
self.forward_geps = tir.forward_geps.clone();
|
||||
for block in &tir.blocks {
|
||||
for inst in &block.insts {
|
||||
if self.bda_device_pointers && inst.opcode == "inttoptr" {
|
||||
if let (Some(result), Some(source)) = (
|
||||
inst.result.as_ref(),
|
||||
inst.operands
|
||||
.first()
|
||||
.and_then(|operand| operand.as_typed_value()),
|
||||
) {
|
||||
self.bda_inttoptr_sources.insert(result.clone(), source);
|
||||
}
|
||||
}
|
||||
if matches!(inst.cmp_predicate.as_deref(), Some("eq" | "ne")) {
|
||||
if let [crate::native::tir::TirOperand::Value {
|
||||
name: lhs_name,
|
||||
@@ -458,7 +607,40 @@ impl Emitter {
|
||||
.block_labels
|
||||
.get(&body_block.name)
|
||||
.ok_or_else(|| format!("native emitter: missing block {}", body_block.name))?;
|
||||
if crate::env_vars::spi_why() {
|
||||
self.module.debug_names.push(Self::inst(
|
||||
Op::Name,
|
||||
None,
|
||||
None,
|
||||
vec![
|
||||
Operand::IdRef(label),
|
||||
Operand::LiteralString(format!("block {}", body_block.name)),
|
||||
],
|
||||
));
|
||||
}
|
||||
let mut instructions = Vec::new();
|
||||
if self.bda_device_pointers && block_idx == 0 {
|
||||
let direct_buffers = self
|
||||
.raw_offsets
|
||||
.iter()
|
||||
.filter_map(|(name, raw)| {
|
||||
(raw.root == *name
|
||||
&& raw.const_off == 0
|
||||
&& raw.dyn_terms.is_empty()
|
||||
&& self.data_buffer_params.contains(name)
|
||||
&& self.direct_param_indices.contains_key(name))
|
||||
.then_some(name.clone())
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
for name in direct_buffers {
|
||||
let (low, high) =
|
||||
self.emit_direct_buffer_address_payload(&name, &mut instructions)?;
|
||||
let address =
|
||||
self.combine_pointer_payload_words(low, high, &mut instructions)?;
|
||||
self.pointer_payload_words.insert(name.clone(), (low, high));
|
||||
self.bda_direct_addresses.insert(name, address);
|
||||
}
|
||||
}
|
||||
let tir_block = &tir.blocks[block_idx];
|
||||
for inst in &tir_block.insts {
|
||||
// M-A4: dispatch each instruction through the graph-driven `emit_body_inst`, which
|
||||
@@ -491,7 +673,13 @@ impl Emitter {
|
||||
// materialization to its unique phi-incoming predecessor edge under dominance guards; never
|
||||
// reorders blocks or rewrites merges), load-bearing for the banked phi-materialization rows
|
||||
// (f2eeff34/e91bba5c/36f701c5/a4440d75/0691c869/f5d57f02) independent of the deleted roster.
|
||||
if structured_active {
|
||||
// The large-CFG direct-switch subset is also locally structured even though the complete
|
||||
// planner declined the surrounding function. Its pointer-phi materializations require this
|
||||
// same CFG-independent normalization before finish-time predecessor repair can consume them.
|
||||
if structured_active
|
||||
|| (body_blocks.len() > crate::native::cfg::CROSS_ARM_EDGE_MAX_BLOCKS
|
||||
&& !self.switch_merges.is_empty())
|
||||
{
|
||||
// The structurizer produces correct CFG structure but, like the default path, can still
|
||||
// materialize a pointer phi's incoming access-chain inside the phi's OWN block (between phi
|
||||
// nodes) — spirv-val rejects it ("OpPhi must appear within a non-entry block before all
|
||||
@@ -923,7 +1111,7 @@ impl Emitter {
|
||||
let Some(call_result) = &inst.emit_scan_call else {
|
||||
continue;
|
||||
};
|
||||
let call = call_result.as_ref().map_err(|e| e.clone())?;
|
||||
let call = call_result.as_ref().as_ref().map_err(|e| e.clone())?;
|
||||
let Some(callee) = functions_by_name.get(call.callee.as_str()) else {
|
||||
continue;
|
||||
};
|
||||
@@ -1262,6 +1450,12 @@ impl Emitter {
|
||||
.raw_buffer_params
|
||||
.contains(&(func.to_string(), name.to_string()))
|
||||
{
|
||||
if self.bda_device_pointers
|
||||
&& *addrspace == 1
|
||||
&& !self.ir.entry_functions.contains(func)
|
||||
{
|
||||
return self.type_id(&LlType::Int(64));
|
||||
}
|
||||
if *addrspace == 3 {
|
||||
if let Some(pointee) =
|
||||
self.concrete_vector_workgroup_raw_param_pointee(func, index, name)
|
||||
@@ -1570,7 +1764,7 @@ mod tests {
|
||||
BodyBlock {
|
||||
name: name.to_string(),
|
||||
role: crate::native::cfg::BlockRole::Normal,
|
||||
typed,
|
||||
typed: typed.map(Into::into),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -247,8 +247,11 @@ impl Emitter {
|
||||
let Some(_len) = self.raw_byte_array_root_len(raw) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let LlType::Int(bits) = ty else {
|
||||
return Ok(false);
|
||||
let (bits, needs_bitcast) = match ty {
|
||||
LlType::Int(bits) => (*bits, false),
|
||||
LlType::Float => (32, true),
|
||||
LlType::Half => (16, true),
|
||||
_ => return Ok(false),
|
||||
};
|
||||
if bits % 8 != 0 {
|
||||
return Ok(false);
|
||||
@@ -258,7 +261,9 @@ impl Emitter {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let result_ty = self.type_id(ty)?;
|
||||
let int_ty = LlType::Int(bits);
|
||||
let result_ty = self.type_id(&int_ty)?;
|
||||
let assembled_result = if needs_bitcast { self.fresh() } else { result };
|
||||
let mut acc = None;
|
||||
for byte in 0..byte_count {
|
||||
let loaded = self.emit_raw_byte_array_byte_load(
|
||||
@@ -266,7 +271,7 @@ impl Emitter {
|
||||
extra_byte + u64::from(byte),
|
||||
instructions,
|
||||
)?;
|
||||
let widened = if *bits == 8 {
|
||||
let widened = if bits == 8 {
|
||||
loaded
|
||||
} else {
|
||||
let widened = self.fresh();
|
||||
@@ -281,7 +286,7 @@ impl Emitter {
|
||||
let term = if byte == 0 {
|
||||
widened
|
||||
} else {
|
||||
let shift = self.const_signed_int(*bits, i64::from(byte * 8))?;
|
||||
let shift = self.const_signed_int(bits, i64::from(byte * 8))?;
|
||||
let shifted = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::ShiftLeftLogical,
|
||||
@@ -293,7 +298,7 @@ impl Emitter {
|
||||
};
|
||||
acc = Some(if let Some(prev) = acc {
|
||||
let combined = if byte + 1 == byte_count {
|
||||
result
|
||||
assembled_result
|
||||
} else {
|
||||
self.fresh()
|
||||
};
|
||||
@@ -308,11 +313,11 @@ impl Emitter {
|
||||
term
|
||||
});
|
||||
}
|
||||
if acc != Some(result) {
|
||||
if acc != Some(assembled_result) {
|
||||
instructions.push(Self::inst(
|
||||
Op::CopyObject,
|
||||
Some(result_ty),
|
||||
Some(result),
|
||||
Some(assembled_result),
|
||||
vec![Operand::IdRef(acc.ok_or_else(|| {
|
||||
"native emitter: raw byte-array integer load produced no accumulator \
|
||||
(byte count must be >= 1)"
|
||||
@@ -320,6 +325,15 @@ impl Emitter {
|
||||
})?)],
|
||||
));
|
||||
}
|
||||
if needs_bitcast {
|
||||
let value_ty = self.type_id(ty)?;
|
||||
instructions.push(Self::inst(
|
||||
Op::Bitcast,
|
||||
Some(value_ty),
|
||||
Some(result),
|
||||
vec![Operand::IdRef(assembled_result)],
|
||||
));
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
|
||||
@@ -142,14 +142,36 @@ impl Emitter {
|
||||
|
||||
let lhs_ty = self.resolve_type(&lhs.ty)?;
|
||||
let rhs_ty = self.resolve_type(&rhs.ty)?;
|
||||
if lhs_ty != rhs_ty || !matches!(lhs_ty, LlType::Int(_)) {
|
||||
let (LlType::Int(lhs_bits), LlType::Int(rhs_bits)) = (&lhs_ty, &rhs_ty) else {
|
||||
return Err(format!(
|
||||
"native emitter: cannot compose GEP indices with types {lhs_ty:?} and {rhs_ty:?}"
|
||||
));
|
||||
}
|
||||
let result_type = self.type_id(&lhs_ty)?;
|
||||
let lhs_id = self.value_id(&lhs.value, &lhs.ty)?;
|
||||
let rhs_id = self.value_id(&rhs.value, &rhs.ty)?;
|
||||
};
|
||||
// LLVM permits each GEP index to choose its own integer width. Once two successive GEPs are
|
||||
// linearized into one index, perform their addition at the wider width. GEP indices are
|
||||
// signed offsets, so a narrower dynamic term is sign-extended exactly as it is in the BDA
|
||||
// byte-address materializer. Rejecting i64+i32 here stranded otherwise representable device
|
||||
// pointer walks before the BDA retry could validate them.
|
||||
let result_bits = (*lhs_bits).max(*rhs_bits);
|
||||
let result_ty = LlType::Int(result_bits);
|
||||
let result_type = self.type_id(&result_ty)?;
|
||||
let lhs_original = self.value_id(&lhs.value, &lhs.ty)?;
|
||||
let rhs_original = self.value_id(&rhs.value, &rhs.ty)?;
|
||||
let mut widen = |id, bits| {
|
||||
if bits == result_bits {
|
||||
return id;
|
||||
}
|
||||
let widened = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::SConvert,
|
||||
Some(result_type),
|
||||
Some(widened),
|
||||
vec![Operand::IdRef(id)],
|
||||
));
|
||||
widened
|
||||
};
|
||||
let lhs_id = widen(lhs_original, *lhs_bits);
|
||||
let rhs_id = widen(rhs_original, *rhs_bits);
|
||||
let result = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::IAdd,
|
||||
@@ -158,17 +180,18 @@ impl Emitter {
|
||||
vec![Operand::IdRef(lhs_id), Operand::IdRef(rhs_id)],
|
||||
));
|
||||
let name = format!("%air.gepidx.{result}");
|
||||
self.values.insert(name.clone(), (result, lhs_ty.clone()));
|
||||
self.values
|
||||
.insert(name.clone(), (result, result_ty.clone()));
|
||||
self.record_int_alignment(
|
||||
&name,
|
||||
&lhs_ty,
|
||||
&result_ty,
|
||||
add_int_alignment(
|
||||
self.int_value_alignment(&lhs.value),
|
||||
self.int_value_alignment(&rhs.value),
|
||||
),
|
||||
);
|
||||
Ok(TypedValue {
|
||||
ty: lhs_ty,
|
||||
ty: result_ty,
|
||||
value: LlValue::Local(name),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -298,12 +298,9 @@ impl Emitter {
|
||||
let nbytes = bits / 8;
|
||||
let uchar_ty = self.type_id(&LlType::Int(8))?;
|
||||
let ptr_ty = self.ptr_type_id(storage, &LlType::Int(8))?;
|
||||
// Accumulate in the integer width we bitcast from (u32 for <=32-bit results, u64 for 64-bit).
|
||||
let acc_ty_ll = if bits <= 32 {
|
||||
LlType::Int(32)
|
||||
} else {
|
||||
LlType::Int(64)
|
||||
};
|
||||
// Accumulate in the exact integer width we bitcast from. In particular, a half must be
|
||||
// assembled as u16: SPIR-V OpBitcast requires equal total bit widths.
|
||||
let acc_ty_ll = LlType::Int(bits);
|
||||
let acc_ty = self.type_id(&acc_ty_ll)?;
|
||||
let mut acc: Option<Word> = None;
|
||||
for k in 0..nbytes {
|
||||
|
||||
@@ -124,9 +124,47 @@ impl Emitter {
|
||||
word_index: Word,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<(Word, StorageClass), String> {
|
||||
let root_id = self.raw_root_value_id(raw)?;
|
||||
let storage = self.raw_access_storage(raw)?;
|
||||
let ptr_ty = self.ptr_type_id(storage, &LlType::Int(32))?;
|
||||
if let Some(base_address) = raw.device_addr_base {
|
||||
if storage != StorageClass::PhysicalStorageBuffer {
|
||||
return Err(format!(
|
||||
"native emitter: device-address raw word uses non-physical storage {storage:?}"
|
||||
));
|
||||
}
|
||||
let i64_ty = self.type_id(&LlType::Int(64))?;
|
||||
let index64 = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::UConvert,
|
||||
Some(i64_ty),
|
||||
Some(index64),
|
||||
vec![Operand::IdRef(word_index)],
|
||||
));
|
||||
let byte_offset = self.fresh();
|
||||
let four = self.const_signed_int(64, 4)?;
|
||||
instructions.push(Self::inst(
|
||||
Op::IMul,
|
||||
Some(i64_ty),
|
||||
Some(byte_offset),
|
||||
vec![Operand::IdRef(index64), Operand::IdRef(four)],
|
||||
));
|
||||
let address = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::IAdd,
|
||||
Some(i64_ty),
|
||||
Some(address),
|
||||
vec![Operand::IdRef(base_address), Operand::IdRef(byte_offset)],
|
||||
));
|
||||
let ptr = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::ConvertUToPtr,
|
||||
Some(ptr_ty),
|
||||
Some(ptr),
|
||||
vec![Operand::IdRef(address)],
|
||||
));
|
||||
return Ok((ptr, storage));
|
||||
}
|
||||
let root_id = self.raw_root_value_id(raw)?;
|
||||
let ptr = self.fresh();
|
||||
if storage == StorageClass::Private
|
||||
&& self
|
||||
|
||||
+396
-12
@@ -1,6 +1,8 @@
|
||||
use super::cfg::{
|
||||
block_index_by_label, id_ref_operand, infer_branch_merges, infer_loop_merges,
|
||||
infer_switch_merges, lower_unstructured_switches, LoopMergeInfo,
|
||||
block_index_by_label, funnel_shared_branch_dispatches, id_ref_operand,
|
||||
infer_bounded_branch_merges_by_header, infer_branch_merges, infer_direct_branch_merges,
|
||||
infer_direct_switch_merges, infer_loop_merges, infer_switch_merges,
|
||||
lower_unstructured_switches, refunnel_one_deep_shared_arm, LoopMergeInfo,
|
||||
};
|
||||
use super::ir::{
|
||||
LlDeclaration, LlFunction, LlGep, LlGlobal, LlModule, LlType, LlTypeCapability, LlValue,
|
||||
@@ -51,8 +53,8 @@ pub(super) struct Emitter {
|
||||
/// (`air.atomic.*.i32`) but are declared with a 32-bit-bitcastable *non*-integer scalar pointee
|
||||
/// (e.g. a `float` threadgroup scratch slot used for the atomic-min/max bit-pattern idiom).
|
||||
/// Under Logical addressing an integer atomic needs an `i32`-typed pointer to that exact memory,
|
||||
/// which — for a global — only exists if the variable itself is declared `i32`; the old path
|
||||
/// reinterpreted the float pointer with an illegal logical-pointer `OpBitcast`. So `emit_global`
|
||||
/// which — for a global — only exists if the variable itself is declared `i32`. Reinterpreting
|
||||
/// the float pointer would require an illegal logical-pointer `OpBitcast`, so `emit_global`
|
||||
/// declares these as `i32` instead, and the existing scalar value-reinterpret load/store paths
|
||||
/// (32-bit `OpBitcast` on the *value*) carry the float accesses. Computed structurally from the
|
||||
/// `air.atomic.*.i32` ABI symbol family before globals emit; excludes any global also accessed by
|
||||
@@ -80,6 +82,14 @@ pub(super) struct Emitter {
|
||||
pointer_pointees: HashMap<String, LlType>,
|
||||
local_alloca_pointees: HashMap<String, LlType>,
|
||||
pointer_nullness: HashMap<String, Word>,
|
||||
/// BDA-mode integer sources for `inttoptr` results in the current function. Collected from the
|
||||
/// typed graph before block emission so a loop-header address phi can reserve a backedge value
|
||||
/// whose `inttoptr` definition appears in the latch.
|
||||
bda_inttoptr_sources: HashMap<String, TypedValue>,
|
||||
/// Runtime 64-bit addresses for descriptor-rooted direct buffer parameters. In BDA mode these
|
||||
/// are materialized once in the entry block from the reflected buffer-address sidecar, then used
|
||||
/// as ordinary dominating integer values by address-domain pointer merges.
|
||||
bda_direct_addresses: HashMap<String, Word>,
|
||||
/// The two little-endian 32-bit words of a serialized 64-bit pointer loaded through a raw
|
||||
/// buffer view. Logical SPIR-V pointers cannot represent or compare this wire payload, so raw
|
||||
/// pointer equality and stores operate on these integer words instead.
|
||||
@@ -93,6 +103,10 @@ pub(super) struct Emitter {
|
||||
tir_phi_incomings: HashMap<String, Vec<(LlValue, String)>>,
|
||||
function_param_pointees: HashMap<(String, usize), LlType>,
|
||||
function_param_nonnull: HashSet<(String, usize)>,
|
||||
/// Residual helper pointer parameters whose authored LLVM nullness is observed. Logical SPIR-V
|
||||
/// pointers cannot carry a null value portably, so calls append one Boolean shadow for exactly
|
||||
/// these parameters and the callee binds that shadow to its ordinary pointer SSA name.
|
||||
function_param_nullness: HashSet<(String, usize)>,
|
||||
direct_param_values: HashSet<String>,
|
||||
direct_param_indices: HashMap<String, u32>,
|
||||
param_values: HashSet<String>,
|
||||
@@ -108,6 +122,10 @@ pub(super) struct Emitter {
|
||||
raw_offsets: HashMap<String, RawBufferOffset>,
|
||||
int_alignments: HashMap<String, u64>,
|
||||
unmodeled_pointers: HashSet<String>,
|
||||
/// AIR occasionally embeds a numeric Workgroup address directly in an atomic operand. Logical
|
||||
/// SPIR-V has no integer-to-Workgroup-pointer conversion, so preserve equality of identical
|
||||
/// numeric addresses with one module-scope atomic slot per address.
|
||||
workgroup_i32_addresses: HashMap<u64, Word>,
|
||||
/// SSA value names bound by `air.get_null_texture_*`. A strict subset of `unmodeled_pointers`
|
||||
/// (many other placeholders land there too), so `air.is_null_texture` keys on THIS set — a
|
||||
/// value synthesized as a null texture answers TRUE, everything else stays on the default path.
|
||||
@@ -116,6 +134,11 @@ pub(super) struct Emitter {
|
||||
block_labels: HashMap<String, Word>,
|
||||
branch_merges: HashMap<(String, String), String>,
|
||||
branch_merges_by_header: HashMap<String, String>,
|
||||
/// The current function was planned by the construct tree, whose merge ownership is keyed by
|
||||
/// header rather than by a potentially shared target pair. This is per-function provenance:
|
||||
/// enabling the construct-tree retry for the module does not change how normally planned helper
|
||||
/// functions look up their merges.
|
||||
branch_merges_header_only: bool,
|
||||
loop_merges: HashMap<String, LoopMergeInfo>,
|
||||
switch_merges: HashMap<String, String>,
|
||||
current_block: Option<String>,
|
||||
@@ -261,6 +284,8 @@ struct SelectedLoadPointer {
|
||||
cond: Word,
|
||||
true_ptr: Option<Word>,
|
||||
false_ptr: Option<Word>,
|
||||
true_storage: StorageClass,
|
||||
false_storage: StorageClass,
|
||||
pointee: LlType,
|
||||
true_raw: Option<RawBufferOffset>,
|
||||
false_raw: Option<RawBufferOffset>,
|
||||
@@ -272,7 +297,8 @@ struct SelectedLoadPointer {
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct DynamicPointerTable {
|
||||
index: TypedValue,
|
||||
selector: Word,
|
||||
selector_bits: u32,
|
||||
entries: Vec<(u32, TypedValue)>,
|
||||
}
|
||||
|
||||
@@ -383,6 +409,7 @@ impl Emitter {
|
||||
|
||||
pub(super) fn new(mut ir: LlModule) -> Self {
|
||||
ir.inline_simple_static_initializers();
|
||||
ir.fold_static_initializer_constants();
|
||||
ir.inline_ordinary_leaf_helpers();
|
||||
let mut module = Module::new();
|
||||
module.capabilities.push(Instruction::new(
|
||||
@@ -434,6 +461,8 @@ impl Emitter {
|
||||
pointer_pointees: HashMap::new(),
|
||||
local_alloca_pointees: HashMap::new(),
|
||||
pointer_nullness: HashMap::new(),
|
||||
bda_inttoptr_sources: HashMap::new(),
|
||||
bda_direct_addresses: HashMap::new(),
|
||||
pointer_payload_words: HashMap::new(),
|
||||
pointer_payload_values: HashSet::new(),
|
||||
pointer_phi_values: HashSet::new(),
|
||||
@@ -441,6 +470,7 @@ impl Emitter {
|
||||
tir_phi_incomings: HashMap::new(),
|
||||
function_param_pointees: HashMap::new(),
|
||||
function_param_nonnull: HashSet::new(),
|
||||
function_param_nullness: HashSet::new(),
|
||||
direct_param_values: HashSet::new(),
|
||||
direct_param_indices: HashMap::new(),
|
||||
param_values: HashSet::new(),
|
||||
@@ -451,11 +481,13 @@ impl Emitter {
|
||||
raw_offsets: HashMap::new(),
|
||||
int_alignments: HashMap::new(),
|
||||
unmodeled_pointers: HashSet::new(),
|
||||
workgroup_i32_addresses: HashMap::new(),
|
||||
null_texture_values: HashSet::new(),
|
||||
function_ids: HashMap::new(),
|
||||
block_labels: HashMap::new(),
|
||||
branch_merges: HashMap::new(),
|
||||
branch_merges_by_header: HashMap::new(),
|
||||
branch_merges_header_only: false,
|
||||
loop_merges: HashMap::new(),
|
||||
switch_merges: HashMap::new(),
|
||||
current_block: None,
|
||||
@@ -548,7 +580,7 @@ impl Emitter {
|
||||
let Some(call_result) = &inst.emit_scan_call else {
|
||||
continue;
|
||||
};
|
||||
let call = call_result.as_ref().map_err(|e| e.clone())?;
|
||||
let call = call_result.as_ref().as_ref().map_err(|e| e.clone())?;
|
||||
let Some(callee) = functions_by_name.get(&call.callee) else {
|
||||
continue;
|
||||
};
|
||||
@@ -608,7 +640,7 @@ impl Emitter {
|
||||
let Some(call_result) = &inst.emit_scan_call else {
|
||||
continue;
|
||||
};
|
||||
let call = call_result.as_ref().map_err(|e| e.clone())?;
|
||||
let call = call_result.as_ref().as_ref().map_err(|e| e.clone())?;
|
||||
let Some(callee) = functions_by_name.get(&call.callee) else {
|
||||
continue;
|
||||
};
|
||||
@@ -637,6 +669,82 @@ impl Emitter {
|
||||
Ok(all_nonnull)
|
||||
}
|
||||
|
||||
pub(super) fn infer_function_param_nullness(
|
||||
&self,
|
||||
functions: &[LlFunction],
|
||||
) -> Result<HashSet<(String, usize)>, String> {
|
||||
let function_param_nonnull = self.infer_function_param_nonnull(functions)?;
|
||||
let mut required = HashSet::new();
|
||||
for function in functions {
|
||||
for inst in function.carrier_insts() {
|
||||
if !matches!(inst.cmp_predicate.as_deref(), Some("eq" | "ne")) {
|
||||
continue;
|
||||
}
|
||||
let operands = inst
|
||||
.operands
|
||||
.iter()
|
||||
.map(crate::native::tir::TirOperand::as_typed_value)
|
||||
.collect::<Option<Vec<_>>>();
|
||||
let Some(operands) = operands else {
|
||||
continue;
|
||||
};
|
||||
let [lhs, rhs] = operands.as_slice() else {
|
||||
continue;
|
||||
};
|
||||
if !matches!(self.resolve_type(&lhs.ty)?, LlType::Ptr(_)) {
|
||||
continue;
|
||||
}
|
||||
let observed = match (&lhs.value, &rhs.value) {
|
||||
(LlValue::Zero, LlValue::Local(name))
|
||||
| (LlValue::Local(name), LlValue::Zero) => name,
|
||||
_ => continue,
|
||||
};
|
||||
if let Some(index) = function
|
||||
.params
|
||||
.iter()
|
||||
.position(|(name, _)| name == observed)
|
||||
{
|
||||
required.insert((function.name.clone(), index));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A helper may forward one of its parameters directly to another helper that observes
|
||||
// nullness. Propagate that ABI requirement back through direct parameter-to-parameter calls;
|
||||
// ordinary SSA aliases carry their already-recorded Boolean at emission time.
|
||||
let mut changed = true;
|
||||
while changed {
|
||||
changed = false;
|
||||
for function in functions {
|
||||
for inst in function.carrier_insts() {
|
||||
let Some(call) = inst.call.as_ref() else {
|
||||
continue;
|
||||
};
|
||||
for (callee_index, argument) in call.args.iter().enumerate() {
|
||||
if !required.contains(&(call.callee.clone(), callee_index)) {
|
||||
continue;
|
||||
}
|
||||
let LlValue::Local(argument_name) = &argument.value else {
|
||||
continue;
|
||||
};
|
||||
let Some(caller_index) = function
|
||||
.params
|
||||
.iter()
|
||||
.position(|(name, _)| name == argument_name)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
changed |= required.insert((function.name.clone(), caller_index));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
required.retain(|key| {
|
||||
!self.ir.entry_functions.contains(&key.0) && !function_param_nonnull.contains(key)
|
||||
});
|
||||
Ok(required)
|
||||
}
|
||||
|
||||
fn local_call_arg_nonnull_values(
|
||||
&self,
|
||||
function: &LlFunction,
|
||||
@@ -669,7 +777,7 @@ impl Emitter {
|
||||
}
|
||||
// `bitcast` carries the parsed src + dst TEXT (`convert_dst_type` stays emit-time); re-parse
|
||||
// the dst text to keep the reader's `parse_type(dst_text)? -> resolve_type?` propagation.
|
||||
if let Some((src, dst_text)) = &inst.bitcast {
|
||||
if let Some((src, dst_text)) = inst.bitcast.as_deref() {
|
||||
if matches!(self.resolve_type(&parse_type(dst_text)?)?, LlType::Ptr(_))
|
||||
&& self.call_arg_known_nonnull(&src.value, &nonnull)
|
||||
{
|
||||
@@ -679,7 +787,9 @@ impl Emitter {
|
||||
continue;
|
||||
}
|
||||
if let Some(gep) = &inst.gep {
|
||||
if self.call_arg_known_nonnull(&gep.base.value, &nonnull) {
|
||||
if self.call_arg_known_nonnull(&gep.base.value, &nonnull)
|
||||
|| self.inbounds_gep_has_nonzero_constant_offset(gep)?
|
||||
{
|
||||
nonnull.insert(name.clone());
|
||||
changed = true;
|
||||
}
|
||||
@@ -689,6 +799,22 @@ impl Emitter {
|
||||
Ok(nonnull)
|
||||
}
|
||||
|
||||
fn inbounds_gep_has_nonzero_constant_offset(&self, gep: &LlGep) -> Result<bool, String> {
|
||||
if !gep.inbounds {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(first) = const_index(gep.indices.first()) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let source_ty = self.resolve_type(&gep.source_ty)?;
|
||||
if first != 0 && self.raw_type_size_align(&source_ty)?.0 != 0 {
|
||||
return Ok(true);
|
||||
}
|
||||
Ok(self
|
||||
.constant_aggregate_gep_offset(&source_ty, &gep.indices[1..])?
|
||||
.is_some_and(|(offset, _)| offset != 0))
|
||||
}
|
||||
|
||||
fn call_arg_known_nonnull(&self, value: &LlValue, local_nonnull: &HashSet<String>) -> bool {
|
||||
match value {
|
||||
LlValue::Local(name) => local_nonnull.contains(name),
|
||||
@@ -727,7 +853,7 @@ impl Emitter {
|
||||
if pointees.contains_key(name) {
|
||||
continue;
|
||||
}
|
||||
if let Some((src, dst_text)) = &inst.bitcast {
|
||||
if let Some((src, dst_text)) = inst.bitcast.as_deref() {
|
||||
let dst_ty = self.resolve_type(&parse_type(dst_text)?)?;
|
||||
if matches!(dst_ty, LlType::Ptr(_)) {
|
||||
if let LlValue::Local(src_name) = &src.value {
|
||||
@@ -828,6 +954,7 @@ impl Emitter {
|
||||
self.emit_inner()?;
|
||||
self.record_air_struct_offsets(buffer_layouts);
|
||||
if self.used_device_address {
|
||||
self.lower_bda_null_aggregate_pointers()?;
|
||||
self.switch_to_physical_storage_buffer64();
|
||||
}
|
||||
Ok((self.module, self.emit_sidecar))
|
||||
@@ -848,6 +975,239 @@ impl Emitter {
|
||||
self.require_extension("SPV_KHR_physical_storage_buffer");
|
||||
}
|
||||
|
||||
/// PhysicalStorageBuffer64 does not permit logical pointers as aggregate values. Callback-free
|
||||
/// AIR intersection lowering can leave one such value behind as an opaque result field that is
|
||||
/// structurally always null. Re-type only fields reached exclusively by a null-pointer
|
||||
/// `OpCompositeInsert` to the integer address representation used by the BDA path. Any other use
|
||||
/// leaves the pointer untouched, so an unsupported live logical-pointer aggregate still fails
|
||||
/// validation rather than acquiring invented semantics.
|
||||
fn lower_bda_null_aggregate_pointers(&mut self) -> Result<(), String> {
|
||||
let null_pointers =
|
||||
self.module
|
||||
.types_global_values
|
||||
.iter()
|
||||
.filter_map(|inst| {
|
||||
(inst.class.opcode == Op::ConstantNull)
|
||||
.then_some((inst.result_id?, inst.result_type?))
|
||||
})
|
||||
.filter(|(_, ty)| {
|
||||
self.module.types_global_values.iter().any(|inst| {
|
||||
inst.class.opcode == Op::TypePointer && inst.result_id == Some(*ty)
|
||||
})
|
||||
})
|
||||
.collect::<HashMap<_, _>>();
|
||||
if null_pointers.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let type_defs = self
|
||||
.module
|
||||
.types_global_values
|
||||
.iter()
|
||||
.filter_map(|inst| inst.result_id.map(|id| (id, inst.clone())))
|
||||
.collect::<HashMap<_, _>>();
|
||||
let mut fields_by_null: HashMap<Word, Vec<(Word, usize)>> = HashMap::new();
|
||||
let mut unsupported_use = HashSet::new();
|
||||
for function in &self.module.functions {
|
||||
for inst in function
|
||||
.blocks
|
||||
.iter()
|
||||
.flat_map(|block| block.instructions.iter())
|
||||
{
|
||||
for (operand_index, operand) in inst.operands.iter().enumerate() {
|
||||
let Operand::IdRef(id) = operand else {
|
||||
continue;
|
||||
};
|
||||
let Some(pointer_ty) = null_pointers.get(id).copied() else {
|
||||
continue;
|
||||
};
|
||||
if inst.class.opcode != Op::CompositeInsert || operand_index != 0 {
|
||||
unsupported_use.insert(*id);
|
||||
continue;
|
||||
}
|
||||
let Some(mut aggregate_ty) = inst.result_type else {
|
||||
unsupported_use.insert(*id);
|
||||
continue;
|
||||
};
|
||||
let mut target = None;
|
||||
for index in inst.operands.iter().skip(2) {
|
||||
let Operand::LiteralBit32(member) = index else {
|
||||
target = None;
|
||||
break;
|
||||
};
|
||||
let Some(def) = type_defs.get(&aggregate_ty) else {
|
||||
target = None;
|
||||
break;
|
||||
};
|
||||
let Some(Operand::IdRef(member_ty)) = def.operands.get(*member as usize)
|
||||
else {
|
||||
target = None;
|
||||
break;
|
||||
};
|
||||
target = Some((aggregate_ty, *member as usize, *member_ty));
|
||||
aggregate_ty = *member_ty;
|
||||
}
|
||||
match target {
|
||||
Some((owner, member, leaf_ty)) if leaf_ty == pointer_ty => {
|
||||
fields_by_null.entry(*id).or_default().push((owner, member));
|
||||
}
|
||||
_ => {
|
||||
unsupported_use.insert(*id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fields_by_null.retain(|id, fields| !fields.is_empty() && !unsupported_use.contains(id));
|
||||
if fields_by_null.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let address_ty = self.type_id(&LlType::Int(64))?;
|
||||
let zero = self.const_signed_int(64, 0)?;
|
||||
let lowered_nulls = fields_by_null.keys().copied().collect::<HashSet<_>>();
|
||||
let mut address_values = lowered_nulls.clone();
|
||||
let mut lowered_fields = fields_by_null
|
||||
.into_values()
|
||||
.flatten()
|
||||
.collect::<HashSet<_>>();
|
||||
let result_types = self
|
||||
.module
|
||||
.types_global_values
|
||||
.iter()
|
||||
.chain(self.module.functions.iter().flat_map(|function| {
|
||||
function.parameters.iter().chain(
|
||||
function
|
||||
.blocks
|
||||
.iter()
|
||||
.flat_map(|block| block.instructions.iter()),
|
||||
)
|
||||
}))
|
||||
.filter_map(|inst| Some((inst.result_id?, inst.result_type?)))
|
||||
.collect::<HashMap<_, _>>();
|
||||
loop {
|
||||
let mut changed = false;
|
||||
for function in &self.module.functions {
|
||||
for inst in function
|
||||
.blocks
|
||||
.iter()
|
||||
.flat_map(|block| block.instructions.iter())
|
||||
{
|
||||
match inst.class.opcode {
|
||||
Op::CompositeExtract => {
|
||||
let Some(Operand::IdRef(composite)) = inst.operands.first() else {
|
||||
continue;
|
||||
};
|
||||
let Some(mut aggregate_ty) = result_types.get(composite).copied() else {
|
||||
continue;
|
||||
};
|
||||
let mut target = None;
|
||||
for index in inst.operands.iter().skip(1) {
|
||||
let Operand::LiteralBit32(member) = index else {
|
||||
target = None;
|
||||
break;
|
||||
};
|
||||
let Some(def) = type_defs.get(&aggregate_ty) else {
|
||||
target = None;
|
||||
break;
|
||||
};
|
||||
let Some(Operand::IdRef(member_ty)) =
|
||||
def.operands.get(*member as usize)
|
||||
else {
|
||||
target = None;
|
||||
break;
|
||||
};
|
||||
target = Some((aggregate_ty, *member as usize));
|
||||
aggregate_ty = *member_ty;
|
||||
}
|
||||
if target.is_some_and(|field| lowered_fields.contains(&field)) {
|
||||
if let Some(result) = inst.result_id {
|
||||
changed |= address_values.insert(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
Op::CompositeInsert => {
|
||||
let Some(Operand::IdRef(object)) = inst.operands.first() else {
|
||||
continue;
|
||||
};
|
||||
if !address_values.contains(object) {
|
||||
continue;
|
||||
}
|
||||
let Some(mut aggregate_ty) = inst.result_type else {
|
||||
continue;
|
||||
};
|
||||
let mut target = None;
|
||||
for index in inst.operands.iter().skip(2) {
|
||||
let Operand::LiteralBit32(member) = index else {
|
||||
target = None;
|
||||
break;
|
||||
};
|
||||
let Some(def) = type_defs.get(&aggregate_ty) else {
|
||||
target = None;
|
||||
break;
|
||||
};
|
||||
let Some(Operand::IdRef(member_ty)) =
|
||||
def.operands.get(*member as usize)
|
||||
else {
|
||||
target = None;
|
||||
break;
|
||||
};
|
||||
target = Some((aggregate_ty, *member as usize));
|
||||
aggregate_ty = *member_ty;
|
||||
}
|
||||
if let Some(field) = target {
|
||||
changed |= lowered_fields.insert(field);
|
||||
}
|
||||
}
|
||||
Op::CopyObject
|
||||
if inst.operands.iter().any(|operand| {
|
||||
matches!(operand, Operand::IdRef(id) if address_values.contains(id))
|
||||
}) =>
|
||||
{
|
||||
if let Some(result) = inst.result_id {
|
||||
changed |= address_values.insert(result);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
for inst in &mut self.module.types_global_values {
|
||||
let Some(owner) = inst.result_id else {
|
||||
continue;
|
||||
};
|
||||
for (member, operand) in inst.operands.iter_mut().enumerate() {
|
||||
if lowered_fields.contains(&(owner, member)) {
|
||||
*operand = Operand::IdRef(address_ty);
|
||||
}
|
||||
}
|
||||
}
|
||||
for function in &mut self.module.functions {
|
||||
for inst in function
|
||||
.blocks
|
||||
.iter_mut()
|
||||
.flat_map(|block| block.instructions.iter_mut())
|
||||
{
|
||||
if inst
|
||||
.result_id
|
||||
.is_some_and(|id| address_values.contains(&id))
|
||||
{
|
||||
inst.result_type = Some(address_ty);
|
||||
}
|
||||
for operand in &mut inst.operands {
|
||||
if matches!(operand, Operand::IdRef(id) if lowered_nulls.contains(id)) {
|
||||
*operand = Operand::IdRef(zero);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run the full emission for its side effect of populating `storage_snapshots` (one per function's
|
||||
/// final `pointer_storage`), and return them — the M1 storage-carrier measurement entry. Discards
|
||||
/// the module. Mirrors [`emit`] exactly except for the capture flag, so the snapshots reflect the
|
||||
@@ -907,6 +1267,7 @@ impl Emitter {
|
||||
}
|
||||
self.infer_function_param_pointees(&functions)?;
|
||||
self.function_param_nonnull = self.infer_function_param_nonnull(&functions)?;
|
||||
self.function_param_nullness = self.infer_function_param_nullness(&functions)?;
|
||||
for f in &functions {
|
||||
self.emit_function_with_raw_retry(f)?;
|
||||
}
|
||||
@@ -1001,12 +1362,29 @@ impl Emitter {
|
||||
|
||||
fn rewrite_scalar_pointer_arithmetic_access_chains(&mut self) {
|
||||
let mut pointer_storage = HashMap::new();
|
||||
let aggregate_types = self
|
||||
.module
|
||||
.types_global_values
|
||||
.iter()
|
||||
.filter(|inst| {
|
||||
matches!(
|
||||
inst.class.opcode,
|
||||
Op::TypeStruct | Op::TypeArray | Op::TypeRuntimeArray | Op::TypeMatrix
|
||||
)
|
||||
})
|
||||
.filter_map(|inst| inst.result_id)
|
||||
.collect::<HashSet<_>>();
|
||||
let mut pointer_pointees = HashMap::new();
|
||||
for inst in &self.module.types_global_values {
|
||||
if inst.class.opcode == Op::TypePointer {
|
||||
if let (Some(result), Some(Operand::StorageClass(storage))) =
|
||||
(inst.result_id, inst.operands.first())
|
||||
if let (
|
||||
Some(result),
|
||||
Some(Operand::StorageClass(storage)),
|
||||
Some(Operand::IdRef(pointee)),
|
||||
) = (inst.result_id, inst.operands.first(), inst.operands.get(1))
|
||||
{
|
||||
pointer_storage.insert(result, *storage);
|
||||
pointer_pointees.insert(result, *pointee);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1053,6 +1431,12 @@ impl Emitter {
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if pointer_pointees
|
||||
.get(&result_type)
|
||||
.is_some_and(|pointee| aggregate_types.contains(pointee))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some(Operand::IdRef(base)) = inst.operands.first() else {
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -165,6 +165,35 @@ impl Emitter {
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<bool, String> {
|
||||
match call.callee.as_str() {
|
||||
// AGX2 numbers threadgroup lanes in physical 16-wide cluster rows. Preserve a typed
|
||||
// sentinel here because the native emitter deliberately does not know Vulkan dispatch
|
||||
// geometry; the interface pass replaces it using LocalInvocationId + LocalSize.
|
||||
"llvm.agx2.cluster.num" => {
|
||||
if !call.args.is_empty() {
|
||||
return Err(format!(
|
||||
"native emitter: {} expects no operands",
|
||||
call.callee
|
||||
));
|
||||
}
|
||||
let result_ty = self.resolve_type(&call.ret)?;
|
||||
if result_ty != LlType::Int(32) {
|
||||
return Err(format!(
|
||||
"native emitter: {} returned {result_ty:?}, expected i32",
|
||||
call.callee
|
||||
));
|
||||
}
|
||||
let result_type = self.type_id(&result_ty)?;
|
||||
let result = self.result_id(name, &result_ty)?;
|
||||
let zero = self.const_uint(0)?;
|
||||
instructions.push(Self::inst(
|
||||
Op::CopyObject,
|
||||
Some(result_type),
|
||||
Some(result),
|
||||
vec![Operand::IdRef(zero)],
|
||||
));
|
||||
self.emit_sidecar.agx2_cluster_numbers.push(result);
|
||||
Ok(true)
|
||||
}
|
||||
// `air.is_null_texture_<dim>(%tex)` asks whether a texture handle is the null texture.
|
||||
// We consume it HERE only when `%tex` is a value we ourselves synthesized from
|
||||
// `air.get_null_texture_*` (tracked in `null_texture_values`): that value never crosses
|
||||
@@ -193,6 +222,25 @@ impl Emitter {
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
"air.get_null_intersection_function_table" => {
|
||||
if !call.args.is_empty() {
|
||||
return Err(format!(
|
||||
"native emitter: {} expects no operands",
|
||||
call.callee
|
||||
));
|
||||
}
|
||||
let result_ty = self.resolve_type(&call.ret)?;
|
||||
let LlType::Ptr(addrspace) = result_ty else {
|
||||
return Err(format!(
|
||||
"native emitter: {} returned {result_ty:?}, expected pointer",
|
||||
call.callee
|
||||
));
|
||||
};
|
||||
self.define_unmodeled_byte_pointer_value(name, addrspace)?;
|
||||
let is_null = self.const_bool(true)?;
|
||||
self.record_pointer_nullness(name.to_string(), is_null);
|
||||
Ok(true)
|
||||
}
|
||||
"air.get_instance_count_instance_acceleration_structure" => {
|
||||
if call.args.len() != 1 {
|
||||
return Err(format!("native emitter: {} expects 1 operand", call.callee));
|
||||
@@ -670,6 +718,8 @@ impl Emitter {
|
||||
}
|
||||
"air.atomic.local.add.s.i32"
|
||||
| "air.atomic.local.add.u.i32"
|
||||
| "air.atomic.local.sub.s.i32"
|
||||
| "air.atomic.local.sub.u.i32"
|
||||
| "air.atomic.local.max.s.i32"
|
||||
| "air.atomic.local.max.u.i32"
|
||||
| "air.atomic.local.min.s.i32"
|
||||
@@ -686,6 +736,7 @@ impl Emitter {
|
||||
| "air.atomic.global.max.u.i32"
|
||||
| "air.atomic.global.min.s.i32"
|
||||
| "air.atomic.global.min.u.i32"
|
||||
| "air.atomic.global.sub.s.i32"
|
||||
| "air.atomic.global.sub.u.i32" => {
|
||||
if call.args.len() != 5 {
|
||||
return Err(format!(
|
||||
@@ -708,6 +759,7 @@ impl Emitter {
|
||||
let op = match call.callee.as_str() {
|
||||
"air.atomic.local.add.s.i32" => Op::AtomicIAdd,
|
||||
"air.atomic.local.add.u.i32" => Op::AtomicIAdd,
|
||||
"air.atomic.local.sub.s.i32" | "air.atomic.local.sub.u.i32" => Op::AtomicISub,
|
||||
"air.atomic.local.max.s.i32" => Op::AtomicSMax,
|
||||
"air.atomic.local.max.u.i32" => Op::AtomicUMax,
|
||||
"air.atomic.local.min.s.i32" => Op::AtomicSMin,
|
||||
@@ -722,7 +774,7 @@ impl Emitter {
|
||||
"air.atomic.global.min.s.i32" => Op::AtomicSMin,
|
||||
"air.atomic.global.min.u.i32" => Op::AtomicUMin,
|
||||
"air.atomic.global.or.u.i32" => Op::AtomicOr,
|
||||
"air.atomic.global.sub.u.i32" => Op::AtomicISub,
|
||||
"air.atomic.global.sub.s.i32" | "air.atomic.global.sub.u.i32" => Op::AtomicISub,
|
||||
"air.atomic.local.or.u.i32" => Op::AtomicOr,
|
||||
"air.atomic.local.xchg.i32" => Op::AtomicExchange,
|
||||
_ => Op::AtomicIAdd,
|
||||
|
||||
@@ -53,6 +53,28 @@ impl Emitter {
|
||||
ptr_arg: &TypedValue,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<Word, String> {
|
||||
if let LlValue::IntToPtr {
|
||||
source,
|
||||
destination,
|
||||
} = &ptr_arg.value
|
||||
{
|
||||
if self.resolve_type(destination)? != LlType::Ptr(3) {
|
||||
return Err(format!(
|
||||
"native emitter: atomic inttoptr constant expression targets {destination:?}, expected Workgroup pointer"
|
||||
));
|
||||
}
|
||||
let address = match source.value {
|
||||
LlValue::Int(value) | LlValue::Hex(value) => value,
|
||||
LlValue::SignedInt(value) if value >= 0 => value as u64,
|
||||
_ => {
|
||||
return Err(
|
||||
"native emitter: Workgroup atomic inttoptr address is not a nonnegative integer literal"
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
};
|
||||
return self.workgroup_i32_pointer_for_address(address);
|
||||
}
|
||||
if let LlValue::Local(name) = &ptr_arg.value {
|
||||
if let Some(raw) = self.raw_offsets.get(name).cloned() {
|
||||
return self.emit_raw_word_pointer_for_access(&raw, 0, Some(4), instructions);
|
||||
@@ -79,17 +101,26 @@ impl Emitter {
|
||||
"native emitter: atomic i32 pointer targets {pointee:?}"
|
||||
));
|
||||
};
|
||||
let [field] = fields.as_slice() else {
|
||||
return Err(format!(
|
||||
"native emitter: atomic i32 pointer targets struct with {} fields",
|
||||
fields.len()
|
||||
));
|
||||
};
|
||||
let field = self.resolve_type(field)?;
|
||||
if field != LlType::Int(32) {
|
||||
return Err(format!(
|
||||
"native emitter: atomic i32 pointer targets struct field {field:?}"
|
||||
));
|
||||
let mut field = LlType::Struct(fields);
|
||||
let mut depth = 0usize;
|
||||
loop {
|
||||
field = self.resolve_type(&field)?;
|
||||
match field {
|
||||
LlType::Int(32) => break,
|
||||
LlType::Struct(ref fields) if !fields.is_empty() => {
|
||||
field = fields[0].clone();
|
||||
depth += 1;
|
||||
}
|
||||
LlType::Array(ref element, count) if count > 0 => {
|
||||
field = element.as_ref().clone();
|
||||
depth += 1;
|
||||
}
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"native emitter: atomic i32 pointer first-field chain targets {field:?}"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
let LlType::Ptr(addrspace) = self.resolve_type(&ptr_arg.ty)? else {
|
||||
return Err(format!(
|
||||
@@ -104,7 +135,9 @@ impl Emitter {
|
||||
Op::InBoundsAccessChain,
|
||||
Some(ptr_type),
|
||||
Some(result),
|
||||
vec![Operand::IdRef(ptr), Operand::IdRef(zero)],
|
||||
std::iter::once(Operand::IdRef(ptr))
|
||||
.chain(std::iter::repeat_n(Operand::IdRef(zero), depth))
|
||||
.collect(),
|
||||
));
|
||||
Ok(result)
|
||||
}
|
||||
@@ -200,6 +233,22 @@ impl Emitter {
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn workgroup_i32_pointer_for_address(&mut self, address: u64) -> Result<Word, String> {
|
||||
if let Some(pointer) = self.workgroup_i32_addresses.get(&address) {
|
||||
return Ok(*pointer);
|
||||
}
|
||||
let ptr_type = self.ptr_type_id(StorageClass::Workgroup, &LlType::Int(32))?;
|
||||
let pointer = self.fresh();
|
||||
self.module.types_global_values.push(Self::inst(
|
||||
Op::Variable,
|
||||
Some(ptr_type),
|
||||
Some(pointer),
|
||||
vec![Operand::StorageClass(StorageClass::Workgroup)],
|
||||
));
|
||||
self.workgroup_i32_addresses.insert(address, pointer);
|
||||
Ok(pointer)
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn unmodeled_atomic_f32_pointer(
|
||||
&mut self,
|
||||
) -> Result<Word, String> {
|
||||
|
||||
@@ -29,7 +29,7 @@ fn air_i32_literal(value: &LlValue) -> Option<i64> {
|
||||
/// its `Int(16)` bit pattern, so arithmetic must round-trip through f32). Returns `1` for a scalar
|
||||
/// `BFloat`, `N` for `Vector(BFloat, N)`, and `None` for any non-bf16 type. Purely structural (element
|
||||
/// type + shape), never keyed on a name.
|
||||
fn bfloat_lanes(ty: &LlType) -> Option<u32> {
|
||||
pub(in crate::native::emitter) fn bfloat_lanes(ty: &LlType) -> Option<u32> {
|
||||
match ty {
|
||||
LlType::BFloat => Some(1),
|
||||
LlType::Vector(elem, n) if **elem == LlType::BFloat => Some(*n),
|
||||
@@ -47,7 +47,7 @@ fn float_lanes(ty: &LlType) -> Option<u32> {
|
||||
|
||||
/// `elem` for `n <= 1`, else `Vector(elem, n)` — the scalar-or-vector shape used by the shaped bf16
|
||||
/// widen/narrow helpers.
|
||||
fn shaped_type(elem: LlType, n: u32) -> LlType {
|
||||
pub(in crate::native::emitter) fn shaped_type(elem: LlType, n: u32) -> LlType {
|
||||
if n <= 1 {
|
||||
elem
|
||||
} else {
|
||||
|
||||
@@ -200,7 +200,7 @@ fn pointer_edges_from_carrier(
|
||||
// the access census — 05's scalar `float` arm reaches its phi through
|
||||
// `%142 = bitcast (%141 = gep float …)`; without this edge `%141`'s Float access is invisible
|
||||
// and the whole-vs-part network masquerades as Uniform.
|
||||
if let Some((src, dst)) = &inst.bitcast {
|
||||
if let Some((src, dst)) = inst.bitcast.as_deref() {
|
||||
if matches!(src.ty, LlType::Ptr(_)) && dst.trim_start().starts_with("ptr") {
|
||||
if let LlValue::Local(local) = &src.value {
|
||||
edges.push((name.clone(), local.clone()));
|
||||
@@ -417,7 +417,7 @@ mod tests {
|
||||
BodyBlock {
|
||||
name: "entry".to_string(),
|
||||
role: crate::native::cfg::BlockRole::Normal,
|
||||
typed,
|
||||
typed: typed.map(Into::into),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -150,9 +150,10 @@ impl Emitter {
|
||||
/// Returns `None` when the layout cannot be linearized (dynamic struct index, size mismatch,
|
||||
/// non-divisible stride) so the caller can leave the chain alone rather than miscompile.
|
||||
///
|
||||
/// Index list is the AIR/LLVM GEP list (leading const-0 dropped via [`gep_spirv_indices`], same
|
||||
/// as the structured emit path). First remaining index strides by `sizeof(source_ty)`; further
|
||||
/// indices walk members/elements.
|
||||
/// Index list is the original AIR/LLVM GEP list. Its first index always strides by
|
||||
/// `sizeof(source_ty)`; later indices walk members/elements. In particular, a leading zero must
|
||||
/// remain in the walk: dropping it would misread the following struct-member ordinal as a
|
||||
/// whole-struct stride.
|
||||
pub(in crate::native::emitter) fn linearize_gep_indices_in_scalar_units(
|
||||
&mut self,
|
||||
source_ty: &LlType,
|
||||
@@ -160,10 +161,6 @@ impl Emitter {
|
||||
scalar: &LlType,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<Option<TypedValue>, String> {
|
||||
let indices = match gep_spirv_indices(indices) {
|
||||
Ok(v) => v,
|
||||
Err(_) => return Ok(None),
|
||||
};
|
||||
if indices.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Byte-neutral responsibility split of the former monolith impl; see the parent module.
|
||||
|
||||
use super::super::ops::{bfloat_lanes, shaped_type};
|
||||
use super::*;
|
||||
|
||||
impl Emitter {
|
||||
@@ -18,6 +19,9 @@ impl Emitter {
|
||||
// R3: source the incoming VALUES from the typed graph (labels stay from the parsed pairs).
|
||||
// Byte-identical to the parsed values by tir's phi-operand soundness; falls back on any mismatch.
|
||||
let incoming = self.phi_incoming_values(&name, parsed_incoming);
|
||||
if self.emit_bda_address_phi(&name, &incoming, &result_ty, instructions)? {
|
||||
return Ok(());
|
||||
}
|
||||
if self.emit_raw_pointer_phi(&name, &incoming, &result_ty, instructions)? {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -162,6 +166,66 @@ impl Emitter {
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<(), String> {
|
||||
let operand_ty = self.resolve_type(&lhs.ty)?;
|
||||
let rhs_ty = self.resolve_type(&rhs.ty)?;
|
||||
if operand_ty != rhs_ty {
|
||||
return Err(format!(
|
||||
"native emitter: fcmp operand type mismatch {operand_ty:?} vs {rhs_ty:?}"
|
||||
));
|
||||
}
|
||||
if let Some(lanes) = bfloat_lanes(&operand_ty) {
|
||||
let result_ty = float_compare_result_type(&shaped_type(LlType::Float, lanes))?;
|
||||
let result_type = self.type_id(&result_ty)?;
|
||||
let result = self.result_id(&name, &result_ty)?;
|
||||
let lhs_bits = self.value_id_in(&lhs.value, &lhs.ty, instructions)?;
|
||||
let rhs_bits = self.value_id_in(&rhs.value, &rhs.ty, instructions)?;
|
||||
if lanes <= 4 {
|
||||
let lhs_f32 = self.bfloat_bits_to_float_shaped_id(lhs_bits, lanes, instructions)?;
|
||||
let rhs_f32 = self.bfloat_bits_to_float_shaped_id(rhs_bits, lanes, instructions)?;
|
||||
instructions.push(Self::inst(
|
||||
pred,
|
||||
Some(result_type),
|
||||
Some(result),
|
||||
vec![Operand::IdRef(lhs_f32), Operand::IdRef(rhs_f32)],
|
||||
));
|
||||
return Ok(());
|
||||
}
|
||||
let bits_type = self.type_id(&LlType::BFloat)?;
|
||||
let bool_type = self.type_id(&LlType::Bool)?;
|
||||
let mut comparisons = Vec::with_capacity(lanes as usize);
|
||||
for lane in 0..lanes {
|
||||
let lhs_lane = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::CompositeExtract,
|
||||
Some(bits_type),
|
||||
Some(lhs_lane),
|
||||
vec![Operand::IdRef(lhs_bits), Operand::LiteralBit32(lane)],
|
||||
));
|
||||
let rhs_lane = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::CompositeExtract,
|
||||
Some(bits_type),
|
||||
Some(rhs_lane),
|
||||
vec![Operand::IdRef(rhs_bits), Operand::LiteralBit32(lane)],
|
||||
));
|
||||
let lhs_f32 = self.bfloat_bits_to_float_shaped_id(lhs_lane, 1, instructions)?;
|
||||
let rhs_f32 = self.bfloat_bits_to_float_shaped_id(rhs_lane, 1, instructions)?;
|
||||
let comparison = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
pred,
|
||||
Some(bool_type),
|
||||
Some(comparison),
|
||||
vec![Operand::IdRef(lhs_f32), Operand::IdRef(rhs_f32)],
|
||||
));
|
||||
comparisons.push(Operand::IdRef(comparison));
|
||||
}
|
||||
instructions.push(Self::inst(
|
||||
Op::CompositeConstruct,
|
||||
Some(result_type),
|
||||
Some(result),
|
||||
comparisons,
|
||||
));
|
||||
return Ok(());
|
||||
}
|
||||
let result_ty = float_compare_result_type(&operand_ty)?;
|
||||
let result_type = self.type_id(&result_ty)?;
|
||||
let result = self.result_id(&name, &result_ty)?;
|
||||
|
||||
@@ -3,6 +3,106 @@
|
||||
use super::*;
|
||||
|
||||
impl Emitter {
|
||||
/// Lower an addrspace(1) pointer phi as a phi of 64-bit byte addresses when every arm has an
|
||||
/// exact address-domain representation: either a direct Metal buffer root supplied by the
|
||||
/// reflected address sidecar, or an `inttoptr`/BDA raw value. This is the structural shape used
|
||||
/// by device-address hierarchies: the root arm starts at a bound acceleration-structure buffer
|
||||
/// and loop backedges follow child addresses loaded from that buffer.
|
||||
pub(in crate::native::emitter) fn emit_bda_address_phi(
|
||||
&mut self,
|
||||
name: &str,
|
||||
incoming: &[(LlValue, String)],
|
||||
result_ty: &LlType,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<bool, String> {
|
||||
if !self.bda_device_pointers || *result_ty != LlType::Ptr(1) {
|
||||
return Ok(false);
|
||||
}
|
||||
if !incoming
|
||||
.iter()
|
||||
.all(|(value, _)| self.bda_phi_value_is_addressable(value))
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let address_ty = LlType::Int(64);
|
||||
let result_type = self.type_id(&address_ty)?;
|
||||
let result_name = bda_address_name(name);
|
||||
let result = self.result_id(&result_name, &address_ty)?;
|
||||
let mut ops = Vec::new();
|
||||
let mut seen_incoming: HashMap<Word, Word> = HashMap::new();
|
||||
for (value, label) in incoming {
|
||||
let value_id = self.bda_phi_address_id(value)?;
|
||||
let label_id = self.label_id(label)?;
|
||||
if let Some(existing) = seen_incoming.insert(label_id, value_id) {
|
||||
if existing != value_id {
|
||||
return Err(format!(
|
||||
"native emitter: BDA address phi has multiple values from predecessor {label}"
|
||||
));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
ops.push(Operand::IdRef(value_id));
|
||||
ops.push(Operand::IdRef(label_id));
|
||||
}
|
||||
instructions.push(Self::inst(Op::Phi, Some(result_type), Some(result), ops));
|
||||
self.emit_pointer_nullness_phi(name, incoming, result_ty, instructions)?;
|
||||
self.used_device_address = true;
|
||||
let mut raw = RawBufferOffset::root(format!(".bda_phi_{name}"), 1);
|
||||
raw.device_addr_base = Some(result);
|
||||
self.raw_offsets.insert(name.to_string(), raw);
|
||||
self.pointer_storage
|
||||
.insert(name.to_string(), StorageClass::PhysicalStorageBuffer);
|
||||
self.pointer_pointees
|
||||
.insert(name.to_string(), LlType::Int(8));
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn bda_phi_value_is_addressable(&self, value: &LlValue) -> bool {
|
||||
match value {
|
||||
LlValue::Zero => true,
|
||||
LlValue::Local(name) => {
|
||||
self.bda_inttoptr_sources.contains_key(name)
|
||||
|| self.bda_direct_addresses.contains_key(name)
|
||||
|| self.raw_offsets.get(name).is_some_and(|raw| {
|
||||
raw.const_off == 0
|
||||
&& raw.dyn_terms.is_empty()
|
||||
&& (raw.device_addr_base.is_some()
|
||||
|| self.bda_direct_addresses.contains_key(&raw.root))
|
||||
})
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn bda_phi_address_id(&mut self, value: &LlValue) -> Result<Word, String> {
|
||||
match value {
|
||||
LlValue::Zero => self.const_signed_int(64, 0),
|
||||
LlValue::Local(name) => {
|
||||
if let Some(address) = self.bda_direct_addresses.get(name).copied() {
|
||||
return Ok(address);
|
||||
}
|
||||
if let Some(raw) = self.raw_offsets.get(name) {
|
||||
if raw.const_off == 0 && raw.dyn_terms.is_empty() {
|
||||
if let Some(address) = raw.device_addr_base {
|
||||
return Ok(address);
|
||||
}
|
||||
if let Some(address) = self.bda_direct_addresses.get(&raw.root).copied() {
|
||||
return Ok(address);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(source) = self.bda_inttoptr_sources.get(name).cloned() {
|
||||
return self.phi_value_id(&source.value, &source.ty, &mut Vec::new());
|
||||
}
|
||||
Err(format!(
|
||||
"native emitter: pointer {name} has no exact BDA address representation"
|
||||
))
|
||||
}
|
||||
_ => Err("native emitter: unsupported BDA address phi value".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn pointer_aware_type_id(
|
||||
&mut self,
|
||||
ty: &LlType,
|
||||
@@ -557,3 +657,7 @@ impl Emitter {
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
fn bda_address_name(name: &str) -> String {
|
||||
format!("{name}.metal2vulkan.bda_address")
|
||||
}
|
||||
@@ -457,6 +457,11 @@ impl Emitter {
|
||||
if let Some(id) = self.pointer_nullness.get(name).copied() {
|
||||
return Ok(id);
|
||||
}
|
||||
if self.bda_device_pointers && self.bda_inttoptr_sources.contains_key(name) {
|
||||
let id = self.result_id(&pointer_null_name(name), &LlType::Bool)?;
|
||||
self.pointer_nullness.insert(name.clone(), id);
|
||||
return Ok(id);
|
||||
}
|
||||
if !self.values.contains_key(name) && self.pointer_phi_values.contains(name) {
|
||||
let id = self.result_id(&pointer_null_name(name), &LlType::Bool)?;
|
||||
self.pointer_nullness.insert(name.clone(), id);
|
||||
|
||||
@@ -8,7 +8,7 @@ impl Emitter {
|
||||
result: Word,
|
||||
result_ty: &LlType,
|
||||
selected: &SelectedPointer,
|
||||
_access_align: Option<u64>,
|
||||
access_align: Option<u64>,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<(), String> {
|
||||
let LlType::Ptr(addrspace) = self.resolve_type(&selected.ty)? else {
|
||||
@@ -25,55 +25,31 @@ impl Emitter {
|
||||
let Some(storage) = true_storage.or(false_storage) else {
|
||||
return Err("native emitter: selected load has no concrete pointer arm".to_string());
|
||||
};
|
||||
if !matches!(
|
||||
storage,
|
||||
StorageClass::StorageBuffer | StorageClass::UniformConstant
|
||||
) || true_storage.is_some_and(|true_storage| true_storage != storage)
|
||||
|| false_storage.is_some_and(|false_storage| false_storage != storage)
|
||||
{
|
||||
return Err(
|
||||
"native emitter: selected direct load requires uniform storage-class arms"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
let pointee = if true_is_null {
|
||||
self.pointer_pointee_for_value(&selected.false_value)?
|
||||
} else {
|
||||
self.pointer_pointee_for_value(&selected.true_value)?
|
||||
}
|
||||
.ok_or_else(|| "native emitter: selected direct load missing pointee type".to_string())?;
|
||||
let result_ty = self.resolve_type(result_ty)?;
|
||||
if !types_compatible(&self.resolve_type(&pointee)?, &result_ty) {
|
||||
return Err(format!(
|
||||
"native emitter: selected direct load type mismatch {pointee:?} vs {result_ty:?}"
|
||||
));
|
||||
}
|
||||
let result_type = self.type_id(&result_ty)?;
|
||||
let true_value = if true_is_null {
|
||||
self.const_null(&result_ty)?
|
||||
} else {
|
||||
let ptr = self.value_id(&selected.true_value, &selected.ty)?;
|
||||
let value = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::Load,
|
||||
Some(result_type),
|
||||
Some(value),
|
||||
vec![Operand::IdRef(ptr)],
|
||||
));
|
||||
value
|
||||
self.emit_selected_direct_load_arm_value(
|
||||
&selected.true_value,
|
||||
&selected.ty,
|
||||
true_storage.unwrap_or(storage),
|
||||
&result_ty,
|
||||
access_align,
|
||||
instructions,
|
||||
)?
|
||||
};
|
||||
let false_value = if false_is_null {
|
||||
self.const_null(&result_ty)?
|
||||
} else {
|
||||
let ptr = self.value_id(&selected.false_value, &selected.ty)?;
|
||||
let value = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::Load,
|
||||
Some(result_type),
|
||||
Some(value),
|
||||
vec![Operand::IdRef(ptr)],
|
||||
));
|
||||
value
|
||||
self.emit_selected_direct_load_arm_value(
|
||||
&selected.false_value,
|
||||
&selected.ty,
|
||||
false_storage.unwrap_or(storage),
|
||||
&result_ty,
|
||||
access_align,
|
||||
instructions,
|
||||
)?
|
||||
};
|
||||
instructions.push(Self::inst(
|
||||
Op::Select,
|
||||
@@ -88,6 +64,100 @@ impl Emitter {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn emit_selected_direct_load_arm_value(
|
||||
&mut self,
|
||||
value: &LlValue,
|
||||
pointer_ty: &LlType,
|
||||
storage: StorageClass,
|
||||
load_ty: &LlType,
|
||||
access_align: Option<u64>,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<Word, String> {
|
||||
if let LlValue::Local(name) = value {
|
||||
if let Some(raw) = self.raw_offsets.get(name).cloned() {
|
||||
let loaded = self.fresh();
|
||||
self.emit_raw_load(loaded, load_ty, &raw, access_align, instructions)?;
|
||||
return Ok(loaded);
|
||||
}
|
||||
}
|
||||
if let Some(pointee) = self.pointer_pointee_for_value(value)? {
|
||||
let pointee = self.resolve_type(&pointee)?;
|
||||
if let (LlType::Int(source_bits), LlType::Int(result_bits)) = (&pointee, load_ty) {
|
||||
if source_bits > result_bits {
|
||||
// AIR is little-endian: loading a narrower integer through the same base address
|
||||
// observes the low-bit prefix of the declared wider slot. Logical SPIR-V cannot
|
||||
// reinterpret the pointer itself, so preserve the access in value space by
|
||||
// loading through the arm's declared type and truncating to the requested width.
|
||||
let pointer = self.value_id(value, pointer_ty)?;
|
||||
let wide = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::Load,
|
||||
Some(self.type_id(&pointee)?),
|
||||
Some(wide),
|
||||
vec![Operand::IdRef(pointer)],
|
||||
));
|
||||
let narrowed = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::UConvert,
|
||||
Some(self.type_id(load_ty)?),
|
||||
Some(narrowed),
|
||||
vec![Operand::IdRef(wide)],
|
||||
));
|
||||
return Ok(narrowed);
|
||||
}
|
||||
}
|
||||
}
|
||||
let ptr = self.selected_direct_load_arm_pointer(
|
||||
value,
|
||||
pointer_ty,
|
||||
storage,
|
||||
load_ty,
|
||||
instructions,
|
||||
)?;
|
||||
let loaded = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::Load,
|
||||
Some(self.type_id(load_ty)?),
|
||||
Some(loaded),
|
||||
vec![Operand::IdRef(ptr)],
|
||||
));
|
||||
Ok(loaded)
|
||||
}
|
||||
|
||||
fn selected_direct_load_arm_pointer(
|
||||
&mut self,
|
||||
value: &LlValue,
|
||||
pointer_ty: &LlType,
|
||||
storage: StorageClass,
|
||||
load_ty: &LlType,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<Word, String> {
|
||||
if let Some(pointee) = self.pointer_pointee_for_value(value)? {
|
||||
if types_compatible(&self.resolve_type(&pointee)?, load_ty) {
|
||||
return self.value_id(value, pointer_ty);
|
||||
}
|
||||
}
|
||||
if let Some((element, levels)) = self.aggregate_pointer_arm_scalar_element(value)? {
|
||||
if types_compatible(&self.resolve_type(&element)?, load_ty) {
|
||||
let LlType::Ptr(addrspace) = self.resolve_type(pointer_ty)? else {
|
||||
return Err("native emitter: selected load arm is not a pointer".to_string());
|
||||
};
|
||||
return self.decay_pointer_arm_to_element(
|
||||
value,
|
||||
addrspace,
|
||||
storage,
|
||||
&element,
|
||||
levels,
|
||||
instructions,
|
||||
);
|
||||
}
|
||||
}
|
||||
let pointee = self.pointer_pointee_for_value(value)?;
|
||||
Err(format!(
|
||||
"native emitter: selected direct load arm {value:?} with pointee {pointee:?} cannot address {load_ty:?}"
|
||||
))
|
||||
}
|
||||
|
||||
/// Store `object` THROUGH a direct pointer select (`selected_pointers`), the write-side analog of
|
||||
/// [`emit_selected_pointer_direct_load`]. A pointer `OpSelect`-then-store is illegal under Logical
|
||||
/// addressing when the arms can point into distinct buffers, and there is no value-level "store to
|
||||
@@ -270,37 +340,8 @@ impl Emitter {
|
||||
return Ok(());
|
||||
}
|
||||
let pointee = self.resolve_type(&selected.pointee)?;
|
||||
if pointee == LlType::Int(8) && selected.true_ptr.is_none() && selected.false_ptr.is_none()
|
||||
{
|
||||
if let (Some(true_raw), Some(false_raw)) = (&selected.true_raw, &selected.false_raw) {
|
||||
let result_type = self.type_id(&result_ty)?;
|
||||
let true_value = self.fresh();
|
||||
let false_value = self.fresh();
|
||||
self.emit_raw_load(true_value, &result_ty, true_raw, access_align, instructions)?;
|
||||
self.emit_raw_load(
|
||||
false_value,
|
||||
&result_ty,
|
||||
false_raw,
|
||||
access_align,
|
||||
instructions,
|
||||
)?;
|
||||
instructions.push(Self::inst(
|
||||
Op::Select,
|
||||
Some(result_type),
|
||||
Some(result),
|
||||
vec![
|
||||
Operand::IdRef(selected.cond),
|
||||
Operand::IdRef(true_value),
|
||||
Operand::IdRef(false_value),
|
||||
],
|
||||
));
|
||||
return Ok(());
|
||||
}
|
||||
return Err(
|
||||
"native emitter: selected i8 pointer load requires raw offsets".to_string(),
|
||||
);
|
||||
}
|
||||
if pointee == LlType::Int(8) && pointee != result_ty {
|
||||
let reinterpret_raw = pointee == LlType::Int(8) && pointee != result_ty;
|
||||
if reinterpret_raw {
|
||||
let pointee_bits = bitcast_width(&pointee).ok_or_else(|| {
|
||||
format!("native emitter: cannot reinterpret selected load from {pointee:?}")
|
||||
})?;
|
||||
@@ -312,36 +353,10 @@ impl Emitter {
|
||||
"native emitter: selected pointer load bit width mismatch {pointee:?} ({pointee_bits}) vs {result_ty:?} ({result_bits})"
|
||||
));
|
||||
}
|
||||
if let (Some(true_raw), Some(false_raw)) = (&selected.true_raw, &selected.false_raw) {
|
||||
let result_type = self.type_id(&result_ty)?;
|
||||
let true_value = self.fresh();
|
||||
let false_value = self.fresh();
|
||||
self.emit_raw_load(true_value, &result_ty, true_raw, access_align, instructions)?;
|
||||
self.emit_raw_load(
|
||||
false_value,
|
||||
&result_ty,
|
||||
false_raw,
|
||||
access_align,
|
||||
instructions,
|
||||
)?;
|
||||
instructions.push(Self::inst(
|
||||
Op::Select,
|
||||
Some(result_type),
|
||||
Some(result),
|
||||
vec![
|
||||
Operand::IdRef(selected.cond),
|
||||
Operand::IdRef(true_value),
|
||||
Operand::IdRef(false_value),
|
||||
],
|
||||
));
|
||||
return Ok(());
|
||||
}
|
||||
return Err(
|
||||
"native emitter: selected i8 pointer reinterpret load requires raw offsets"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
if !types_compatible(&pointee, &result_ty) {
|
||||
if !types_compatible(&pointee, &result_ty)
|
||||
&& (selected.true_ptr.is_some() || selected.false_ptr.is_some())
|
||||
{
|
||||
return Err(format!(
|
||||
"native emitter: selected pointer load type mismatch {pointee:?} vs {result_ty:?}"
|
||||
));
|
||||
@@ -349,24 +364,36 @@ impl Emitter {
|
||||
let result_type = self.type_id(&result_ty)?;
|
||||
let true_value = self.fresh();
|
||||
let false_value = self.fresh();
|
||||
let true_ptr = selected
|
||||
.true_ptr
|
||||
.ok_or_else(|| "native emitter: selected pointer load missing true arm".to_string())?;
|
||||
let false_ptr = selected
|
||||
.false_ptr
|
||||
.ok_or_else(|| "native emitter: selected pointer load missing false arm".to_string())?;
|
||||
instructions.push(Self::inst(
|
||||
Op::Load,
|
||||
Some(result_type),
|
||||
Some(true_value),
|
||||
vec![Operand::IdRef(true_ptr)],
|
||||
));
|
||||
instructions.push(Self::inst(
|
||||
Op::Load,
|
||||
Some(result_type),
|
||||
Some(false_value),
|
||||
vec![Operand::IdRef(false_ptr)],
|
||||
));
|
||||
if let Some(true_ptr) = selected.true_ptr {
|
||||
instructions.push(Self::inst(
|
||||
Op::Load,
|
||||
Some(result_type),
|
||||
Some(true_value),
|
||||
vec![Operand::IdRef(true_ptr)],
|
||||
));
|
||||
} else if let Some(true_raw) = &selected.true_raw {
|
||||
self.emit_raw_load(true_value, &result_ty, true_raw, access_align, instructions)?;
|
||||
} else {
|
||||
return Err("native emitter: selected pointer load missing true arm".to_string());
|
||||
}
|
||||
if let Some(false_ptr) = selected.false_ptr {
|
||||
instructions.push(Self::inst(
|
||||
Op::Load,
|
||||
Some(result_type),
|
||||
Some(false_value),
|
||||
vec![Operand::IdRef(false_ptr)],
|
||||
));
|
||||
} else if let Some(false_raw) = &selected.false_raw {
|
||||
self.emit_raw_load(
|
||||
false_value,
|
||||
&result_ty,
|
||||
false_raw,
|
||||
access_align,
|
||||
instructions,
|
||||
)?;
|
||||
} else {
|
||||
return Err("native emitter: selected pointer load missing false arm".to_string());
|
||||
}
|
||||
instructions.push(Self::inst(
|
||||
Op::Select,
|
||||
Some(result_type),
|
||||
|
||||
@@ -39,6 +39,15 @@ impl Emitter {
|
||||
)? {
|
||||
return Ok(());
|
||||
}
|
||||
if self.record_cross_storage_pointer_select(
|
||||
&name,
|
||||
&result_ty,
|
||||
&true_value.value,
|
||||
&false_value.value,
|
||||
cond_id,
|
||||
)? {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let pointer_meta =
|
||||
self.pointer_merge_meta(&[&true_value.value, &false_value.value], &result_ty)?;
|
||||
@@ -193,6 +202,73 @@ impl Emitter {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Defer a pointer select whose concrete arms occupy different SPIR-V storage classes. Logical
|
||||
/// SPIR-V cannot represent that pointer value, but loads through it are exactly representable:
|
||||
/// derive each arm independently and select the loaded values. Recording the source operands
|
||||
/// here lets the existing selected-pointer GEP/load machinery perform that value-domain replay.
|
||||
pub(in crate::native::emitter) fn record_cross_storage_pointer_select(
|
||||
&mut self,
|
||||
name: &str,
|
||||
result_ty: &LlType,
|
||||
true_value: &LlValue,
|
||||
false_value: &LlValue,
|
||||
cond_id: Word,
|
||||
) -> Result<bool, String> {
|
||||
let LlType::Ptr(addrspace) = result_ty else {
|
||||
return Ok(false);
|
||||
};
|
||||
if matches!(true_value, LlValue::Zero | LlValue::Undef)
|
||||
|| matches!(false_value, LlValue::Zero | LlValue::Undef)
|
||||
|| self.pointer_phi_incoming_values.contains(name)
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let true_storage = self.pointer_storage_for(true_value, *addrspace)?;
|
||||
let false_storage = self.pointer_storage_for(false_value, *addrspace)?;
|
||||
if true_storage == false_storage {
|
||||
return Ok(false);
|
||||
}
|
||||
let value_readable = |storage| {
|
||||
matches!(
|
||||
storage,
|
||||
StorageClass::Private
|
||||
| StorageClass::UniformConstant
|
||||
| StorageClass::StorageBuffer
|
||||
| StorageClass::Workgroup
|
||||
)
|
||||
};
|
||||
if !value_readable(true_storage) || !value_readable(false_storage) {
|
||||
return Ok(false);
|
||||
}
|
||||
// An addrspace(2) opaque parameter is a sampler handle, not data memory. Selected sampler
|
||||
// pointers are intentionally represented by the same typed placeholder consumed by
|
||||
// `valid_sampler_value`; the AIR image pass replaces it with its descriptor-backed default
|
||||
// sampler instead of attempting an illegal cross-storage pointer OpSelect. Data-buffer
|
||||
// parameters stay on the per-arm value replay below.
|
||||
let opaque_parameter_arm = |value: &LlValue| {
|
||||
matches!(value, LlValue::Local(local)
|
||||
if self.param_values.contains(local) && !self.data_buffer_params.contains(local))
|
||||
};
|
||||
let selected_has_data_pointee = self.tir_use_pointees.contains_key(name);
|
||||
if *addrspace == 2
|
||||
&& !selected_has_data_pointee
|
||||
&& (opaque_parameter_arm(true_value) || opaque_parameter_arm(false_value))
|
||||
{
|
||||
self.define_unmodeled_byte_pointer_value(name, *addrspace)?;
|
||||
return Ok(true);
|
||||
}
|
||||
self.selected_pointers.insert(
|
||||
name.to_string(),
|
||||
SelectedPointer {
|
||||
cond: cond_id,
|
||||
true_value: true_value.clone(),
|
||||
false_value: false_value.clone(),
|
||||
ty: result_ty.clone(),
|
||||
},
|
||||
);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn pointer_select_arm_id(
|
||||
&mut self,
|
||||
value: &LlValue,
|
||||
@@ -520,6 +596,8 @@ impl Emitter {
|
||||
cond: cond_id,
|
||||
true_ptr: Some(true_ptr),
|
||||
false_ptr: Some(false_ptr),
|
||||
true_storage: storage,
|
||||
false_storage: storage,
|
||||
pointee: LlType::Void,
|
||||
true_raw: None,
|
||||
false_raw: None,
|
||||
|
||||
@@ -25,15 +25,73 @@ impl Emitter {
|
||||
let Some(storage) = true_storage.or(false_storage) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let pointee = gep_pointee(source_ty, indices)?;
|
||||
if let (Some(true_storage), Some(false_storage)) = (true_storage, false_storage) {
|
||||
if true_storage != false_storage {
|
||||
let raw_arm = |emitter: &Self, value: &LlValue| match value {
|
||||
LlValue::Local(local) => emitter.raw_offsets.get(local).cloned(),
|
||||
_ => None,
|
||||
};
|
||||
let true_raw = raw_arm(self, &selected.true_value)
|
||||
.map(|raw| self.apply_raw_gep(raw, source_ty, indices))
|
||||
.transpose()?;
|
||||
let false_raw = raw_arm(self, &selected.false_value)
|
||||
.map(|raw| self.apply_raw_gep(raw, source_ty, indices))
|
||||
.transpose()?;
|
||||
let true_ptr = if true_raw.is_none() {
|
||||
let ptr_type = self.ptr_type_id(true_storage, &pointee)?;
|
||||
Some(self.emit_selected_pointer_access_chain(
|
||||
ptr_type,
|
||||
&selected.true_value,
|
||||
&selected.ty,
|
||||
source_ty,
|
||||
&pointee,
|
||||
true_storage,
|
||||
indices,
|
||||
instructions,
|
||||
)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let false_ptr = if false_raw.is_none() {
|
||||
let ptr_type = self.ptr_type_id(false_storage, &pointee)?;
|
||||
Some(self.emit_selected_pointer_access_chain(
|
||||
ptr_type,
|
||||
&selected.false_value,
|
||||
&selected.ty,
|
||||
source_ty,
|
||||
&pointee,
|
||||
false_storage,
|
||||
indices,
|
||||
instructions,
|
||||
)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
self.selected_load_pointers.insert(
|
||||
name.to_string(),
|
||||
SelectedLoadPointer {
|
||||
cond: selected.cond,
|
||||
true_ptr,
|
||||
false_ptr,
|
||||
true_storage,
|
||||
false_storage,
|
||||
pointee: pointee.clone(),
|
||||
true_raw,
|
||||
false_raw,
|
||||
load_typed: false,
|
||||
},
|
||||
);
|
||||
self.pointer_pointees.insert(name.to_string(), pointee);
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
if !matches!(
|
||||
storage,
|
||||
StorageClass::StorageBuffer | StorageClass::UniformConstant
|
||||
) || true_storage.is_some_and(|true_storage| true_storage != storage)
|
||||
|| false_storage.is_some_and(|false_storage| false_storage != storage)
|
||||
{
|
||||
) {
|
||||
return Ok(false);
|
||||
}
|
||||
let pointee = gep_pointee(source_ty, indices)?;
|
||||
if true_is_null || false_is_null {
|
||||
return self.emit_nullable_selected_pointer_gep(
|
||||
name,
|
||||
@@ -110,6 +168,8 @@ impl Emitter {
|
||||
cond: selected.cond,
|
||||
true_ptr,
|
||||
false_ptr,
|
||||
true_storage: storage,
|
||||
false_storage: storage,
|
||||
pointee: pointee.clone(),
|
||||
true_raw,
|
||||
false_raw,
|
||||
@@ -129,7 +189,6 @@ impl Emitter {
|
||||
&mut self,
|
||||
name: &str,
|
||||
selected: &SelectedLoadPointer,
|
||||
storage: StorageClass,
|
||||
source_ty: &LlType,
|
||||
indices: &[TypedValue],
|
||||
instructions: &mut Vec<Instruction>,
|
||||
@@ -148,14 +207,21 @@ impl Emitter {
|
||||
.clone()
|
||||
.map(|raw| self.apply_raw_gep(raw, source_ty, indices))
|
||||
.transpose()?;
|
||||
let ptr_type = (selected.true_ptr.is_some() || selected.false_ptr.is_some())
|
||||
.then(|| self.ptr_type_id(storage, &pointee))
|
||||
let true_ptr_type = selected
|
||||
.true_ptr
|
||||
.is_some()
|
||||
.then(|| self.ptr_type_id(selected.true_storage, &pointee))
|
||||
.transpose()?;
|
||||
let true_ptr = match (selected.true_ptr, ptr_type) {
|
||||
let false_ptr_type = selected
|
||||
.false_ptr
|
||||
.is_some()
|
||||
.then(|| self.ptr_type_id(selected.false_storage, &pointee))
|
||||
.transpose()?;
|
||||
let true_ptr = match (selected.true_ptr, true_ptr_type) {
|
||||
(Some(ptr), Some(ptr_type)) => Some(self.emit_selected_pointer_access_chain_from_id(
|
||||
ptr_type,
|
||||
ptr,
|
||||
storage,
|
||||
selected.true_storage,
|
||||
source_ty,
|
||||
&pointee,
|
||||
indices,
|
||||
@@ -164,11 +230,11 @@ impl Emitter {
|
||||
(None, _) => None,
|
||||
(Some(_), None) => return Ok(false),
|
||||
};
|
||||
let false_ptr = match (selected.false_ptr, ptr_type) {
|
||||
let false_ptr = match (selected.false_ptr, false_ptr_type) {
|
||||
(Some(ptr), Some(ptr_type)) => Some(self.emit_selected_pointer_access_chain_from_id(
|
||||
ptr_type,
|
||||
ptr,
|
||||
storage,
|
||||
selected.false_storage,
|
||||
source_ty,
|
||||
&pointee,
|
||||
indices,
|
||||
@@ -177,8 +243,8 @@ impl Emitter {
|
||||
(None, _) => None,
|
||||
(Some(_), None) => return Ok(false),
|
||||
};
|
||||
if (true_ptr.is_none() || false_ptr.is_none())
|
||||
&& (true_raw.is_none() || false_raw.is_none())
|
||||
if (true_ptr.is_none() && true_raw.is_none())
|
||||
|| (false_ptr.is_none() && false_raw.is_none())
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
@@ -188,13 +254,18 @@ impl Emitter {
|
||||
cond: selected.cond,
|
||||
true_ptr,
|
||||
false_ptr,
|
||||
true_storage: selected.true_storage,
|
||||
false_storage: selected.false_storage,
|
||||
pointee: pointee.clone(),
|
||||
true_raw,
|
||||
false_raw,
|
||||
load_typed: false,
|
||||
},
|
||||
);
|
||||
self.pointer_storage.insert(name.to_string(), storage);
|
||||
if selected.true_storage == selected.false_storage {
|
||||
self.pointer_storage
|
||||
.insert(name.to_string(), selected.true_storage);
|
||||
}
|
||||
self.pointer_pointees.insert(name.to_string(), pointee);
|
||||
if !self.pointer_phi_values.is_empty() {
|
||||
let is_null = self.const_bool(false)?;
|
||||
|
||||
+31
-12
@@ -206,18 +206,6 @@ impl Emitter {
|
||||
if let Some(id) = self.interner.ptr_types.get(&key) {
|
||||
return Ok(*id);
|
||||
}
|
||||
if pointee == LlType::Int(8) {
|
||||
if let Some((_, id)) = self.interner.types.iter().find(|(ty, _)| {
|
||||
matches!(
|
||||
ty,
|
||||
LlType::Ptr(addrspace)
|
||||
if llvm_pointer_storage(*addrspace).ok() == Some(storage)
|
||||
)
|
||||
}) {
|
||||
self.interner.ptr_types.insert(key, *id);
|
||||
return Ok(*id);
|
||||
}
|
||||
}
|
||||
let pointee_id = self.type_id(&pointee)?;
|
||||
let id = self.fresh();
|
||||
self.module.types_global_values.push(Self::inst(
|
||||
@@ -419,6 +407,10 @@ impl Emitter {
|
||||
"native emitter: getelementptr value requires instruction-local materialization"
|
||||
.to_string(),
|
||||
),
|
||||
LlValue::IntToPtr { .. } => Err(
|
||||
"native emitter: inttoptr value requires instruction-local materialization"
|
||||
.to_string(),
|
||||
),
|
||||
LlValue::Bool(value) => match self.resolve_type(ty)? {
|
||||
LlType::Bool | LlType::Int(1) => self.const_bool(*value),
|
||||
other => Err(format!(
|
||||
@@ -427,12 +419,18 @@ impl Emitter {
|
||||
},
|
||||
LlValue::Int(value) => match self.resolve_type(ty)? {
|
||||
LlType::Int(bits) => self.const_int(bits, *value),
|
||||
LlType::Float if *value == 0 => self.const_float32(0.0),
|
||||
LlType::Half if *value == 0 => self.const_float16_bits(0),
|
||||
LlType::BFloat if *value == 0 => self.const_int(16, 0),
|
||||
other => Err(format!(
|
||||
"native emitter: integer literal {value} used as non-int type {other:?}"
|
||||
)),
|
||||
},
|
||||
LlValue::SignedInt(value) => match self.resolve_type(ty)? {
|
||||
LlType::Int(bits) => self.const_signed_int(bits, *value),
|
||||
LlType::Float if *value == 0 => self.const_float32(0.0),
|
||||
LlType::Half if *value == 0 => self.const_float16_bits(0),
|
||||
LlType::BFloat if *value == 0 => self.const_int(16, 0),
|
||||
other => Err(format!(
|
||||
"native emitter: integer literal {value} used as non-int type {other:?}"
|
||||
)),
|
||||
@@ -505,6 +503,27 @@ impl Emitter {
|
||||
"native emitter: getelementptr value `{name}` did not materialize a pointer"
|
||||
));
|
||||
}
|
||||
if let LlValue::IntToPtr {
|
||||
source,
|
||||
destination,
|
||||
} = value
|
||||
{
|
||||
let expected = self.resolve_type(ty)?;
|
||||
let destination = self.resolve_type(destination)?;
|
||||
if expected != destination {
|
||||
return Err(format!(
|
||||
"native emitter: inttoptr constant-expression destination {destination:?} does not match typed operand {expected:?}"
|
||||
));
|
||||
}
|
||||
let name = format!("%air.const.inttoptr.{}", self.module.id_bound());
|
||||
self.emit_inttoptr_resolved(
|
||||
source.as_ref().clone(),
|
||||
destination,
|
||||
name.clone(),
|
||||
instructions,
|
||||
)?;
|
||||
return self.value_id(&LlValue::Local(name), ty);
|
||||
}
|
||||
if let Some(elem) = self.one_lane_vector_elem(ty)? {
|
||||
match value {
|
||||
LlValue::Splat(lane) => {
|
||||
|
||||
@@ -131,6 +131,31 @@ pub fn is_pointer_typing_emit_error(err: &str) -> bool {
|
||||
|| err.contains("cannot store through reinterpreted pointer select")
|
||||
}
|
||||
|
||||
/// Whether emission reached a deferred cross-storage pointer select at an opaque consumer (most
|
||||
/// commonly an internal-helper argument). Logical SPIR-V cannot materialize one pointer value for
|
||||
/// arms in different storage classes; the typed helper-inlining tier preserves the deferred carrier
|
||||
/// across the former parameter boundary and replays its loads in the value domain.
|
||||
pub fn is_deferred_pointer_materialization_emit_error(err: &str) -> bool {
|
||||
err.contains("selected pointer") && err.contains("missing metadata")
|
||||
}
|
||||
|
||||
pub fn deferred_pointer_materialization_name(err: &str) -> Option<String> {
|
||||
let rest = err.split_once("selected pointer ")?.1;
|
||||
let name = rest.split_once(" missing metadata")?.0;
|
||||
if name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// CFG cross-arm cloning names a cloned SSA value `%xa<fresh-id>_<source-name>`. Retry input is
|
||||
// the pre-structurization AIR text, so carry the structural source suffix back across that
|
||||
// boundary. Ordinary names pass through unchanged.
|
||||
let source = name
|
||||
.strip_prefix("%xa")
|
||||
.and_then(|rest| rest.split_once('_'))
|
||||
.filter(|(id, _)| !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_digit()))
|
||||
.map_or(name.to_string(), |(_, source)| format!("%{source}"));
|
||||
Some(source)
|
||||
}
|
||||
|
||||
/// Whether a native-emitter error came from the typed straight-line body dispatcher after it failed
|
||||
/// to find a migrated lowering/carrier for one instruction. CFG-only retry feeds cannot repair this
|
||||
/// class: they change structured merge handling around already-emitted blocks, but this error occurs
|
||||
@@ -144,7 +169,7 @@ pub fn is_graph_walk_unmigrated_emit_error(err: &str) -> bool {
|
||||
/// relooper retry tiers can restructure. Used by [`classify_validation_error`] to route a rejected
|
||||
/// module to the `CfgStructurization` cascade; a false positive only wastes a retry that is discarded
|
||||
/// unless it independently validates. Anything pointer/parser/intrinsic-shaped returns false so the
|
||||
/// cfg retry stays off that path. The needle set is spirv-val phrasings only: the legacy emit-error
|
||||
/// cfg retry stays off that path. The needle set is spirv-val phrasings only: retired emit-error
|
||||
/// `cost budget` / `clone budget` needles were deleted at cleanup-plan S2 (the repair roster that
|
||||
/// produced them died at W4, and [`classify_emit_error`] no longer consults this predicate).
|
||||
pub fn is_cfg_structurization_error(err: &str) -> bool {
|
||||
@@ -176,7 +201,7 @@ pub fn is_cfg_structurization_error(err: &str) -> bool {
|
||||
}
|
||||
|
||||
/// Whether a spirv-val error is the illegal-logical-pointer-`OpPhi` rejection the M4 phi-the-index
|
||||
/// rewrite ([`rewrite_logical_pointer_phis_retry_module`]) targets: a pointer `OpPhi`/`OpSelect` in
|
||||
/// rewrite (`rewrite_logical_pointer_phis_retry_module`) targets: a pointer `OpPhi`/`OpSelect` in
|
||||
/// a storage class `VariablePointers` cannot cover (Private/UniformConstant/Function). Used by
|
||||
/// `lib.rs`'s retry to route a rejected module to the rewrite; a false positive only wastes a retry
|
||||
/// that is discarded unless the rewrite independently validates.
|
||||
@@ -185,7 +210,8 @@ pub fn is_logical_pointer_phi_error(err: &str) -> bool {
|
||||
}
|
||||
|
||||
/// Whether a spirv-val error is the cross-binding pointer-merge rejection the W1 PhysicalStorageBuffer64
|
||||
/// rewrite ([`rewrite_cross_binding_pointer_merges_bytes`]) targets: an `OpSelect`/`OpPhi` over pointers
|
||||
/// rewrite ([`crate::native::rewrite_cross_binding_pointer_merges_bytes`]) targets: an
|
||||
/// `OpSelect`/`OpPhi` over pointers
|
||||
/// from DISTINCT descriptor bindings, illegal under Logical addressing ("Variable pointers must point
|
||||
/// into the same structure"). Used by `lib.rs`'s retry to route a rejected module to the PSB rewrite; a
|
||||
/// false positive only wastes a retry that is discarded unless the rewrite independently validates.
|
||||
@@ -259,6 +285,8 @@ pub fn classify_validation_error(err: &str) -> ValidationClass {
|
||||
/// *validation*, routing through the validation-side cfg cascade instead.)
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum EmitErrorClass {
|
||||
/// Deferred cross-storage pointer consumed across a helper boundary.
|
||||
DeferredPointerMaterialization,
|
||||
/// Buffer/pointer-typing gap the raw byte model can express — [`is_pointer_typing_emit_error`].
|
||||
PointerTyping,
|
||||
/// Any other emit failure.
|
||||
@@ -268,7 +296,9 @@ pub enum EmitErrorClass {
|
||||
/// Classify a native-emitter emit `Err` into its [`EmitErrorClass`]. Equivalent, arm-for-arm, to the
|
||||
/// ordered `Err(emit_err) if is_*(emit_err)` guard chain it replaces.
|
||||
pub fn classify_emit_error(err: &str) -> EmitErrorClass {
|
||||
if is_pointer_typing_emit_error(err) {
|
||||
if is_deferred_pointer_materialization_emit_error(err) {
|
||||
EmitErrorClass::DeferredPointerMaterialization
|
||||
} else if is_pointer_typing_emit_error(err) {
|
||||
EmitErrorClass::PointerTyping
|
||||
} else {
|
||||
EmitErrorClass::Other
|
||||
|
||||
+118
-8
@@ -23,7 +23,51 @@ use std::collections::{HashMap, HashSet};
|
||||
/// Inline every eligible direct call to a module-local `internal` helper, transitively, to a
|
||||
/// fixpoint. Returns the module text unchanged when nothing is eligible or any difficulty is hit.
|
||||
pub(super) fn inline_nonrecursive_internal_calls(san_ll: &str) -> String {
|
||||
match try_inline(san_ll) {
|
||||
match try_inline(san_ll, None) {
|
||||
Some(out) => out,
|
||||
None => san_ll.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Inline only internal helpers that directly consume the result of a pointer `select`. This is the
|
||||
/// bounded repair for a deferred cross-storage pointer reaching a call boundary: it removes exactly
|
||||
/// that opaque consumer so ordinary selected-pointer load/store replay can operate inside the cloned
|
||||
/// helper body, without expanding the rest of a large module's internal call graph.
|
||||
pub(super) fn inline_pointer_select_consumer(
|
||||
san_ll: &str,
|
||||
entry_name: Option<&str>,
|
||||
selected_pointer: &str,
|
||||
) -> String {
|
||||
let Some(items) = parse_items(san_ll) else {
|
||||
return san_ll.to_string();
|
||||
};
|
||||
let mut targets = HashSet::new();
|
||||
for item in &items {
|
||||
let Item::Func(function) = item else {
|
||||
continue;
|
||||
};
|
||||
if let Some(entry_name) = entry_name {
|
||||
let Some(signature) = parse_def_header(&function.header) else {
|
||||
continue;
|
||||
};
|
||||
if signature.name.trim_start_matches('@') != entry_name {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
for call in function.body.iter().filter_map(|line| parse_call(line)) {
|
||||
if call
|
||||
.args
|
||||
.iter()
|
||||
.any(|argument| argument == selected_pointer)
|
||||
{
|
||||
targets.insert(call.callee);
|
||||
}
|
||||
}
|
||||
}
|
||||
if targets.is_empty() {
|
||||
return san_ll.to_string();
|
||||
}
|
||||
match try_inline(san_ll, Some((&targets, selected_pointer))) {
|
||||
Some(out) => out,
|
||||
None => san_ll.to_string(),
|
||||
}
|
||||
@@ -608,7 +652,7 @@ fn preceded_by_label_keyword(out: &str) -> bool {
|
||||
|
||||
/// The whole pass, in the fallible `Option` domain so any bail returns `None` and the caller keeps
|
||||
/// the input verbatim.
|
||||
fn try_inline(san_ll: &str) -> Option<String> {
|
||||
fn try_inline(san_ll: &str, targets: Option<(&HashSet<String>, &str)>) -> Option<String> {
|
||||
let items = parse_items(san_ll)?;
|
||||
|
||||
// Collect the internal-function table: name -> (signature, body). Only `define internal`.
|
||||
@@ -618,7 +662,9 @@ fn try_inline(san_ll: &str) -> Option<String> {
|
||||
if let Item::Func(f) = it {
|
||||
has_any_func = true;
|
||||
let sig = parse_def_header(&f.header)?;
|
||||
if sig.internal {
|
||||
if sig.internal
|
||||
&& targets.is_none_or(|(targets, _selected)| targets.contains(&sig.name))
|
||||
{
|
||||
// Every param must name a value for us to substitute; reject varargs/unnamed.
|
||||
if sig.params.iter().any(|p| p.is_empty()) {
|
||||
// Un-inlinable internal fn: keep it in the table only as a non-target by NOT
|
||||
@@ -668,7 +714,12 @@ fn try_inline(san_ll: &str) -> Option<String> {
|
||||
match it {
|
||||
Item::Raw(r) => out_items.push(Item::Raw(r)),
|
||||
Item::Func(f) => {
|
||||
let new_body = inline_body_to_fixpoint(f.body, &internal, &mut counter)?;
|
||||
let new_body = inline_body_to_fixpoint(
|
||||
f.body,
|
||||
&internal,
|
||||
&mut counter,
|
||||
targets.map(|(_, selected)| selected),
|
||||
)?;
|
||||
out_items.push(Item::Func(FuncBlock {
|
||||
header: f.header,
|
||||
body: new_body,
|
||||
@@ -717,7 +768,12 @@ fn drop_dead_internal_functions(items: Vec<Item>) -> Vec<Item> {
|
||||
Some(s) => s,
|
||||
None => continue,
|
||||
};
|
||||
if sig.internal && !live.contains(&sig.name) {
|
||||
// AIR static constructors are implicit emitter roots: their calls are injected
|
||||
// after function emission and therefore do not appear in the textual IR. Keep
|
||||
// them live during this source-level helper sweep so targeted inlining cannot
|
||||
// silently discard function-constant/default-state initialization.
|
||||
let implicit_constructor_root = sig.name.starts_with("@_GLOBAL__sub_I");
|
||||
if sig.internal && !implicit_constructor_root && !live.contains(&sig.name) {
|
||||
continue; // a not-yet-live internal fn does not propagate references
|
||||
}
|
||||
(f.body.as_slice(), Some(sig.name))
|
||||
@@ -741,7 +797,9 @@ fn drop_dead_internal_functions(items: Vec<Item>) -> Vec<Item> {
|
||||
.into_iter()
|
||||
.filter(|it| match it {
|
||||
Item::Func(f) => match parse_def_header(&f.header) {
|
||||
Some(sig) if sig.internal => live.contains(&sig.name),
|
||||
Some(sig) if sig.internal => {
|
||||
sig.name.starts_with("@_GLOBAL__sub_I") || live.contains(&sig.name)
|
||||
}
|
||||
_ => true,
|
||||
},
|
||||
_ => true,
|
||||
@@ -851,12 +909,13 @@ fn inline_body_to_fixpoint(
|
||||
mut body: Vec<String>,
|
||||
internal: &HashMap<String, (DefSig, Vec<String>)>,
|
||||
counter: &mut usize,
|
||||
selected_pointer: Option<&str>,
|
||||
) -> Option<Vec<String>> {
|
||||
// A generous bound to guarantee termination even if something pathological slips past the cycle
|
||||
// check; acyclic transitive inlining is finite, this only guards against bugs.
|
||||
let mut budget = 100_000usize;
|
||||
loop {
|
||||
let Some(idx) = find_inlinable_call(&body, internal) else {
|
||||
let Some(idx) = find_inlinable_call(&body, internal, selected_pointer) else {
|
||||
return Some(body);
|
||||
};
|
||||
body = inline_one(body, idx, internal, counter)?;
|
||||
@@ -871,10 +930,14 @@ fn inline_body_to_fixpoint(
|
||||
fn find_inlinable_call(
|
||||
body: &[String],
|
||||
internal: &HashMap<String, (DefSig, Vec<String>)>,
|
||||
selected_pointer: Option<&str>,
|
||||
) -> Option<usize> {
|
||||
for (i, line) in body.iter().enumerate() {
|
||||
if let Some(c) = parse_call(line) {
|
||||
if internal.contains_key(&c.callee) {
|
||||
if internal.contains_key(&c.callee)
|
||||
&& selected_pointer
|
||||
.is_none_or(|selected| c.args.iter().any(|argument| argument == selected))
|
||||
{
|
||||
return Some(i);
|
||||
}
|
||||
}
|
||||
@@ -1669,4 +1732,51 @@ merge:
|
||||
"stale %bcall phi predecessor survived:\n{out}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pointer_select_consumer_inline_is_bounded_to_the_consuming_helper() {
|
||||
let src = r#"
|
||||
@fallback = internal addrspace(2) global i32 0
|
||||
@fc_default = internal addrspace(2) global i8 0
|
||||
|
||||
define internal void @_GLOBAL__sub_I_defaults() section "air.static_init" {
|
||||
entry:
|
||||
store i8 1, ptr addrspace(2) @fc_default
|
||||
ret void
|
||||
}
|
||||
|
||||
define internal i32 @consume(ptr addrspace(2) %pointer, i1 %branch) {
|
||||
entry:
|
||||
br i1 %branch, label %left, label %right
|
||||
left:
|
||||
%value = load i32, ptr addrspace(2) %pointer
|
||||
ret i32 %value
|
||||
right:
|
||||
ret i32 0
|
||||
}
|
||||
|
||||
define internal i32 @unrelated(i32 %value) {
|
||||
entry:
|
||||
%sum = add i32 %value, 1
|
||||
ret i32 %sum
|
||||
}
|
||||
|
||||
define i32 @main(ptr addrspace(2) %runtime, i1 %choose) {
|
||||
entry:
|
||||
%selected = select i1 %choose, ptr addrspace(2) %runtime, ptr addrspace(2) @fallback
|
||||
%consumed = call i32 @consume(ptr addrspace(2) %selected, i1 %choose)
|
||||
%other = call i32 @unrelated(i32 %consumed)
|
||||
ret i32 %other
|
||||
}
|
||||
"#;
|
||||
let out = inline_pointer_select_consumer(src, Some("main"), "%selected");
|
||||
assert!(!out.contains("call i32 @consume"), "{out}");
|
||||
assert!(out.contains("call i32 @unrelated"), "{out}");
|
||||
assert!(out.contains("define internal i32 @unrelated"), "{out}");
|
||||
assert!(
|
||||
out.contains("define internal void @_GLOBAL__sub_I_defaults"),
|
||||
"implicit constructor root was swept:\n{out}"
|
||||
);
|
||||
assert!(out.contains(".inl0.left:"), "{out}");
|
||||
}
|
||||
}
|
||||
@@ -80,6 +80,29 @@ impl LlModule {
|
||||
let Some(original) = allocas.get(&name) else {
|
||||
continue;
|
||||
};
|
||||
// Opaque-pointer AIR commonly packs subword lanes into scalar scratch by bitcasting
|
||||
// the alloca and indexing it as `i8` (for example, two half lanes in one float).
|
||||
// Logical SPIR-V cannot form an `uchar*` PtrAccessChain from a scalar pointer. Model
|
||||
// the allocation by its byte image instead; the existing raw-byte load/store path
|
||||
// then preserves each typed access at its exact byte offset. This is structural and
|
||||
// bounded to the allocation's declared size, never keyed to a source identifier.
|
||||
if seen
|
||||
.iter()
|
||||
.any(|ty| self.resolve_known_type(ty) == LlType::Int(8))
|
||||
&& !self.type_contains_pointer(original)
|
||||
{
|
||||
if let Some((size, _)) = self.native_memcpy_type_size_align(original) {
|
||||
if let Ok(size) = u32::try_from(size) {
|
||||
if size > 1 {
|
||||
self.local_alloca_pointees.insert(
|
||||
(f.name.clone(), name.clone()),
|
||||
LlType::Array(Box::new(LlType::Int(8)), size),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let candidates = seen
|
||||
.into_iter()
|
||||
.filter(|ty| ty != original)
|
||||
|
||||
+41
-3
@@ -61,12 +61,17 @@ pub(super) enum LlValue {
|
||||
Struct(Vec<TypedValue>),
|
||||
Splat(Box<TypedValue>),
|
||||
Gep(Box<LlGep>),
|
||||
IntToPtr {
|
||||
source: Box<TypedValue>,
|
||||
destination: LlType,
|
||||
},
|
||||
Zero,
|
||||
Undef,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct LlGep {
|
||||
pub(super) inbounds: bool,
|
||||
pub(super) source_ty: LlType,
|
||||
pub(super) base: TypedValue,
|
||||
pub(super) indices: Vec<TypedValue>,
|
||||
@@ -77,6 +82,10 @@ pub(super) struct LlFunction {
|
||||
pub(super) name: String,
|
||||
pub(super) ret: LlType,
|
||||
pub(super) params: Vec<(String, LlType)>,
|
||||
/// Explicit aggregate pointees carried by LLVM's `byval(T)` parameter attribute. Opaque
|
||||
/// pointer syntax otherwise erases `T`, and a parameter used only as a memcpy source has no
|
||||
/// dereference from which the ordinary body-use inference could recover it.
|
||||
pub(super) byval_param_pointees: Vec<Option<LlType>>,
|
||||
/// The function's basic blocks lowered to typed carriers — the parse-once typed IR and the SOLE
|
||||
/// body substrate. `parse_function` lexes the body lines transiently and hands them to
|
||||
/// `parse_inner`, which lowers them once (via `split_body_blocks`, where the module type table is
|
||||
@@ -125,6 +134,8 @@ pub(super) struct LlModule {
|
||||
pub(super) functions: Vec<LlFunction>,
|
||||
pub(super) declarations: Vec<LlDeclaration>,
|
||||
pub(super) globals: Vec<LlGlobal>,
|
||||
/// Proven immutable integer values materialized by AIR static initializers.
|
||||
static_init_int_globals: HashMap<String, u32>,
|
||||
/// Stage entry selected by the caller's parsed AIR metadata. `None` preserves the downstream
|
||||
/// transform's historical fallback to the first bodied function.
|
||||
pub(super) entry_name: Option<String>,
|
||||
@@ -236,7 +247,7 @@ fn pointer_param_alias_roots(f: &LlFunction) -> HashMap<String, String> {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some((true_value, false_value)) = &inst.select_arms {
|
||||
if let Some((true_value, false_value)) = inst.select_arms.as_deref() {
|
||||
if !matches!(true_value.ty, LlType::Ptr(_))
|
||||
|| !matches!(false_value.ty, LlType::Ptr(_))
|
||||
{
|
||||
@@ -325,7 +336,7 @@ fn cross_buffer_pointer_phi_gep_sources(f: &LlFunction) -> HashMap<String, HashS
|
||||
merged.extend(value_roots.iter().cloned());
|
||||
}
|
||||
(complete.then_some(merged), true)
|
||||
} else if let Some((true_value, false_value)) = &inst.select_arms {
|
||||
} else if let Some((true_value, false_value)) = inst.select_arms.as_deref() {
|
||||
if !matches!(true_value.ty, LlType::Ptr(_))
|
||||
|| !matches!(false_value.ty, LlType::Ptr(_))
|
||||
{
|
||||
@@ -446,7 +457,14 @@ fn infer_metadata_data_buffer_params(
|
||||
return out;
|
||||
};
|
||||
for (idx, (name, ty)) in entry.params.iter().enumerate() {
|
||||
if kern.buffer_type_name(idx as u32).is_none() {
|
||||
if !matches!(
|
||||
kern.role_of(idx as u32),
|
||||
Some(
|
||||
KernRole::Buffer(_)
|
||||
| KernRole::AccelerationStructureShadow(_)
|
||||
| KernRole::PrimitiveAccelerationStructureShadow(_)
|
||||
)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if matches!(ty, LlType::Ptr(1 | 2)) {
|
||||
@@ -1225,4 +1243,24 @@ join:
|
||||
);
|
||||
assert!(parsed(air).local_alloca_pointees.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_alloca_with_byte_view_uses_bounded_byte_storage() {
|
||||
let air = concat!(
|
||||
"define void @k() {\n",
|
||||
"entry:\n",
|
||||
" %slot = alloca float, align 4\n",
|
||||
" %alias = bitcast ptr %slot to ptr\n",
|
||||
" %high = getelementptr i8, ptr %alias, i64 2\n",
|
||||
" store half 0xH3C00, ptr %high, align 2\n",
|
||||
" ret void\n",
|
||||
"}\n",
|
||||
);
|
||||
assert_eq!(
|
||||
parsed(air)
|
||||
.local_alloca_pointees
|
||||
.get(&("k".to_string(), "%slot".to_string())),
|
||||
Some(&LlType::Array(Box::new(LlType::Int(8)), 4))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,13 @@ fn is_residual_intrinsic(name: &str) -> bool {
|
||||
name.starts_with("air.")
|
||||
|| name.starts_with("llvm.fabs.")
|
||||
|| name.starts_with("llvm.fmuladd.")
|
||||
|| matches!(
|
||||
name,
|
||||
"llvm.agx2.f16matmad4x4.v2f16"
|
||||
| "llvm.agx2.f32matmad4x4.v2f32"
|
||||
| "llvm.agx2.f16matmad8x8.v2f16"
|
||||
| "llvm.agx2.f32matmad8x8.v2f32"
|
||||
)
|
||||
|| name.starts_with("llvm.bswap.")
|
||||
|| name.starts_with("llvm.maxnum.")
|
||||
|| name.starts_with("llvm.minnum.")
|
||||
@@ -38,6 +45,7 @@ fn is_residual_intrinsic(name: &str) -> bool {
|
||||
fn is_literal(value: &LlValue) -> bool {
|
||||
match value {
|
||||
LlValue::Local(_) | LlValue::Global(_) | LlValue::Gep(_) => false,
|
||||
LlValue::IntToPtr { source, .. } => is_literal(&source.value),
|
||||
LlValue::Vector(values) | LlValue::Array(values) | LlValue::Struct(values) => {
|
||||
values.iter().all(|value| is_literal(&value.value))
|
||||
}
|
||||
@@ -208,6 +216,14 @@ fn collect_value_capabilities(
|
||||
collect_value_capabilities(&index.value, aliases, visiting, capabilities);
|
||||
}
|
||||
}
|
||||
LlValue::IntToPtr {
|
||||
source,
|
||||
destination,
|
||||
} => {
|
||||
collect_type_capabilities(&source.ty, aliases, visiting, capabilities);
|
||||
collect_value_capabilities(&source.value, aliases, visiting, capabilities);
|
||||
collect_type_capabilities(destination, aliases, visiting, capabilities);
|
||||
}
|
||||
LlValue::Local(_)
|
||||
| LlValue::Global(_)
|
||||
| LlValue::Bool(_)
|
||||
@@ -377,18 +393,6 @@ impl LlModule {
|
||||
if helpers.is_empty() {
|
||||
return TypedInlineStats::default();
|
||||
}
|
||||
// A pointer-parameter helper and a value-only helper can jointly retarget the module-wide
|
||||
// Private parameter-carrier inference: the former helper's `load i32` + value bitcast then
|
||||
// becomes a direct float load after the latter helper is spliced. Keep only the pointer
|
||||
// helper residual in this mixed composition. Pointer-only modules still exercise the
|
||||
// general pointer-parameter splice.
|
||||
let has_value_only_helper = helpers.values().any(|helper| {
|
||||
helper
|
||||
.params
|
||||
.iter()
|
||||
.all(|(_, ty)| !matches!(ty, LlType::Ptr(_)))
|
||||
});
|
||||
|
||||
let source_pointees = self.ptr_pointees.clone();
|
||||
let mut source_value_pointees = source_pointees.clone();
|
||||
source_value_pointees.extend(self.local_alloca_pointees.clone());
|
||||
@@ -430,18 +434,6 @@ impl LlModule {
|
||||
}
|
||||
let call = instruction.call.as_ref()?;
|
||||
let helper = helpers.get(&call.callee)?.clone();
|
||||
if has_value_only_helper
|
||||
&& helper
|
||||
.params
|
||||
.iter()
|
||||
.any(|(_, ty)| matches!(ty, LlType::Ptr(_)))
|
||||
&& !call
|
||||
.args
|
||||
.iter()
|
||||
.any(|arg| matches!(arg.value, LlValue::Gep(_)))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if call.args.len() != helper.params.len() {
|
||||
return None;
|
||||
}
|
||||
@@ -545,8 +537,7 @@ impl LlModule {
|
||||
.next()
|
||||
.expect("eligible ordinary helper has one block");
|
||||
let typed = block
|
||||
.typed
|
||||
.as_mut()
|
||||
.typed_mut()
|
||||
.expect("eligible ordinary helper has a typed block");
|
||||
typed.rename(&local_rename);
|
||||
cloned_pointer_loads.extend(typed.insts.iter().filter_map(|instruction| {
|
||||
@@ -599,14 +590,13 @@ impl LlModule {
|
||||
let inserted = typed.insts.len();
|
||||
let replacement = typed.insts.drain(..);
|
||||
self.functions[function_index].blocks[block_index]
|
||||
.typed
|
||||
.as_mut()
|
||||
.typed_mut()
|
||||
.expect("call site came from a typed block")
|
||||
.insts
|
||||
.splice(instruction_index..=instruction_index, replacement);
|
||||
if let Some(result_substitution) = &result_substitution {
|
||||
for caller_block in &mut self.functions[function_index].blocks {
|
||||
if let Some(typed) = &mut caller_block.typed {
|
||||
if let Some(typed) = caller_block.typed_mut() {
|
||||
typed.substitute_values(result_substitution);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -435,7 +435,7 @@ entry:
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_pointer_and_value_helpers_keep_pointer_helper_residual() {
|
||||
fn mixed_pointer_and_value_helpers_inline_independently() {
|
||||
let ll = r#"
|
||||
define internal void @write(ptr %pointer, i32 %value) {
|
||||
store i32 %value, ptr %pointer
|
||||
@@ -461,11 +461,11 @@ define void @main() {
|
||||
assert_eq!(
|
||||
stats,
|
||||
TypedInlineStats {
|
||||
splices: 1,
|
||||
helper_instances: 1,
|
||||
splices: 2,
|
||||
helper_instances: 2,
|
||||
}
|
||||
);
|
||||
assert_eq!(call_names(function(&module, "main")), vec!["write"]);
|
||||
assert!(call_names(function(&module, "main")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -44,6 +44,8 @@ impl LlModule {
|
||||
kern: Option<&meta::KernMeta>,
|
||||
entry_name: Option<&str>,
|
||||
) -> Result<Self, String> {
|
||||
let ray_lowered = crate::native::ray_intersection::lower_callback_free_triangle_queries(ll);
|
||||
let ll = ray_lowered.as_deref().unwrap_or(ll);
|
||||
let mut types = HashMap::new();
|
||||
let lines: Vec<&str> = ll.lines().collect();
|
||||
let mut functions = Vec::new();
|
||||
@@ -111,6 +113,8 @@ impl LlModule {
|
||||
for (f, blocks) in functions.iter_mut().zip(block_lists) {
|
||||
f.blocks = blocks;
|
||||
}
|
||||
drop(function_bodies);
|
||||
drop(lines);
|
||||
let entry_functions = entry_name
|
||||
.map(|name| HashSet::from([name.to_string()]))
|
||||
.unwrap_or_else(|| infer_entry_functions(ll));
|
||||
@@ -154,6 +158,7 @@ impl LlModule {
|
||||
functions,
|
||||
declarations,
|
||||
globals,
|
||||
static_init_int_globals: meta::static_init_foldable_int_global_values(ll),
|
||||
entry_name: entry_name.map(str::to_string),
|
||||
preinlined_static_initializers: HashSet::new(),
|
||||
preinlined_helper_pointer_loads: HashSet::new(),
|
||||
|
||||
@@ -5,6 +5,14 @@ use super::*;
|
||||
impl LlModule {
|
||||
pub(in crate::native) fn infer_pointer_pointees(&mut self) {
|
||||
for f in &self.functions {
|
||||
for ((name, ty), pointee) in f.params.iter().zip(&f.byval_param_pointees) {
|
||||
if matches!(ty, LlType::Ptr(_)) {
|
||||
if let Some(pointee) = pointee {
|
||||
self.ptr_pointees
|
||||
.insert((f.name.clone(), name.clone()), pointee.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let params = f
|
||||
.params
|
||||
.iter()
|
||||
@@ -21,7 +29,7 @@ impl LlModule {
|
||||
let Some(result) = &inst.result else {
|
||||
continue;
|
||||
};
|
||||
let Some((true_value, false_value)) = &inst.select_arms else {
|
||||
let Some((true_value, false_value)) = inst.select_arms.as_deref() else {
|
||||
continue;
|
||||
};
|
||||
if !matches!(true_value.ty, LlType::Ptr(_))
|
||||
@@ -143,7 +151,7 @@ impl LlModule {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some((true_value, false_value)) = &inst.select_arms {
|
||||
if let Some((true_value, false_value)) = inst.select_arms.as_deref() {
|
||||
let (LlValue::Local(true_name), LlValue::Local(false_name)) =
|
||||
(&true_value.value, &false_value.value)
|
||||
else {
|
||||
@@ -331,7 +339,7 @@ impl LlModule {
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some((object, ptr)) = &inst.store else {
|
||||
let Some((object, ptr)) = inst.store.as_deref() else {
|
||||
continue;
|
||||
};
|
||||
let LlValue::Local(param) = &object.value else {
|
||||
|
||||
@@ -108,7 +108,7 @@ impl LlModule {
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((object, ptr)) = &inst.store {
|
||||
if let Some((object, ptr)) = inst.store.as_deref() {
|
||||
if let LlValue::Local(base) = &ptr.value {
|
||||
if self.resolve_known_type(&object.ty) != LlType::Int(8) {
|
||||
if let Some(root) = byte_gep_aliases.get(base).cloned() {
|
||||
@@ -233,7 +233,7 @@ impl LlModule {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some((true_value, false_value)) = &inst.select_arms {
|
||||
if let Some((true_value, false_value)) = inst.select_arms.as_deref() {
|
||||
if !matches!(true_value.ty, LlType::Ptr(_))
|
||||
|| !matches!(false_value.ty, LlType::Ptr(_))
|
||||
{
|
||||
|
||||
Loaded 100 of 353 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user