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

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

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

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

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

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

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

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

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

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

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

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

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

Rebased onto development 4cf936ed4d (selidx landed as 3ecf606aa8). The conflicts: the version
lines; the mechanism test, where development added RuntimeFact::PrivateArena; runtime-sources.sha256,
where development's is kept; and api_signatures.tsv and docs/REFUSALS.md, both regenerated
(signatures.py --bless, refusal_surface.py) and differing from development by this change's items
alone. The jobs above ran at the old base; the rebased tip's are in the report to main.
2026-11-21 00:03:34 -08:00
Anees Iqbal 3ecf606aa8 Stage io: an index not shown the same across a primitive is refused; the selected index store goes
Metal's shading language leaves a primitive whose vertices write different indices undefined:
"You must return the same value of [[render_target_array_index]] for every vertex in a primitive.
If values differ, the behavior and value passed to the fragment function are undefined." The same
sentence covers [[viewport_array_index]]. The selected index store answered that case with the
first vertex's index, through the synthesized geometry stages, and MoltenVK's profile could take
DriverDeviation::MetalFirstVertexIndices to store it as written. Both reproduced undefined Metal.
The runtime never reached either: it enables no geometryShader, and no profile takes the
deviation.

After this change every profile has one form. An index that the function's structure shows to be
the same at every vertex of a primitive is stored to Layer or ViewportIndex where
shaderOutputLayer or shaderOutputViewportIndex is enabled. Without that feature it is refused as
Unsupported(LayeredRendering), or as Unsupported(VertexAmplification) for an index the
amplification's offset alone sets. The refusal needs the output feature only; geometryShader is
no longer offered. An index not shown the same is refused as NotImplemented(LayeredRendering) on
every device. index_store's comment cites the two spec sentences as the reason for that refusal.
It cites Vulkan's same-value rule (VUID-VkPipelineShaderStageCreateInfo-stage-02596 for Layer,
-02597 for ViewportIndex) as the reason the index is not stored as written. A device without
multiViewport still stores no viewport index.

Removed:
- IndexStore::Selected, indices_selected, selected_index;
- StageIoPlan::indices_selected and first_vertex_indices_by_device, and the compile layer's
  requirement;
- IoRole::SelectedLayer and SelectedViewport, with their codec tags;
- VaryingKey::selected_layer and selected_viewport, with their key tags;
- GeometryStages::layer and viewport, the stages' Layer and ViewportIndex stores, and the
  Reason's index half;
- RuntimeFact::SynthesizedGeometry's layer and viewport fields;
- DriverDeviation::MetalFirstVertexIndices, its last variant, and with it the DriverDeviation type
  and DeviceProfile::takes_driver_deviation;
- VkProperty::MetalFirstVertexIndices and its codec tag.

The geometry stages keep the barycentric weights and the fan-out. A fan-out stage past the
geometry limits is now refused as RasterizationRateMap needing the limit. Before, it was refused
as LayeredRendering with an empty alternative, because the stage's reason held neither weights
nor an index.

Rule 1: no note stops being raised. The first-vertex form raised none. The input it served is now
a typed refusal, so no difference goes silent. The catalogue is unchanged.

The command line: no code there names a removed item. Translating a vertex function whose index
is not shown the same now prints FALLBACK (NotImplemented LayeredRendering) on a geometryShader
profile, where before it compiled with the stages. Validation: four authored cases compiled on
every profile-leg but moltenvk-m3 through the stages: 07f125464dac, 434e73e03189, 7ce6dea0475e
and a013a2bcbe56. On moltenvk-m3 they were refused needing geometryShader. They are now refused
on every leg; the authored compile census takes them at the next named pin, not in this change.
The coverage census test that read three geometry stages from engine/rt6_first_vertex now reads
them from engine/bary_weights on the 780M profile without fragmentShaderBarycentric.

Fixture: engine/vertex_amplification's amp_vertex and amp_vertex_layer now take their viewport
and slice from the instance (iid & 1) instead of the vertex (vid & 1). The amplification and
render-target-slice tests then still compile them, and engine/rt6_first_vertex carries the
per-vertex case. The fixture was regenerated by scripts/regen-air-fixtures (Apple metal
32023.922, llvm-dis 21.1.8).

Tests:
- engine_selected_indices becomes engine_target_indices, covering:
  - a uniform slice or viewport takes the output or nothing else;
  - no multiViewport stores nothing;
  - per-vertex indices are refused on every device;
  - the floor's zero reads;
  - the weights' stage beside a vertex Layer is not implemented.
- link/tests/geometry.rs loses its two selected-index tests.
- engine_amplification, engine_render_target_slice and engine_stage_io now expect the builtin and
  the output-only refusal.
- runtime-floor now requires shaderOutputLayer, so the tests that need a device without it
  withhold the feature from the floor's description (engine_target_indices, engine_amplification,
  engine_stage_io).

Bless due until the next named pin, where the M3 bless job takes them; nothing is blessed here:
- tests::air_input::engine_fixtures_match_their_golden_printout: vertex_amplification's printout;
- tests::public_fixtures_engine (the inventory):
  - rt6_first_vertex and rt6_first_vertex_point become NotImplemented(LayeredRendering) on every
    profile;
  - amp_vertex and amp_vertex_layer become ok on moltenvk-m3;
  - each LayeredRendering cell that offered GeometryShader loses that alternative;
- tests::golden_hashes, and pipeline::compile::tests::the_old_render_descriptor_key_keeps_its_value
  (the render key): the profiles' fingerprints change with VkProperty's codec;
- the authored compile census.

SEMANTICS_VERSION 2245 -> 2246 and ARTIFACT_FORMAT_VERSION 582 -> 583.
SEMANTICS: an index store changes form. ARTIFACT: the codec loses two IoRole tags, a VkProperty tag
and two RuntimeFact fields. RUNTIME_VERSION stays; runtime-sources.sha256 takes the new hash, and
api_signatures is blessed. docs/REFUSALS.md is regenerated. The runtime README's known gap for a
differing index names the refusal as not implemented and drops the geometry stage form. API.md's
layered-rendering bullet, its RenderPipeline stage list and its profile accessors, and
ARCHITECTURE.md's link line drop the selected index.

Consumer check (consumer_check.sh, consumer development b76d6ac4a9):
- MetalFirstVertexIndices, SelectedLayer, SelectedViewport, selected_layer, selected_viewport,
  SynthesizedGeometry, driver_deviations and DriverDeviation: 0 hits.
- GeometryStages and takes_driver_deviation: in crates/reims-vgpu-c/link-order.txt only.
- DriverDeviation and takes_driver_deviation are named in crates/reims-vgpu-vulkan/src/gpu/rgbx.rs
  and encode_render/tests/metal_tests.rs on some of the consumer's steelbrain/* branches, for
  MetalSampler, MetalHalfConversion and MetalVertexSimdgroups, which the stack below already
  removed. development has neither file.

Verified (jobs read):
- m3-max-61766: lint in every configuration and the suites at this change on the earlier stack
  (eeef281428); its reds were the bless-due goldens above.
- At the stack's tip over this change (dvl-5 1fa4aed963 and dvl-6 92fe40c38f): 61978 and 61987,
  fmt, clippy in every configuration, Rustdoc, each feature alone, the API docs and the Windows
  clippy, green; 61891, the suites at dvl-4: 13 failures, each a bless-due golden above or
  development's own (the raster state test, the inventory's sample_fill rows); 61968, the lavapipe
  device suite of metal2vulkan-validation, 1483 of 1483.
- m3-max-62042: the metal2vulkan-validation suite at dvl-5, 1378 of 1378 passed.
- States-only play of this change's player (p-si.zst) over the 36 streams on um870 (61909),
  gem10 (61912), ms01 (61958), um790 (61990) and msi (62045): 502,920 render and 108,189 compute
  states made, 0 refused, every stream exit 0.
2026-11-20 23:23:51 -08:00
Anees Iqbal 3656f31676 DriverWorkaround keeps the two answers every device takes; the driver-defect refusal goes
DriverWorkaround held 26 variants; Device::from_queries takes only ClippedCoverageNotMetals and
TessellatorNotMetals, on every device, and the batch's earlier commits removed every reader of
the other 24. They go, and the enum's docs now say what it is: a device answer that no Vulkan
query tells apart, noted on every device.

Needs::DriverDefect and Unsupported::driver_defect named a DriverWorkaround measured on a
driver's identity. No site constructs it any more; they go, with their arms in the permanence
match, the validation engine's outcome map and its key test, the conformance verdict's device
gap, the error tests and the refusal surface script.

Docs that named deleted variants are rewritten to what the code does now: the f32 denormals in
an entry that declares the 16-bit float controls are the device's own on every device; the stage
bound is the one bound a kernel's plan is held under; the uniform view is a Uniform block (the
texel form went with ExternalUniformReadsSkipACache); the Intel venues' note no longer claims the
RPL-P's profile takes a workaround.

Verified: nothing yet; the gate follows.
2026-11-20 11:57:41 -08:00
Anees Iqbal 9a1c8fe6dc metal2vulkan-rt takes the runtime's name: metal2vulkan-runtime, published
The cutover's last mechanical step. The old runtime is deleted, so its name is free: the crate
moves to crates/metal2vulkan-runtime, its package is metal2vulkan-runtime and its library
metal2vulkan_runtime, and every reference in the tree follows (sources, tests, scripts, CI,
generated tables and docs).

It is now a published crate, as AGENTS.md said it would be once it took the name: version 0.2.0
with the other two, the translator pinned exactly (=0.2.0, as the translator pins the AIR front
end), documentation, keywords and categories, and copies of the repository's four license files,
which the published-crates test now holds equal to the root's for three crates. CI packages it
with the others. Prose that said it was unpublished, or counted two published crates, says three.

AGENTS.md: facts only. The crate table row, the published-crates and version sentences, and the
paragraph on the old runtime, whose name the runtime now carries (listed for the owner).

Made by one script run on this tip. Verified by the job
named in the landing note.
2026-11-20 09:10:02 -08:00
Anees Iqbal aaa3213887 Translator cutover: first trial-compile fixes (imports, the half pair, push tests, removed routes) 2026-11-20 09:08:20 -08:00
Anees Iqbal 4d3daeace8 Docs: the runtime is metal2vulkan-rt; HOWTO's sections on the deleted runtime give way to rt's README
metal2vulkan-runtime is deleted, so the user-facing docs name metal2vulkan-rt as the runtime:
- README.md: the crate table's runtime row is metal2vulkan-rt (not published yet); two published
  crates; the git dependency and both README links name it; the runtime needs a Vulkan 1.3 device
  with its README's floor; the sentence on the deleted runtime's repro bundles goes.
- CONTRIBUTING.md: the layout lists metal2vulkan-rt and metal2vulkan-conformance; the gate drops
  `-p metal2vulkan-runtime` and gains the conformance suite's line, as AGENTS.md's gate has it;
  two published crates for the signatures and the license copies; the refusal check reads the
  runtime's refusal enums (the deleted runtime's `Problem` is gone).
- docs/VALIDATION.md: the gate as CONTRIBUTING's; "the new runtime" is the runtime in the matrix
  rules and the command replay (the record keys and `harness --runtime new` keep their names).
- docs/HOWTO.md: the sections on the deleted runtime's shader cache, host memory (no-copy
  buffers, unmapping, copied host buffers, guest RAM) and exported memory described its API
  alone; each is now a pointer to rt's README (The cache directory, Imported blocks, Exported
  blocks and Exported surfaces), stating only what that README states. Section 4 loses the
  deleted runtime's repro bundles; section 8 loses its pipeline names, its start-up checks, its
  suspend-time measurements of its own calls and its exit-handler probe, keeping the driver facts.
- docs/ARCHITECTURE.md and the CI workflow's comment name the runtime as metal2vulkan-rt.

Left for the translator's commit (part 2): FAST-PATHS.md and the DevicePolicy text in README,
CONTRIBUTING and VALIDATION's golden-table paragraph ("The old runtime's translations do not
move"), which follows the matrix's old-path rule.

Verified: the compile job is named in the hand-off.
2026-11-20 07:58:56 -08:00
Anees Iqbal d8b39b12d1 SEMANTICS 2141 / RUNTIME 2481: Read short constant windows through uniform texel buffers on the Iris Xe
What: on a device whose profile takes the new cost fact
DriverWorkaround::ExternalUniformReadsSkipACache (ANV on the Iris Xe of
RPL-P alone), a buffer slot's uniform view whose window the translation
bounded to at most TEXEL_WINDOW_BYTES (4 KiB) is declared as a uniform texel
buffer (UniformConstant image, Dim Buffer, Sampled 1, u32 texels) and read with
OpImageFetch; the plan's form is DescriptorView::UniformTexel, its descriptor
UNIFORM_TEXEL_BUFFER, its use class Sampled, its range the uniform view's own
under minTexelBufferOffsetAlignment and maxTexelBufferElements. Every other
uniform view stays a uniform buffer exactly as before. The runtime makes an
R32G32B32A32_UINT view of the planned range for each write, with no cache,
holds it until the command buffer completed (State::retain_own, which also
keeps an indirect chunk that made one from being kept), and binds whole a draw
rebound or carried at such a slot. The zero buffer takes the uniform texel
usage, and upload regions align to the texel offset alignment too.
ARTIFACT_FORMAT_VERSION 525 (DescriptorView gains a variant); SEMANTICS_VERSION 2141, RUNTIME_VERSION 2481.

WorkCounts: uniform_texels_bound; uniform_buffers_bound_to_16k (a bound
buffer's uniform view written as a uniform buffer, window at most 16 KiB: on
the Iris the 4-16 KiB ones); uniform_buffers_bound_past_16k (longer, or not
bounded).

Why: ANV gives external memory MOCS 61 on Gen12.0, which loses the HDC L1
that uniform buffer reads go through; the sampler path keeps its cache. On the
Iris, a UBO over imported memory ran 2.0-2.5x (and 5.2-5.5x for a divergent
index) the time of device memory, a uniform texel buffer 0.98-1.04x (jobs
m3-max-37703, 37729). The window sweep (37753, 37780) set B: at 1 and 4 KiB
texel-set was no slower than ubo-set on device memory in every pattern; at
16 KiB one row was 3.1% slower; from 32 KiB per-lane patterns 2.8-4.2x.

B = 4 KiB covers the consumer's binds only where the kernel's window (its
struct size or accessed hull) is at most 4 KiB. The counting walk counted
buffer sizes, not windows, so the new counter will tell.

The cost of a view per write: vkCreateBufferView+vkDestroyBufferView 0.082 us
on the Iris (mean of 4000), vkUpdateDescriptorSets 0.007 us against a uniform
buffer's 0.024. A set 0 naming a fresh view is found again by no later
command, so such commands lose set-0 reuse.

Tests: engine_access (the texel form's module, its interpretation at
residuals 0, 4, 16 and 256, the window bound, the slot's plan), the profile
fact's carriers, and a lavapipe test whose compile device takes the Iris's
identity (cfg(test) DeviceOptions::compile_as): offsets 0, 4, 16, 256, 260,
set*Bytes data, bytes written before encoding, after it and by a blit, and a
4100-byte window kept as a uniform buffer, with the counts as evidence.

Also: the fixture uniform_texel_windows's AIR companions (job m3-max-37901); a texel form's
loop-invariant fetches move out of their loops as a uniform block's loads do (spirv::hoist, with
its test); the texel form documented (ARCHITECTURE, FAST-PATHS, view docs, runtime README); the
API signatures blessed.

Verified: msi job m3-max-37946 at 00121399e7: fmt check 0, clippy (plain, --cfg m2v_gpu,
--cfg m2v_cpu_icd; --all-targets --all-features -D warnings) 0, rustdoc -D warnings 0. Touched
suites running in the same job. Golden table and engine fixture inventory re-bless on development.
2026-11-16 14:46:29 -08:00
Anees Iqbal 415beb0943 SEMANTICS 2104: loop-invariant loads of uniform views move out of their loops
A new pass, spirv/hoist, runs after the roll pass. It moves a load out of every loop it is
invariant in, into the loop's preheader, in original order and inner loops first. The pure value
ops its indices need move with it. A load qualifies only when all of the following hold:
- It is not volatile and does not make memory visible.
- It goes through an access chain rooted at a Uniform-class Block view. ModuleBuilder declares
  those only for a read-only slot with a bounded window, on a profile whose containment emits no
  check; it refuses a Uniform resource that is not a Block, so no BufferBlock view exists.
- Every index is defined outside the loop, or computed inside it only by pure value ops of
  invariant operands.

A loop is a candidate only where no buffer write can run in any block from which its header is
reachable: the body, what runs before the loop, and an enclosing loop's later code through its
back edge. A buffer write is a store, atomic or image write through StorageBuffer,
PhysicalStorageBuffer or Uniform memory, or a call to a function containing one. Inside a routine,
a loop is a candidate only where the module writes no buffer at all. This also covers another
invocation's write that a barrier inside the loop would make visible.

Speculation: a load in the loop's header block runs whenever the loop is entered, so it moves on
every profile. A load in any other loop block moves only under containment with robust buffer
access (robustBufferAccess or robustBufferAccess2): a uniform view carries no in-shader check to
bypass, and robust access answers in range or zero past the bound range. Under
ContainmentPolicy::UnsafeOff only header-block loads move. Every decision comes from storage
class, view kind, operand definitions, the loop metadata, CFG reachability and the profile's
containment. The values are the same, so the pass is exact and has no FAST-PATHS row.
docs/ARCHITECTURE.md names it in the spirv row and the tidy stage.

Verified (ftk2, 6d6add9acf on 73caf92102):
- The 4 hoist unit tests plus the engine test pass (27487). The engine test reads an authored
  constant struct at fixed words, each under a per-trip branch, in a loop. On all 4 robust
  access-test profiles: the slot is Descriptor(UniformWords), the loop holds no Uniform-class
  load, and the interpreter's sums are right for n = 0, 1, 2, 5, 8. Negative control: with the
  hoist call removed, the test fails ("moltenvk-m3: loads of in in the loop").
- Suite: 3572/3573. The one failure is golden_hashes: 19 cells, engine/tns_mm_flags on the 19
  robust profiles, re-blessed on development. clippy all-features, m2v_gpu and m2v_cpu_icd 0;
  rustdoc 0 (27513-27517).
- Authored compile census (27501, M3): 0 failed, 0 differences, 0 regressions, 768 artifacts
  moved. Slowest compile 590 ms. Peak per-case worker 392 MB, against 391 before.
- Registers on the real modules:
  - RADV XTX: VGPRs 48 both ways, SGPRs 108, no spills, scratch 0, 32 subgroups per SIMD both
    ways; latency -29% (c4) and -26% (c6_8).
  - NVIDIA 2080: registers 64 -> 62 (c4_0, c4_3) and 64 -> 64 (c6_8), stack 0.
- Release timings, cold, one run each, GPU median of 21 CBs at K=1, before -> after in us:
  - The face-tracking conv kernels through the runtime, device-local:
    - XTX: c4_0 22.7 -> 20.8, c4_3 18.3 -> 17.2, c6_8 160.3 -> 133.9 (-16%).
    - 2080: c4_0 29.2 -> 26.7, c6_8 107.9 -> 103.2.
  - One interleaved bare A/B on the 2080 (27567, 6 pairs, P0): the hoist is faster in 5 of 6
    pairs, by 0.8% to 3.7%.
  - Cold "state made in" is unchanged: XTX 8.4-12.1 ms and 2080 20-71 ms in both builds.

SEMANTICS_VERSION 2103 -> 2104.
2026-11-13 18:08:36 -08:00
Anees Iqbal dbcbc704c2 SEMANTICS 2099: forward a thread-memory load to the value its single dominating store wrote, once calls are inlined and again after SCCP
A kernel that keeps values in a private (thread) arena through pointers stored in a closure-like
struct, then read back after its stitched calls are inlined, kept every such slot in memory: on
NVIDIA the arena became local memory (4,304 B on the heaviest authored shape) and the kernel ran
6-10x slower than the same arithmetic in registers.

canon::forward now runs once link, byval, erase, inline and devirt are done, and again right
after the first SCCP and the constant-load folds, over the variant the function constants pick
(SCCP runs again only when forwarding changed the body). A load from a thread allocation becomes
the value its single dominating store wrote where type, offset and length match; allocations with
no read left are dropped; inttoptr(ptrtoint p) read back through such a slot becomes p. A load of
an aggregate that holds a pointer, and a load that would read a thread or threadgroup null
pointer (it exists only in memory), stay memory loads. Plain loads and stores only: volatile,
atomic and non-private address spaces are untouched.

Running forward before SCCP first walked every unspecialized body with all function-constant
variants (peak worker 469 MB, work 10.9 M -> 29.3 M units on the scan cases); forwarding over the
specialized body keeps them at the tip's level.

Verified (ftk2, dff96439f6 on 33de04117d):
- NVIDIA statistics: the heavy kernel's local memory 4,304 B -> 0 (registers 59 -> 64); its
  sibling stays 0 B. Module words: 28078 -> 14358, 15253 -> 11962, 8132 -> 6846.
- RTX 2080 (26970, runtime CB span, median of 21): the three heavy shapes 0.430/0.470/0.221 ->
  0.044/0.046/0.034 ms (6.5-10.3x); others within -1..+3%. RX 7900 XTX (26972): 0.106/0.144/0.068
  -> 0.019/0.020/0.014 ms (4.8-7.4x); one conv shape +8% (A/B 27033 pending), another -6%.
- Census (M3, 26969): 2369 cases, 48670 compiled, 1079 refused, 0 failed, 0 differences, 0
  regressions, 10362 artifacts moved; peak worker 228 MB, slowest compile 908 ms, wall 116 s.
- Suites (msi 26948/26949) pass but golden_hashes (578 cells, re-blessed on development); clippy
  all features, each alone, m2v_gpu and m2v_cpu_icd 0; rustdoc 0. canon/tests/forwarding.rs fails
  before and passes after.
- Pipeline state creation on the 2080, cold process: 19-25 ms tip, 21-36 ms with the change,
  almost all of it the driver.

SEMANTICS_VERSION 2098 -> 2099.
2026-11-13 15:53:27 -08:00
Anees Iqbal 158f9788b5 Half holding: the dot and mix bounds are NativeDot's and NativeMix's, a test, the docs
A half dot or mix already records NativeDot or NativeMix on every device,
so the DeviceArithmetic scan the previous commit added in compile.rs is
removed, and those two notes' docs (artifact.rs, docs/API.md's catalogue)
and docs/FAST-PATHS.md's device-gap row now state the 16-bit form and its
bound: a 16-bit dot of n lanes within (3n - 1) * 2^-11 * sum |a_i b_i| +
(3n - 1) * 2^-25 of Metal's chain (2n - 1 correctly rounded 16-bit
roundings beside Metal's n), a 16-bit mix within 2^-8 of its two terms plus
2^-22. narrow.rs's module docs, lower/arith's dot and mix comment, and
docs/ARCHITECTURE.md (the tidy stage and the spirv/ map) name the pass.

tests::engine_half_hold: a kernel of half min, max, clamp, dot, mix, a
loop-carried half and a thread array of half; on the Iris Xe and RADV
profiles it narrows no exact half, its four input roundings are its only
narrowings and its result's its only widening, its dot, mix and bounds are
16-bit instructions, no float variable stays 32-bit, it answers 33.25 on
the interpreter, passes L3 and records NativeDot and NativeMix; on lavapipe
(Converted) nothing is held and it answers the same.

Verification: not yet run (the build and tests follow).
2026-11-12 22:47:26 -08:00
Anees Iqbal 729912a69e ARCHITECTURE: SCCP's values of a few constants 2026-11-12 07:59:08 -08:00
Anees Iqbal 15866645a8 A generic pointer of no one space is refused as GenericPointer, naming how and where
canon::generic refused every generic pointer it could not give one address space as AddressSpace(8), with no location, so a caller could not tell a pointer of two spaces from one loaded from memory. Feature::GenericPointer (both crates) now names how the pointer gets a space only the run knows (TwoSpaces, Memory, Aggregate, Call, Integer) and the refusal locates the instruction where it does. AddressSpace's doc now lists 8 as defined; the planner treats a generic pointer that survived canonicalization as an invariant breach. FAST-PATHS records the gap, REFUSALS and the API signature table are regenerated, ARCHITECTURE names the pass. runtime_lane::generic_pointers compares generic_spaces and generic_null with the M3 Max's answers (run next on lavapipe).
2026-11-12 07:40:47 -08:00
Anees Iqbal 416f6aeb32 Lane test and Metal answers for the sampler-table fixture; architecture doc 2026-11-12 06:20:54 -08:00
Anees Iqbal 126420d6a8 SCCP folds integer minimum and maximum of constants
A loop whose trip count the function constants decide through llvm.umax (a convolution kernel's max(tile / stride, 1)) kept the call unfolded, so its exit compare had no constant bound, reach could not follow the counter, and a 256 KiB private accumulator was refused against the device's 96 KiB (PrivateMemory 263240). The scalar llvm.umin, umax, smin and smax now fold over constants as ctpop, bitreverse and bswap do; integer minimum and maximum have one answer. engine_arith took its opaque integer bits from llvm.umin(C, -1); they now come from a volatile private word, which no pass folds.

Verified: canon::tests::private_reach's clamped trip count (fails without the fold); the guest kernel at its constants compiles with 144 bytes of private memory on the rdna3 profile (scratch, m3-max-20815).
2026-11-12 05:57:01 -08:00
Anees Iqbal 664b7617d7 The tile fixtures' lane and engine tests; SEMANTICS_VERSION 2040
The runtime lane's private_reach makes private_reach_tiles (tile sizes 2 and 4, linking postfix)
on the device the cfg selects and compares its words with what the probe private_array_reach.m
printed on the M3 Max under macOS 27.0.1, and checks private_reach_rows, whose loop a buffer word
bounds, is refused needing its 256 KiB, as the M3 refused it ("Compute function exceeds available
stack space"). The engine test compiles the same fixtures on the RX 7900 XTX's profile: 128 bytes
a thread with no note, and the rows kernel refused needing 262144 of 98304.

SEMANTICS_VERSION 2040: a private array of nested arrays that bounded indices reach in part is
now emitted and counted at its reach, so refusals and modules change under unchanged keys.
The canon module docs and ARCHITECTURE name the pass.
2026-11-12 03:09:30 -08:00
Anees Iqbal 7f837c636d OpenCL C's native_/half_ functions and vector data loads and stores
Apple's OpenCL compiler spells OpenCL C's native_<fn> and half_<fn> of float
types air.native_<stem>.<type> and air.half_<stem>.<type>, and vload<n>,
vstore<n>, vload_half[<n>], vloada_half<n>, vstore_half[<n>][_<rnd>] and
vstorea_half<n>[_<rnd>] air.vload[a][_half].<space>.<type> and
air.vstore[a][_half].<space>[.<rnd>].<type>. None decoded, so pipelines of
real OpenCL workloads were refused as UnknownIntrinsic
(air.native_powr.v4f32, air.vload.global.v3i32,
air.vstore_half.global.rtz.f32).

- The math family reads native_ and half_ of the twelve stems Apple spells
  (cos, exp, exp10, exp2, log, log10, log2, powr, rsqrt, sin, sqrt, tan),
  f32 scalar and every vector width, as the function at Precision::Fast.
  Metal's devices answer native_powr apart (powr(100, 0.5): 0x1.400002p+3
  on the M3 Max, 0x1.4p+3 on the 5300M), so it is the device's fast form.
- A new family, AirIntrinsic::VectorData (VectorData, VectorDataOp,
  HalfRounding), decodes every address space and element type the
  compiler spells. canon::vector_data makes each call its element
  accesses before SCCP: lane i at element offset * stride + i, at the
  element's own alignment (stride 4 for vloada_half3 / vstorea_half3), a
  half widened by fpext or narrowed by fptrunc.
- vstore_half's rounding suffixes store as the device converts (nearest
  even): the 5300M and the UHD 630 store every suffix as _rte, word for
  word over 32 values, where the M3 Max honours them; agreed with main.
  docs/API.md records the row beside the convert entry.

Measured with an OpenCL-mode probe (owned kernels): vload3(i, g + 1) of
uint reads the 3 words that follow on the M3 Max, the 5300M and the 630;
vloada_half3 / vstorea_half3 step 4 halves, vload_half3 3, on the M3.

Public surface (api_signatures.tsv blessed): AirIntrinsic gains
VectorData; Query gains ChannelOrder and ChannelDataType (previous
commit); new types VectorData, VectorDataOp, HalfRounding. An exhaustive
match over AirIntrinsic or Query in a consumer breaks.

Tests: intrinsics decode tests for both grammars (and their refusals),
observed declarations, canon::tests::vector_data (element accesses at
folded indices), runtime device tests in OpenCL mode (tests::opencl_data:
vload3 past an unaligned pointer, uchar3/short2 at odd elements, half3
strides, vstore_half's suffixes, native_powr). SEMANTICS_VERSION stays
2030 (this branch's bump).
2026-11-11 07:04:32 -08:00
Anees Iqbal 25401533b9 Docs: a fast-math NaN constant beside a run value stores the NaN; the fold's wording
API.md, section 10, Function constants: an fadd, fsub, fmul or fdiv under
nnan whose operand is a function constant bound to a NaN is poison in the
AIR. The translation answers the NaN operand unchanged, as it does without
fast math, where that NaN is Metal's answer. On the M3 Max, Metal drops a
kernel's store of it.

Measured in job m3-max-12877 with case 2d9a7e3091e1f9d9..., which is the
fixture sfold_fast_poison in a scratch corpus:
- Metal on apple-m3-max-macos27.0.1 left every poison row's float and
  half store at the 0xCD fill, and wrote the run-value row.
- MoltenVK with the folds wrote the NaN operand unchanged in every poison
  row (ffc12345, 7f800321, fd21).
- MoltenVK with the base translator dropped the float rows, and wrote ff21
  and 0 in the half rows.
The case is not committed: the corpus compares exactly.

ARCHITECTURE.md: the canon row now says a NaN operand is as it is beside a
value the run computes, and quieted where every operand is a constant.

(cherry picked from commit cddef968a3a8a971341fafcc5469e141fb97b434)
2026-11-09 20:44:24 -08:00
Anees Iqbal f12af61da9 ARCHITECTURE: SCCP's float folds in the canonicalization summary
The canon row names what SCCP settles; it now names the float operations a constant operand
decides (a NaN operand, the first in order, quieted; a product by a zero under nnan and nsz).

(cherry picked from commit f6b2db494f2aabdb2a875c5a49651abc2e28803b)
2026-11-09 20:44:23 -08:00
Anees Iqbal 5e4e9bc60c Make a byval argument's copy at its call, so the inliner takes the call
A byval(T) parameter is the callee's own copy of the T its argument
points to, made at the call. Apple's OpenCL compiler passes a struct
kernel argument so: __entry_st copies the value from its constant buffer
into an alloca and calls st with that pointer byval. The inliner refused
every byval call (DirectCall), so a struct passed by value did not
compile (msi job m3-max-4674: the engine's by-value reflection test).

canon::byval::explicit now runs before pointer erasure: each call that
passes a thread-memory argument byval gets an alloca T and an
llvm.memcpy of T's bytes from the argument just before the call, passes
the copy as a plain pointer, and the attribute leaves the call and every
function's parameters. An argument outside thread memory, or a T
without a size, leaves the module as it was, and the call stays
refused, typed.

Tests: a byval argument is copied at its call and inlined; one outside
thread memory stays DirectCall at the call, naming the callee.

(cherry picked from commit 85844bd545602fa1bc14cb410e6e0b89b3a8c696)
2026-11-07 11:43:21 -08:00
Anees Iqbal 93d2fc8b95 Link a kernel of OpenCL mode as Metal links it: hidden buffers and work-item reads
A compute pipeline Metal makes with openCLModeEnabled (Apple SPI) from a kernel of Apple's
OpenCL compiler (`__entry_<name>` of a library of sourceLanguage 1) binds three hidden buffers
ahead of the kernel's own and reads OpenCL C's work-item functions from the dispatch. Metal
refuses a plain pipeline of such a kernel ("Internal compiler error"). Measured on the M3 Max
(macOS 27.0.1, jobs m3-max-4483 and m3-max-4504): its reflection lists the kernel's arguments,
each buffer 3 past its index and __local memory at its own, then __global_offset_and_num_dims
(index 0, read-only uint), __printf_buffer (1, read-write char) and
__image_order_data_type_table (2, read-only uint), all used; get_global_id adds buffer 0's offset
to the grid position, get_global_offset and get_work_dim read buffer 0, and the other work-item
functions are the global built-ins of their names.

- ComputePipelineDescriptor::open_cl_mode_enabled, carried into LoweringInputs::open_cl_mode
  (part of the key) and SpecRequest::open_cl_mode; the stage-entry cache keys on it.
- air.get_global_offset.i32 and air.get_work_dim.i32 decode as AirIntrinsic::WorkItem.
- canon::opencl, after SCCP and before the global built-ins: appends the three buffers, makes
  get_global_id(c) the lane plus the offset word, the offset and dimension count loads from
  buffer 0, a dimension past 2 OpenCL's 0 or 1, and a dimension the kernel reads from its data a
  select over the three lanes; canon::opencl::entry moves the buffer-indexed arguments 3 on and
  adds the buffers' bindings, which the reflection's unspecialized path uses too.
- Without the mode the kernel compiles as Metal AIR and lowering refuses a WorkItem read
  (Unsupported, Lowering(Dispatch)).
- RuntimeFact::OpenClMode records the mode; a Compiled kernel of the other mode is
  InvalidDescriptor(OpenClMode). The runtime compiles its variants under the descriptor's mode,
  and its warm record carries the field (RECORD_FORMAT 5).
- SEMANTICS_VERSION 1991, ARTIFACT_FORMAT_VERSION 493 (a fact tag added).

Tests: canon::tests::opencl (indices, hidden buffers, the reads' rewrite), the translator's
engine_opencl_mode (the M3's reflection, slot writes, key, the mode check), and the runtime's
opencl_mode device tests (add, lsum, cmul and every work-item function against the M3's values).

(cherry picked from commit e2fdc7b4309c2c239cf1227d0a4c6c54552c1be0)
2026-11-07 11:43:21 -08:00
Anees Iqbal d2f766e88e Fold only the integer bit operations in SCCP
Folding llvm.umin and the other two-operand integer intrinsics over constants made seven
engine_arith tests fail (job m3-max-4310). Their kernels take an opaque integer as
llvm.umin(C, -1), so a NaN or denormal pattern reaches the device without float arithmetic.
OpenCL C's mem_fence needs only llvm.bitreverse. SCCP now folds ctpop, bitreverse and bswap,
and leaves the rest to run where they did, so no module outside the OpenCL shapes changes.

(cherry picked from commit 94d75b4fad376c3138a467893adaa42dedf65a75)
2026-11-07 09:53:31 -08:00
Anees Iqbal 89d8e46d26 Bind an intrinsic's immediates from the call sites of the function passing them on
Metal's compiler leaves OpenCL C's barrier(flags) and mem_fence(flags) out of line: an internal
function passes its parameter on as air.wg.barrier's flags, and mem_fence computes
air.atomic.fence's flags from it through llvm.bitreverse.i2. Every call site passes a constant.
Decode refused the call (Intrinsic(ImmediateNotConstant)), and so every OpenCL kernel that
synchronizes was refused.

Decode now keeps such a call as Callee::Unbound, with the family its declaration names
(intrinsics::Template). Once inlining has made the parameter the call site's constant, SCCP's
edit binds it in the same rebuild, with no pass of its own. SCCP also folds the integer llvm.*
operations (min/max, ctpop, bitreverse, bswap) over constants. LlvmIntrinsic::NarrowInt decodes
those operations on widths no SPIR-V type has (i2), so the fence's flags fold. An immediate still
not constant after canonicalization is refused at the call, in post_check, with the inlined
entry's function location. A NarrowInt that survives is refused as Lowering(Arith).

Tests:
- canon::tests::unbound_immediates: each call site binds its own flags; binding meters no more
  work than the constant twin (264 vs 265 units) and prints the same module; the i2 fence binds
  after folding; flags read from a buffer are refused at the call.
- intrinsics::tests: the narrow-width decode.
- runtime tests::opencl_kernels: a barrier and a fence out of line compute what the M3 and the
  Intel UHD 630 compute.

Verified on the same changes at base c956a4236c: metal2vulkan-air 516/516 (m3-max-4223), the
runtime test on lavapipe (m3-max-4223), and the consumer's glcheck b, b0, f and f0 passing with
the 5080 and 780M profiles (m3-max-4227).

(cherry picked from commit f49960f427b2f1371468b97a215788dea8018d45)
2026-11-07 09:53:17 -08:00
Anees Iqbal c7db26da1b Keep an unrolled entry only where it comes out no larger than its loops
What: canonicalization runs the unrolling rounds (and the SCCP after
each) on a trial body and keeps it only where its size is at most the
entry's before unrolling; otherwise the loops stay as they were and
the trial's undefined-constant reads are dropped with it. The size is
`unroll::live_size`: the instructions that stay once unobserved code
is deleted (every one that is not pure, and every pure one those read,
directly or through others), not counting unconditional branches and
PHIs of one entry, which the copies leave where their blocks join.

Why: with the previous commit alone, a translation census of the
private corpus on the nvidia-rtx5080-laptop profile (no constants
supplied) grew 87 of the 15499 rows both builds translate and shrank
20: 83262314 words in all before the series, 84265507 after (+1.2%),
the largest growth 9546 -> 62171 words (6.5x) and 50185 -> 123245
(2.5x). Those loops' counters pick among a few cheap arms of a body
they run many times, so the copies add more than they decide away, and
the module is what the driver compiles. The fixture this item is for
still unrolls: `fold_loop_extract` specialized is 2296 words (the
baked form 2612). `engine/simd_divergent` `uniform_continue_k`, whose
38 golden cells the previous commit moved, now stays a loop and its
cells are as they were.

Not a speed-for-accuracy choice: either way the program computes the
same answers (unrolling copies every operation as it is), so
`docs/FAST-PATHS.md` has no row for it.

Tests: `canon::tests::unrolling` reworked: the switch's default arm is
80 operations, so copies taking the cheap arms are smaller than the
loop (unrolled, including at `TRIPS`), and copies taking the default
are larger (the loop stays, for supplied and for unsupplied lanes).

Verified: `cargo nextest run -p metal2vulkan-air -p metal2vulkan
--all-features -E 'package(metal2vulkan-air) |
test(/engine_arena|engine_specialized_folds|engine_simd_emulated|golden_hashes_match/)'`:
556 of 557 passed, golden_hashes failing only on the 380 new cells of
the fold fixtures (20 entries on 19 profiles) and no moved cell;
clippy on the crate with all targets and features.

(cherry picked from commit 8dc34fec499b1803bf13b0b1fe57ce1df8241f48)
(cherry picked from commit b1fe70ab5e41dbcf4d2879b7475b76aa1f5fc62c)
2026-11-03 00:45:19 -08:00
Anees Iqbal a5e163422c Unroll the loops whose constant trip count decides a branch of their body
What: after SCCP (and the constant-field reads), canonicalization
unrolls each outermost loop whose exits the constants decide and whose
counter decides a branch or switch of its body (`canon::unroll`), then
runs SCCP again, which folds what each copy decides and deletes the
paths no copy takes; at most 4 rounds, so a nest is taken one level a
round. A loop qualifies when it is reducible with one preheader edge
and one back edge from its latch; it is left only from its header or
latch, each a conditional branch with one way out; its exits are
decided iteration by iteration by integer arithmetic, comparisons,
selects, element and member accesses and constant-global reads of its
header's PHIs and constants (no float operation or comparison is
evaluated); a non-exit branch or switch of its body tests a value
computed that way from its own or its nested loops' header PHIs; and
its latch carries no `llvm.loop.unroll.disable`. Each copy is the
loop's blocks with the header PHIs replaced by that iteration's
values; every instruction is copied as it is, with its flags; a value
used after the loop is the last iteration's.

Why: an uber shader that feeds a `uint4` of function-constant opcodes,
indexed by a 4x4 loop's counters, to a 16-case switch kept every case
of every iteration: 3952 words where the same shader with the
constants written in is 2612. Unrolled and folded it is 2296.

The ceilings are fixed: 64 iterations (`TRIPS`), 8192 instructions
over one loop's copies (`UNROLLED`), 32768 instructions added per
entry over all rounds (`GROWTH`), 4 rounds, 256 instructions evaluated
to decide one iteration's exits (`SLICE`). They are not a
speed-for-accuracy trade, so `docs/FAST-PATHS.md` has no row for them:
unrolling changes no operation and runs each the same number of
times, so a loop past a ceiling stays a loop and computes the same
answers. The ceilings bound only how large the copies grow, and so the
translation's time, memory and output size.

Rule 1: nothing new is evaluated on the host in float. The existing,
documented rule that SCCP folds `fcmp` of two constants (exact IEEE
comparison) is unchanged; a copy can give it new operands where a float
PHI's first iteration value is a constant.

Golden drift: `engine/simd_divergent` `uniform_continue_k` (its
`for (i < 8)` loop branches on `i & 1`) is unrolled, moving its 38
cells (`.ll` and `.air.ll` on 19 profiles); `engine_simd_emulated` runs
it on the CPU interpreter at every width and local size and its output
is unchanged. The table is re-blessed on `development`.

Tests: `canon::tests::unrolling` (six iterations over constant lanes
fold to straight-line code in order; past `TRIPS`, a run-time bound,
`unroll.disable` and run-time opcodes stay loops; at `TRIPS` it
unrolls; undefined lanes unroll to the default case).

Verified: `cargo nextest run -p metal2vulkan-air -p metal2vulkan
--all-features -E 'package(metal2vulkan-air) |
test(/engine_arena|engine_specialized_folds|engine_simd_emulated/)'`
553 passed; golden_hashes fails only on those 38 cells and the new
fixtures' rows; clippy on the workspace with all targets and features.

(cherry picked from commit a99e888de1d35e42de962b678c2f1c00f7383b22)
(cherry picked from commit c1ce0edbd491c3c8fd5ede8e331d5eb958c6bb25)
2026-11-03 00:45:19 -08:00
Anees Iqbal 702c733247 Read the integer fields of a never-written constant global as their constants in SCCP
What: SCCP folds a load of an integer, `bool`, integer-vector or
integer-aggregate field of a global that is in the constant address
space, marked `constant`, not externally initialized and has an
initializer (a program-scope `constant` whose static initializer the
specialization evaluated, or a literal one) to the initializer's value
at that field. A `getelementptr` with constant indices into such a
global is its address constant in the lattice (an interned GEP
constant expression); the instruction is kept and goes when nothing
uses it. So the loads through a `select` the function constants
decided, through by-value copies and through member and element paths
fold, and SCCP folds the selects, branches and switches they decide
and deletes the blocks no path reaches, before SPIR-V.

Why: an uber shader that collects its function constants into a
`constant` struct (`constant Config kConfig = {...}`) read every field
through memory, so a specialization kept every path of the shader: the
fixture added later in this series grows to 22895 words where the same
shader reading the constants directly is 1737.

How it is decided: by structure alone (the global's address space, its
`constant` flag, no external initialization, a constant initializer;
the constant space is read-only to entry functions and only the static
initializer writes it, and those stores are already folded), never by a
name. Rule 1: only integer leaves fold (`const_loads::integers_only`,
an iterative walk capped at 4096 members); a float field's load stays,
for the device to read. The existing rule that SCCP's whole-global load
folds any type (a float function constant included) is kept unchanged.

Tests: `canon::tests::constant_fields` (a struct of an i8 flag, two
`<4 x i8>` opcode vectors and a float, filled by a static initializer
and read through a function-constant `select`: each integer field
folds, the float load stays; the generic path and a run-time index stay
loads). Two existing tests read fields of closed constant globals that
now fold, so they read through byte GEPs instead (`engine_arena`), and
the deeply nested written global test reads with a volatile load to
keep its global.

Verified: `cargo nextest run -p metal2vulkan-air -p metal2vulkan
--all-features -E 'package(metal2vulkan-air) |
test(/engine_arena|engine_specialized_folds/)'`: 524 of 525 passed,
the failure the loop fixture this item does not cover (it needs the
unrolling of the next commit). Clippy on both crates, all targets and
features. The note-set diff, budgets and census of the series are in
the commit that adds the fixtures.

(cherry picked from commit d2d28d5bc7b1aee22e081eb65318e781d4569660)
(cherry picked from commit c39a2591179ab18cbd41b4279109d97190119a61)
2026-11-03 00:45:19 -08:00
Anees Iqbal 14dc4c5f2e Draw a line wider than the device's lines as a band of two triangles
Metal draws a line under Apple's setLineWidth: at a width other than 1 as
the parallelogram Vulkan's non-strict wide lines may be (major axis the
larger framebuffer extent, minor-axis edges through the endpoints, centred,
w long). Devices without wideLines (MoltenVK among them) or whose wide
lines are strict or not parallelograms cannot draw it with their own lines.

A render pipeline's band variant (VariantKey::line_band) adds two
synthesized stages after the vertex stage (pipeline::link::band): a
tessellation control stage that copies each of a line's two vertices and
writes every level 1 in the quad domain, and an evaluation stage that
places each corner at its endpoint moved across the segment by half the
width in framebuffer pixels along the minor axis, taken to clip space
through Vulkan viewport 0's half extent, which the draw pushes
(PushField::LineBand, BindState::line_band, its own 16-byte aligned push
range). Ends behind w = 2^-20 are clipped first; smooth varyings and clip
distances follow their endpoint, flat and integer ones take the first
control point's. GraphicsState::line_band (LineBandState) states the
consumer's contract: PATCH_LIST of two control points, no culling, its
front face, the push offset.

The device description gains what chooses the route: VkFeature::WideLines,
and the limits lineWidthRange, lineWidthGranularity, strictLines,
nonStrictWideLinesUseParallelogram (VK_KHR_maintenance5) and
subPixelPrecisionBits, read from Khronos profile JSON and from ash. The
verifier and requirement rules take the per-vertex arrays of tessellation
control inputs and outputs and evaluation inputs, and TessLevelOuter and
TessLevelInner as arrays. ARTIFACT_FORMAT_VERSION 480 for the new encoded
fields (VariantKey, GraphicsState, LineBandState, PushField, VkFeature).

Verified: cargo build --workspace --all-features --all-targets; nextest
tests::engine_line_band (the band variant on every committed profile with
tessellationShader validates in spirv-val and requirements, draws
PATCH_LIST with its own push range; flat varyings take the first control
point; without tessellationShader it is refused needing it; barycentric
reads are not implemented) and the tessellation push_offset tests pass.

(Carried to development from steelbrain/reims-graphics-kext 19814d7bb3.)
2026-11-01 21:26:20 -08:00
Anees Iqbal 9c80a4957b Compile functions whose function constants are left undefined
A function constant the request leaves unset no longer refuses the pipeline
with NeedsInput(FunctionConstant). Metal makes that pipeline, optional or
required: is_function_constant_defined is false, arguments gated on the
constant (negated or not) are absent, and its reads vary from read to read
(probes/undefined_function_constant_values.m on the M3 Max, macOS 27.0.1:
u + 3 read 0, u * 7 + 1 read 1, u == 0 ? 111 : 222 read 222, b ? 5 : 6 read
5). WindowServer's QuartzCore pipelines leave optional constants unset
(fixed_vert_lpf_gen without constant 53), so the desktop could not draw.

SCCP's lattice is now flat, the undefined value one more value beside the
constants:
- a value computed from an undefined constant alone stays undefined, and a
  pure instruction computing one becomes its type's zero (an address keeps
  naming the constant's global);
- a branch on one takes its false way (a rewrite only where no other way
  was opened), and a select its false arm;
- an and with zero, an or with all ones and a mul by zero are that
  constant whatever the undefined operand holds, in SCCP and in the static
  initializer, so QuartzCore's generic || (...) is true with generic set;
- an operation that also reads a run's value, and a PHI (an undefined
  entry merges as overdefined), keep what the run computes, so a defined
  way keeps its value and a loop counting from the constant still counts.
The entry-block refusal and its inliner gate are gone. Entry gains
undefined_reads, the undefined constants the specialized body reads,
which validation's case checker uses where it used the refusal to prove
an omitted constant unread.

Removed: MissingInput::FunctionConstant (metal2vulkan-air),
RuntimeInput::FunctionConstant (metal2vulkan), the command line's
--constant hint. docs/API.md lists the reads under accepted differences.
SEMANTICS_VERSION 1932. The golden tables and the engine inventory move
only the 532 cells (28 rows by 19 profiles) that were the refusal; each is
now ok.

Verified: metal2vulkan-air 481/481, with negative controls (absorbing rule
off: the two new and/or tests fail; the PHI mapping off: the loop test
fails); the core suites; clippy (all features, --cfg m2v_gpu); the
command line on the M3's QuartzCore library: fixed_vert_lpf_gen with
reims's values (0 and 1 true, 3 = 0) and the whole pipeline with
fixed_frag_lpf_cpf translate and pass spirv-val on moltenvk-m3,
nvidia-rtx5080-laptop and intel-uhd770-rpls-anv, with generic true
keeping the texture-matrix path (521 lines of SPIR-V against 290); every
fixed_* pair and backdrop_capture_compute_tile_* with no constants
translates but the _spc vertex functions, which ask for a vertex
descriptor.
2026-10-31 05:34:42 +02:00
Anees Iqbal bf3ce3813c Read Core Image kernel libraries and split whole aggregate accesses
A Core Image kernel library (metal -fcikernel, metallib -cikernel) is a
metallib of file type 1 whose kernels (!air.ci) are listed as function
TYPE 5 over one shared module. The container refused the file type
(Unsupported LibraryKind(1)), so newLibraryWithData: failed where Metal
succeeds; the consumer's graphics-kext lane hit it on Core Image's own
helper library in a macOS 26 guest, so every Core Image path stopped
there.

What Metal answers, measured with kernels written from scratch on an M3
Max under macOS 27.0.1 (probe programs over Metal's API and objc's message
log of a CIColorKernel render):
- newLibraryWithData: takes it as MTLLibraryTypeExecutable; functionNames
  is empty; the private externFunctionNames lists the kernels in the
  reverse of the table's order (libraries of two and four kernels);
- newFunctionWithName:, newFunctionWithDescriptor: and the private
  newExternFunctionWithName: make each kernel with functionType 4 (no SDK
  enumerator; its description prints "Unknown"); newExternFunctionWithName:
  answers as newFunctionWithName: for any library, a kernel of an
  executable one included, and nil for a missing name;
- a compute pipeline made from an extern function fails ("Function tint
  was not found in the module");
- Core Image fetches each kernel and its own helpers with
  newExternFunctionWithName: and links them on the CPU, in Metal.framework's
  base device class, into an ordinary executable library holding one
  kernel, ciKernelMain, of which it builds a plain compute pipeline.

So now:
- container: file type 1 is read (executable; its functions may share one
  bitcode range, hashed once, as a dynamic library's); TYPE 5 is the new
  FunctionStage::Extern, no stage: the ABI cross-check refuses it as a
  mismatch, Library::Function compiles it as no entry (EntryNotFound,
  available 0). Unobserved file types stay LibraryKind refusals.
- FunctionType gains the private enumerator Extern = 4
  (regen-metal-enums PRIVATE); reflection maps Extern to it.
- runtime Library: function_names leaves extern functions out;
  extern_function_names (reverse table order) and
  new_extern_function_with_name are new.

ciKernelMain itself was refused next: Lowering(Arith) at its first
load, `load [4 x <4 x float>], ptr addrspace(2)`, a whole array loaded
from the constant buffer and passed by value to a helper. Lowering reads
and writes buffer and threadgroup memory a scalar or vector at a time.
The new canon pass `aggregates` (after SCCP, beside the other expansions)
replaces each non-volatile, non-atomic load or store of a pointer-free
array or struct in device, constant or threadgroup memory by its members'
accesses in layout order (a getelementptr i8 at the member's distance, the
access's alignment lowered to what the distance allows, joined by
insertvalue or split by extractvalue), at most 256 members, 8 deep.
Thread memory, pointer-holding aggregates (handles), volatile accesses
and larger types stay whole as before. The same-type pointer bitcast
beside the load was never the problem (verified alone).

Public surface: metal2vulkan-air FunctionStage::Extern; metal2vulkan
FunctionStage::Extern and FunctionType::Extern; runtime
Library::extern_function_names and new_extern_function_with_name
(api_signatures blessed: 5 added, none changed or removed). devtools
gains core_image_metallib. The metal-enum generation now records the
macOS 27.2 SDK (the host's Xcode); no SDK value changed, only Extern was
added. LibraryKind's doc and reach note name what it refuses now.

No cache version moves: file type 1 and aggregate accesses outside thread
memory were refused before, so no key reached them, and
golden_hashes_match_the_table passes unchanged (every public fixture
assembled: this Mac's Xcode 27.2 now has its Metal toolchain). The
runtime-sources pin moves (runtime library.rs): re-pinned here to
23766690fd75227c5333e976bfc1fdfafa6ff78f43e0c5ba8fa5183574cd9371.

Verified (M3 Max, macOS 27.0.1):
- Metal versus this tree's runtime on MoltenVK: Core Image's linked
  ciKernelMain for a tint color kernel and for a sampler kernel (both
  from-scratch CI kernels; the linked libraries captured from Metal in
  scratch and deleted after), same constant buffer, source texture and
  sampler, 4x4 RGBA32Float target: byte-identical texels, the early-out
  column untouched on both. The parent tree answers FALLBACK (Lowering
  Arith) for both. Release CLI: 0.01-0.03 s, 11 MiB each.
- Release CLI, parent vs this tree, largest public fixtures
  (hfb_filter_bank render pair, tns_mm_flags), three runs each:
  0.12-0.13 s vs 0.12-0.16 s and 0.05-0.06 s vs 0.04-0.05 s, 27 MiB both
  (runs beside a test suite; the same within noise).
- New tests: canon aggregates (split loads, stores with nested arrays and
  lowered alignments, threadgroup; volatile, pointer-holding and
  300-element aggregates stay whole), an engine test running a
  ciKernelMain-shaped kernel on the CPU interpreter on three profiles,
  core_image_libraries (container types, stages, shared hash, functionType
  4, EntryNotFound), and a runtime device test on MoltenVK (names, extern
  names, both lookups, pipeline refusal, an executable library's kernel
  through the extern lookup). Negative controls: the split and execution
  tests fail with the pass disabled; the library tests fail with file
  type 1 refused.
- cargo nextest -p metal2vulkan -p metal2vulkan-air -p metal2vulkan-runtime
  -p metal2vulkan-devtools --all-features: 4927 passed (golden hashes and
  the metal-as fixture parts included); -p metal2vulkan-validation
  -p metal2vulkan-conformance: 2369, all passed after the re-pin; doctests
  ok; clippy --workspace --all-targets --all-features -D warnings and the
  runtime's under --cfg m2v_gpu: clean; rustdoc -D warnings and
  scripts/api-docs: clean; REFUSALS, METAL-COVERAGE and
  CONFORMANCE-COVERAGE re-derived (MTLFunctionTypeExtern is listed as not
  yet compared by a conformance case). Not run: a corpus translation
  census, and the device suites beyond the new runtime test.
2026-10-31 03:39:16 +02:00
Anees Iqbal cdc09276f3 Emit fast-math arithmetic in the AIR's order and let the device group and fuse it
One work packet, landed as 4 commits (c81ea84c14..41bbe0f1c2 on archive/development-linear-2026-10-28), in order:

* Emit fast-math arithmetic in the AIR's order and let the device group and fuse it

What. The translator no longer reproduces Metal's compiler's grouping, pairing and fusion of
fast-math arithmetic. Each float operation is emitted in the AIR's order, decorated by its own
fast-math flags: an operation whose flags hold `contract` and `reassoc` is undecorated, so the
device's compiler may group and fuse it; every other one is `NoContraction` (an undecorated
SPIR-V operation would also allow reassociation, which a `contract`-only operation does not), and
a precise module's operations keep their order. `llvm.fmuladd` keeps its fused route: one AIR
operation, answered by the device's fused instruction.

Deleted: lower/arith/regroup.rs (648 lines), reassoc.rs (1469), contract.rs (585) and
contract/chain.rs (1204); the Folded and Fused strategies, ArithPlan's `contract` and `unrounded`
fields and select.rs's CONTRACTED read bit; output_precision's `plan` (the `unrounded` marking of
half output chains, Metal's choice of where not to round) and the plumbing that existed only for
it: LoweringInputs::half_output_lanes, the public HalfOutputLane, StageIo::half_output_lanes,
color_writes' half_output_lanes check, its cache-key hashing and codec entry; Fma::on (tests
only). Tests engine_reassoc (318), engine_regroup (134), engine_settled_sums (572), three
engine_arith tests, three half-output-lane engine_stage_io tests and the fused_sync lockstep case,
whose premises were Metal's grouping. Fixtures regroup_chain, sum_regroup, sum_regroup_precise,
fmx2_contract_fast, fmx2_contract_precise and unm_contract_chain (.metal, .ll, .air.ll, their
TOOLCHAIN lines and air_input printouts). Validation lanes sum_regroup (308) and settled_sums
(394), and the three authored cases whose expected values were Metal's fusions
(multiply-add-contraction-shapes-under-fast-math, multiply-add-contraction-flags-without-fast-math,
multiply-add-chains-under-fast-math) with their observations.

Kept: the contraction rule itself (AIR semantics); output_precision's notes (half_output_note,
note_half_output, note_extended_range_sources), which state where Metal may differ rather than
reproduce it; the F16 strategy's per-operation rounding.

The note. The existing FastMathRewrites covers it: it is now recorded where an operation's
operand comes from an operation the two operations' flags let a compiler regroup (both `reassoc`)
or fuse (a product into a sum, both `contract`), looking through negation, widening, shuffles and
element moves. No new kind. It moves from the ledger's elsewhere class to a device gap
(docs/FAST-PATHS.md row; tests::fast_paths), joins the conformance replay's NATIVE_NOTES, and the
cases' own declarations of it are gone (depth_texel_reads, half_read_nans, host_page_writes,
mesh_draws, sample_positions, snorm_tile_store, visibility, topology_classes).

New tests. tests::engine_fast_math_order: a fast `((d+c)+b)+a`, its precise twin, fast and
contract-only `a*a+c`, and a fast vector product, on every committed profile: spirv-val, no fused
instruction, one instruction per AIR operation, NoContraction exactly where the flags forbid
contraction, the interpreter's answer in the AIR's order, and the note on every form but the
precise sum. runtime_lane::kept_apart (reworks settled_sums): strict and contract-only mul-adds
store two roundings, a precise sum stores the AIR's order, a fast mul-add stores either rounding,
and the layer reports nothing.

Versions: SEMANTICS_VERSION 1900; ARTIFACT_FORMAT_VERSION 469 (StageIo lost a field).
Docs: FAST-PATHS.md, API.md (catalogue entry and policy), ARCHITECTURE.md (module map),
artifact.rs's FastMathRewrites doc. api_signatures.tsv re-blessed.

Verified (this machine unless named):
- Negative control: on the parent tree both new core tests fail (a fast sum regrouped to
  0x34000000 where the AIR order stores 0, the mul-adds fused, the product paired, no note);
  with the change they pass.
- cargo check, clippy --workspace --all-targets --all-features -D warnings, plain and with
  --cfg m2v_gpu; rustdoc -D warnings; refusal_surface --check; conformance and metal coverage
  current.
- Core tests: engine_fast_math_order, engine_arith, arith::tests, engine_stage_io,
  engine_simd*, engine_native_*, engine_metal_math, engine_fetch_*blend, engine_bicubic,
  engine_rotated_weights, engine_extended_range, engine_float_call_notes, color_write,
  api_tests, compile tests, fast_paths: 469 + 83 passed.
- The engine inventory bless (not committed) compiled every public fixture on all 19 profiles:
  43593 ok cells, each through spirv-val; only the deleted fixtures' 28 rows went.
- Conformance replay on lavapipe (linux-gate arm64): exit 0, the 723 rows are exactly
  known-gaps.tsv's, 0 unlisted.
- Validation lanes on lavapipe (linux-gate arm64, --cfg m2v_cpu_icd): kept_apart and the lanes
  that assert notice sets (blits, degrade_notices, gpu_times, half_slice_nans, heap_metal_sizes,
  heap_textures, provoking, provoking_mesh, sparse_textures, ycbcr_passes): 93 passed. llvmpipe
  kept all 4096 fast mul-adds as written and all 4096 fast sums in the AIR's order.
- kept_apart on MoltenVK (Apple M3 Max, --cfg m2v_gpu, under maclock): passed; the device's
  compiler fused 2370 of 4096 fast mul-adds and kept all 4096 fast sums in the AIR's order.
- Release CLI before and after, back to back, on the deleted and most affected fixtures over
  moltenvk-m3, gate-lavapipe, nvidia-rtx5080-laptop and intel-irisxe-anv: wall within noise
  (about 8 ms of process start, +-3 ms on a loaded host). Words: hfb_filter_bank 148284 ->
  162420 on moltenvk-m3 (half chains feeding a half output now round at each operation as the
  AIR says: +1408 OpFConvert, +1408 NoContraction; 289 OpFmaKHR became a multiply and an add),
  unm_contract_chain 33666 -> 35167, fmx2_contract_fast 18557 -> 18908, the rest within +-200.

Not in this commit: the golden tables (6028 cells move in 347 subjects, 5707 of them under an
unchanged key, 28 subjects go with the fixtures) and the engine inventory (28 rows go, none
moves) are re-blessed on development; corpus/authored-compile.tsv keeps three lines for the
deleted cases until its re-bless.

* Read 16-bit operands directly and hold half chains at float without float16

What. Two forms of `half` arithmetic that were neither the device's native one nor the fast one:

- Where a profile takes the device's 16-bit `+ - *` and `fma` (moltenvk-m3 on the measured fact,
  RADV and ANV under the 16-bit float controls), every `half` is held widened in an `f32`, so each
  16-bit operation narrowed both operands and widened its result: three conversions an operation,
  the next operation narrowing what the last had just widened. `FunctionBuilder::convert` now
  answers a narrowing of a value it widened from a 16-bit float with that float (exact), and a
  narrowing of a plain constant whose lanes are zeros, infinities or normal halves with the 16-bit
  constant; the widenings nothing else reads leave with the dead code. A rounding's own pair (a
  narrowing widened back) is never taken apart, so `narrow::rounds_by_conversion`, which decides
  `NativeHalfConversion` and the controlled modes, still sees every rounding. A chain of 16-bit
  operations is now 16-bit instructions on 16-bit values, converted only where a value enters or
  leaves it.
- Without `shaderFloat16` (vk12-floor, SwiftShader, Pascal) the module emulates `half` arithmetic
  in `float`, rounding each result by the device's quantize. New `DevicePolicy::half_chains`:
  `HalfChainPolicy::AtExits` (the default, the fast form) holds a `half` `+ - *` whose flags hold
  `contract` and `reassoc` and whose result only such operations read at `float` precision
  (`lower::arith::half_chain`), so a chain rounds where a value leaves it, one quantize per exit;
  `HalfChainPolicy::EachOperation`, which `exact_answers()` selects, rounds every operation. The
  profile carries it, so its fingerprint covers it. Recorded as `FastMathRewrites` (its doc and
  API.md's catalogue entry extended); a FAST-PATHS.md fast-default row; API.md's policy list.

The forms by profile (unchanged, for the record): moltenvk-m3 takes the measured 16-bit
arithmetic; RADV and ANV the controlled one; NVIDIA (the conversion pair folded,
`HalfConversionPairFolded`) and lavapipe (no `DenormPreserve` for 16 bits) have `shaderFloat16`
but compute `half` in `float` and round by the device's conversion pair, which this commit leaves
as it is; the profiles without `shaderFloat16` quantize.

Tests: tests::engine_fast_math_order::half_operations_read_their_16_bit_operands_directly (no
narrowing of a widened half or a constant on any profile, the rounded chain stored, some profile
takes 16-bit arithmetic) and ::half_chains_without_float16_round_at_their_exits_by_default (one
quantize against two, the held and rounded answers, both policies on every profile, distinct
fingerprints); runtime_lane::kept_apart::half_chains_without_float16_round_at_their_exits on the
device. Updated, as the conversions they counted are gone (the half agent's files, minimal):
lower::arith::tests::narrow::half_arithmetic_on_the_device_is_one_16_bit_instruction (at most two
operand narrowings), tests::engine_arith::half_rounding_follows_the_operation (the chain's
conversion count), tests::engine_arith::a_measured_half_sum_requires_the_arithmetic_fact_alone (a
kernel whose halves only the 16-bit `fma` reads widens nothing, so needs no measured widening).

Versions: SEMANTICS_VERSION 1901. ARTIFACT_FORMAT_VERSION unchanged (no encoded type changed).
api_signatures.tsv re-blessed (the enum and the field).

Words, release CLI, every module spirv-val'd (before = development 7b5cf8328d, then 622b388830,
then this commit):
- moltenvk-m3: hfb_filter_bank 148284, 162420, 140672; grd_half_many_samples 99039, 99330, 96710;
  nan_half_fast 10042, 10057, 9961.
- nvidia-rtx5080-laptop: hfb 147962, 155474, 155474; grd 110944, 111163, 111163; nan 9888, 9882,
  9882.
- gate-lavapipe: hfb 148530, 155470, 155470; grd 111018, 111163, 111163; nan 9888, 9882, 9882.
- vk12-floor: hfb 124826, 131766, 121270; grd 84482, 84627, 82019; nan 9838, 9832, 9808
  (EachOperation reproduces 622b388830's: 131766, 84627, 9832).

Verified:
- Negative controls: with the narrowing fold off, the 16-bit test fails (amd-780m-hawkpoint-radv
  narrows a widened half); with the plan off, the chain test fails (two quantizes on
  lunarg-desktop-baseline-2023). Both pass with them on.
- Core tests on this Mac: 1133 passed (arith, engine_arith, engine_native*, engine_stage_io,
  engine_fetch*, engine_simd*, spirv::*, device::*, cache::*, compile tests, api_tests,
  air_input, fast_paths, engine_fast_math_order, api_signatures, api_surface); conformance
  filtered tests 26 passed; clippy --workspace --all-targets --all-features -D warnings, plain and
  with --cfg m2v_gpu; rustdoc -D warnings; refusal_surface --check.
- The engine inventory bless (not committed) over every public fixture on all 19 profiles: only
  the deleted fixtures' 28 rows go, every other cell as before (spirv-val on each `ok`).
- runtime_lane::kept_apart on SwiftShader (linux-gate arm64, --icd swiftshader): the `fast` chain
  4096 of 4096 held under AtExits and 4096 rounded under EachOperation, the strict chain rounded
  under both; on lavapipe (whose compiler drops the undecorated conversion pairs: the `fast` chain
  4096 held under both, the strict one rounded) and on MoltenVK (Apple M3 Max, under maclock:
  every chain rounded at each sum, the 16-bit arithmetic) both tests pass.
- Lavapipe (linux-gate arm64): the conformance replay exits 0, its 763 rows exactly
  known-gaps.tsv's, 0 unlisted, the verdicts as at 622b388830; runtime_lane kept_apart,
  native_maths, half_* and degrade_notices: 28 passed. MoltenVK: the half_* lanes and
  native_maths' half rounding pass; native_maths_answers_within_its_recorded_bounds fails on
  NativeDivision (`divide::precise` records it everywhere; code this commit does not touch).

Not in this commit: the golden tables (with 622b388830, 7652 cells move in 672 subjects; 28
subjects go) and the engine inventory (28 rows go) are re-blessed on development.

* Number ARTIFACT_FORMAT_VERSION 470, after development's 469

What. development's own commit took 469 for its encoding change while this branch's first commit
took 469 for StageIo losing half_output_lanes; the rebase merged the two equal lines silently, so
two layouts shared one value. 470 keeps an artifact of either from decoding as the other.

Verified: cargo check -p metal2vulkan --all-features --all-targets on the rebased tree.

* Re-pin the runtime sources at the landing tip

The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-10-28 17:24:22 +02:00
Anees Iqbal adef203530 Describe each driver deviation's route as the code takes it now
One work packet, landed as 10 commits (262093ec48..8e4bfa28b4 on archive/development-linear-2026-10-28), in order:

* Describe each driver deviation's route as the code takes it now

The DriverDeviation, VkProperty and driver-table docs still named the
exact emulations the native-arithmetic change sets deleted (Metal's
libm, division, denormal flushing, NaN selection, min/max picks, the
emulated sampler, the color, storage and Depth16 write roundings, the
depth stand-in). Each variant's doc now says what a profile that takes
it gets and what one without it gets: the device's own answer with the
precision note recorded, or, where a capability hangs on the answer, its
emulation or refusal.

- error/mod.rs: DriverDeviation's header and the float-function, NaN,
  sampler, color-write, FMA, denormal, quantize, min/max, half
  arithmetic, storage-write, texel-write and Depth16 variants.
- device/requirements.rs: the matching VkProperty docs; MetalColorWrites
  says no module requires it (compile.rs never adds it), and
  MetalHalfQuantize drops the clamp claim the code does not make.
- device/driver_facts.rs: the table preambles and measurement paragraphs
  (docs and citations only, no row or variant changed); the deleted
  resolve_rounding::color_resolves_against_metals_rules citation now
  names the_device_resolve_rounds_as_announced, which holds the row.
- runtime_lane/heap_textures.rs: heap_depth_textures_keep_their_bytes,
  renamed from ..._with_their_twins (no twin exists), with the two
  driver_facts.rs citations updated.
- lower/texture/mod.rs and pipeline/compile.rs: the storage_properties
  doc and comment list the four properties select_write relies on,
  dropping the 0x7fc00000 store.

Verified by reading each route in lower/ (narrow, fma, denormal, nan,
arith, sampler, stage_io/color_write, texture) and pipeline/compile.rs,
and by git grep for every cited test and item.

* Describe the pixel samplers, routines and color-write inputs as they run now

Translator docs that still described the deleted emulated sampler, the
cube face fold routine, the compiler-word-bound fit and the shader's own
color-write rounding:

- pipeline/artifact.rs: PixelSamplerScaling no longer names a linear
  sample's emulation or a MetalSampler condition; a runtime word's linear
  pixel sample snaps onto its footprint cell on every device
  (position::plan plans SnapKind::WordCell with no device test), a word of
  mixed filters is the device's. ArgumentPixelSamplerScaling says it is
  recorded on every device for any access but a 2D gather and a sample
  without a comparison, as select.rs pixel_note does.
- lower/sampler/select.rs (pixel_note) and lower/sampler/mod.rs
  (RuntimeSlot::cells, ::texels): the cell snap holds on every device; the
  slot's word filter fields are read for a half texel's conversion alone,
  on a MetalSampler device (half_converts requires !device_texels).
- device/profile.rs: FunctionsInlinedAtEveryCall lists the routines that
  exist (wide-integer divisions, precise fmod, texel conversions, filter
  sums, sampling routines; no face fold); takes_driver_deviation names the
  route a deviation's docs give for a driver without it.
- error/mod.rs: RuntimeInput::ColorWrites says what the color-write map
  decides (the conversion that records a note, and NearestEven's half
  rounding), not a rounding of every output.
- bind/color_resolve.rs and its tests: drop the citation of
  resolve_rounding's cost test, which is deleted.
- device/mechanism.rs: drop the trailing comment on the deleted
  ExactFormsOverCompilerLimit fact.

Verified by reading position::plan, select.rs pixel_note and the
half_converts branch, spirv/builder/module.rs's routine kinds and every
mb.routine site, pipeline/color_writes.rs, and git grep for each cited
item.

* Describe texel conversion, YCbCr filtering and depth comparison as the device's

Translator docs still named the deleted linear-filter emulation, the
shader's own depth comparison and the depth twin:

- lower/texture/half.rs: off MetalSampler devices the device's sampler
  filters and the half is its float texel rounded to nearest even
  (device_texels), not this routine's; the only fetch-computed filter that
  skips the routine is the in-place YCbCr one.
- lower/texture/mod.rs (half_texels): drop the example of a runtime
  sampler's sRGB raw-code emulation for the `arm` clauses.
- metal/format/mod.rs: a two-plane YCbCr texture's linear sample is the
  device's filter, noted, but where its planes are read in place.
- pipeline/artifact.rs (RestrictedDepthRange) and lower/texture/slot.rs
  (depth_comparison): every comparison is the device's; no shader-made
  comparison is left to exclude.
- lower/sampler/select.rs: a depth comparison reads the texture's own
  depth image (no twin).
- lower/sampler/mod.rs (Sampling::words): list the terms plain_words
  sums; no linear emulation, level grid or shader comparison term exists.

Verified by reading device_texels, half_texels and both its callers,
linear.rs filter_note and metal_filtered_ycbcr, depth_comparison's one
caller, in_place.rs, and plain_words.

* Describe the runtime's YCbCr filter notice and variant kinds as they fire now

- degradation.rs: YCbCrFilterNotExact fires on a device that samples
  through Metal's own sampler alone (linear.rs metal_filtered_ycbcr is
  None elsewhere), where the stage records HalfSampleFilter or
  FloatSampleFilter for any two-plane YCbCr format bound; a native sampler
  announces device-sampling. The module doc drops the exact forms dropped
  to fit a compiler word bound, whose kind and fit are deleted.
- ycbcr.rs: linear filtering of the converted texels is the device
  sampler's (Metal's own on MoltenVK, announced ycbcr-filter-not-exact);
  only planes read in place are Metal's filter exactly.

Verified by reading lower/sampler/linear.rs, in_place.rs and the runtime's
Kinds::of and degrade_bound_formats.

* Describe the lanes' and cases' native forms where they named deleted emulations

Docs and comments only; no expectation changed.

- validation runtime_lane/driver_deviations.rs: the half quantize,
  min/max, half arithmetic and half widening bullets say what the module
  does off the deviation (the device's own conversion or quantize, the
  same NMin/NMax/NClamp noted native-min-max, narrow::from_bits' decode),
  not the deleted integer rounding, operand picks and exact_answers
  decode.
- validation observation_contract/comparison.rs: HalfSampleFilter and
  FloatSampleFilter are a YCbCr texture through Metal's own sampler.
- validation runtime_lane/pixel_samplers.rs, conformance
  cases/pixel_samplers.rs: the pixel coordinates reach Metal's texels
  through the translator's snaps, filtered by the device's sampler.
- conformance cases/snorm_tile_store.rs: no exact tile store and no
  FAST-PATHS row; only extended-range, padded and bfloat attachments take
  a load pass.

Verified by reading the lanes' assertions, select.rs pixel_note,
position::plan and narrow.rs.

* State the native forms in the doc pages where they promised exact switches

- README.md: the promise that every speed-for-accuracy choice has an
  opt-in exact switch was false for the device's maths, rounding,
  conversions and sampler, which have none; it now says those are the
  device's, recorded, and the runtime's choices keep their switches.
- docs/API.md: exact_answers selects the runtime's five switches (as
  policy.rs's exact_answers sets them), not exact forms of the native
  arithmetic; an unmeasured driver takes each deviation's documented
  route, not a conservative one; half widening's NaN and denormal are the
  device's under its own conversion or the float controls; Depth32Float
  texels are the depth image's, announced where it clamps or flushes; the
  catalogue intro names the native forms.
- docs/ARCHITECTURE.md: the native forms are the device's on every device
  with no policy choice; the policy's accuracy switches are the runtime's.
- docs/FAST-PATHS.md (after the opening section): a YCbCr texture's image
  form holds Metal's texels exactly and its linear sample is the device's
  filter; only the in-place form is Metal's filter.

Verified against device/policy.rs, lower/arith/narrow.rs, the depth twin's
deletion (c11e653acd) and lower/sampler/linear.rs.

* Drop the exact golden table from VALIDATION.md's emitter-stability contract

4bf2c22aad deleted golden_hashes_exact.tsv and its table in
golden_hashes.rs; VALIDATION.md still described a second table of every
sampling fixture under exact_answers. The contract now names the one table.

Verified: crates/metal2vulkan/tests/ holds golden_hashes.tsv alone, and
golden_hashes.rs names no exact table.

* Re-pin the runtime sources after the doc audit

The audit's commits edit doc comments and comments only in files the
runtime guard hashes (degradation.rs, ycbcr.rs, and translator files the
build lists); no run's behaviour changes, so RUNTIME_VERSION stays.

Verified: the_runtime_sources_are_the_committed_ones failed with 81ebd500
committed against 8bc0e06b computed, and passes after this pin.

* Drop the 0x7fc00000 hand-off from half_write_nans_converted's doc

a6e97e7f93 deleted the NaN canonicalization before storage writes
(StorageImageClass::SmallFloatQuietNan among it): a half write to a
packed small float hands the device the half widened, as to a 16-bit
float channel. The doc still said such a write hands it 0x7fc00000, and
tied MetalHalfTexelWrites to both kinds, where it states the 16-bit
float store alone (lower/texture/mod.rs half_write_nans).

Verified by reading half_write_nans and the write emission
(lower/texture/emit.rs), which canonicalizes no small-float NaN.

* Re-pin the runtime sources after the half-write NaN doc fix

metal/format/mod.rs is a runtime guard input; the preceding commit edits a
doc comment there alone, so no run's behaviour changes and RUNTIME_VERSION
stays.

Verified: the_runtime_sources_are_the_committed_ones failed with 8bc0e06b
committed against 279b25d4 computed, and passes after this pin.
2026-10-28 17:24:21 +02:00
Anees Iqbal 78ed264c90 Drop the normalized vertex attribute's exact division (vertex_normalized)
One work packet, landed as 9 commits (9c0bdbe0d2..41066d87d0 on archive/development-linear-2026-10-28), in order:

* Drop the normalized vertex attribute's exact division (vertex_normalized)

The owner's ruling of 2026-10-27: the GPU's native arithmetic is the contract, no exact
emulation. A normalized vertex attribute is now always the device's fixed-function UNORM or
SNORM conversion; the policy-forced pull that divided its codes in the shader goes with
DevicePolicy::vertex_normalized, VertexNormalizedPolicy, its profile field, its ledger row and
its tests. A format pulled for any other reason (a format the device cannot fetch, alignment,
limits, containment, the capture form) still decodes in the shader as before.

Verified: cargo clippy --workspace --all-targets --all-features -D warnings clean; nextest of
engine_vertex_variants, device::tests::profile, fast_paths, catalogue, degradation and
api_surface: 71 passed. api_signatures is re-blessed at the end of the lane.

* Keep the compact decoded twin only (decoded_texels)

The owner's ruling of 2026-10-27: no exact emulation. A carried ASTC LDR texture's decoded
twin now always holds 8-bit codes, and an EAC 11-bit texture's 16-bit normalized codes (its
values in floats only where the device does not take those codes' format, a capability
fallback). DevicePolicy::decoded_texels and DecodedTexelsPolicy go, with their ledger row,
their mentions in the degrade catalogue and the runtime's docs, the policy-keyed fingerprint
test, and the validation lanes' exact twins. decoded-texel-precision is announced as before.
bind::AstcTexels::Float stays: the conformance suite's cross-check decodes Metal's values with
it. RUNTIME_VERSION 1654.

Verified: clippy --workspace --all-targets --all-features -D warnings clean, plain and with
--cfg m2v_gpu; nextest of fast_paths, device profile, degradation and catalogue, image_plan's
decode bands, the conformance ASTC and ETC cases, api_surface: 112 passed.

* Take the device's texel conversion only (texel_conversion)

The owner's ruling of 2026-10-27: no exact emulation. A read, sample or gather with a float
or half result off Apple's GPUs is now always the device's conversion of the texel's codes,
recorded as DeviceTexelConversion or HalfTexelConversion. DevicePolicy::texel_conversion and
TexelConversionPolicy go, with Metal's conversion by the bound format's class:
lower::texture::float_texel (its routine, census entry and tests), the float_texel plan flags of
reads and samples, the slots' float_format and the heap's float class, and the field of
RuntimeFact::ExactFormsOverCompilerLimit that named it (encoded, so ARTIFACT_FORMAT_VERSION
456; SEMANTICS_VERSION 1873). The ledger row goes; DeviceTexelConversion is now documented in
docs/API.md section 9 alone (fast_paths classes it Elsewhere), and the conformance cases cite
the note's bound in place of the row. The half routine on Apple's GPUs is untouched.

Verified: clippy --workspace --all-targets --all-features -D warnings clean, plain and with
--cfg m2v_gpu; nextest of fast_paths, device profile, catalogue, degradation, the fit, mechanism,
codec, the snapshot variant, engine_handles, the extended-range heap tests, the texel-conversion
test (rewritten for the device's form alone), the conformance ETC, BC and border cases and the
runtime's fitted-variant notice: passed (one exact-conversion test deleted).

* Take the device's filter of a two-plane YCbCr texture only (ycbcr_filter)

The owner's ruling: promise the GPU's native arithmetic, no exact emulation.
YCbCrFilterPolicy and its Exact form go: no slot takes a YCbCr variant
(RuntimeFact::YCbCrTexture, VariantKey and LoweringInputs::ycbcr_textures,
ProfileFields::ycbcr_variant, Linear::exact_only and the binder's
ycbcr_variant are gone). A natively sampling device filters such a texture's
texels (device-sampling); on MoltenVK Metal's own sampler filters them,
noted where the bound format is two-plane YCbCr (ycbcr-filter-not-exact).
The planes read in place on a device whose memory is the host's are kept:
that is a capability path, Metal's filter exactly.

The FAST-PATHS row goes; HalfTexelConversion, which only that row named, is
classed Elsewhere (API.md's catalogue states it). The YCbCr tests keep the
default's selection and drop the variant's; the uniform-branch test runs at
the default policy; the validation lane's Exact draw test goes.

Verified: cargo clippy --workspace --all-targets --all-features -D warnings,
plain and with --cfg m2v_gpu, clean. nextest over fast_paths, device::tests,
bind::plan, compile::fit, compile::tests, engine_linear_half, catalogue,
degradation, api_surface, codec, cache: 372 passed, 5 failed. The five are
engine_linear_half tests of the emulated sampler on lavapipe and MoltenVK
under EXACT_SAMPLING (the_emulation_reaches_what_metal_measured,
the_linear_sums_run_one_by_a_branch_and_stay_calls,
swizzled_packed_texels_are_the_unswizzled_swizzled,
a_pipelines_texture_notes_follow_its_bound_format_and_sampler,
a_depth_comparison_through_a_filter_is_a_filtered_float_sample); they go with
the emulated sampler in the next step. api_signatures is re-blessed at the
end of the lane.

* Take the device's sampler only (sampling, unorm8_linear_filter)

The owner's ruling of 2026-10-27: promise the GPU's native arithmetic, no
exact emulation. Metal's sampler emulated by fetches (SamplingPolicy::Exact,
a pipeline per bound sampler state) and the device's 8-bit unorm filter at
Metal's footprint step (Unorm8LinearFilterPolicy) are gone with their
switches: every sample, gather and comparison goes to the device's sampler,
Metal's own on MoltenVK (VkProperty::MetalSampler) and the device's
elsewhere (VkProperty::DeviceSampling, PrecisionNote::DeviceSampling).

Deleted: lower/sampler/compared.rs, native.rs, linear/compare.rs,
linear/cube.rs, the nearest and level snaps, the cube face position and
fold (face::snapped, FaceWrap), the span and cube bicubic routines, the heap
depth class (FLAG_DEPTH_*, HANDLE_DEPTH_*, Lookup::Flagged's depth), the
normalized gather snap and the runtime sampler's anisotropic bias route.
Notes nothing records any more are deleted with their catalogue and codec
entries and the runtime's Degradation kinds: DeviceGatherFootprint,
CubeFaceReciprocal, DeviceDepthComparison, DeviceTexelDenormals,
DeviceUnorm8LinearFilter. The fit drops the sampling field of
ExactFormsOverCompilerLimit and makes every module-growing form native in
one reduction.

Kept as capability: bicubic, extended range, heap raw reads, YCbCr planes
read in place (its tests move to engine_ycbcr_in_place), constexpr pixel
samplers' snaps and fetches, the runtime pixel word's gather and footprint
cell, Metal's cube face at a tie, the anisotropic emulation without
samplerAnisotropy and for an unmeasured cube-gradient route, the
VkSampler level clamp on Metal's grid.

Validation and conformance follow: the lanes judge the device's filter
within two codes where it samples natively, the anisotropic lane runs with
samplerAnisotropy withheld, and the conformance cases drop their
device-texel-denormals declarations. docs/API.md, FAST-PATHS.md,
ARCHITECTURE.md, CONTRIBUTING.md and VALIDATION.md updated.

Verified so far: cargo check of the workspace, all targets and features,
plain and --cfg m2v_gpu; 1000 of 3664 translator lib tests passed before
the run was stopped for the rebase.

* Join the device-sampler deletions with development's half and write removals

The rebase onto development left two joins only a build shows:

- `packed_scales` and `PackedField::small` lost their last readers (the
  float texel conversion this branch deleted and the normalized write
  development deleted): both go.
- `engine_srgb_raw` takes `DevicePolicy::default()` where development's
  side named `EXACT_SAMPLING`, so it imports `DevicePolicy` again.

Also formats the conflict resolutions (`cargo fmt --all`).

Verified: `cargo check --workspace --all-targets --all-features` passes.

* Drop the sampler word's snap and level-rule fields with their last readers

With every sample the device's own, no function reads a runtime sampler's
nearest snap (`SamplerWord::NEAREST_BASE`, `NEAREST_SNAP`, `NEAREST_LEVEL`,
`LEVELED_SNAP`) or its level rule (`LEVEL_RULE`); only tests named them.
The constants go, with the word test of the base-level mask; the
`VkSampler` clamp on Metal's level grid (`clamps_on_grid`) stays, and its
docs no longer say the shader reads the rule.

The runtime-sampler tests of `engine_sampler` asked, off MoltenVK, for the
emulation's linear state, leveled snap and level rule: they now state the
device's sample on every committed profile (the pixel fields alone, gated;
`MetalSampler` on MoltenVK, `DeviceSampling` elsewhere; no level field).

Also matches `SnapKind::WordGather` as the unit variant it is (clippy).

Verified: clippy (all targets, all features, -D warnings) passes.

* Test the anisotropic, bias and position paths as the device's sampler runs them

The tests of these paths compiled under the exact sampling policy, which
is gone; under the default each now states what the translation does:

- Metal's anisotropic filter is emulated only without `samplerAnisotropy`
  (and on MoltenVK's unmeasured cube-gradient route), so the emulation's
  shape tests compile on committed profiles with the feature withheld,
  and their MoltenVK arms on the profile as described. An isotropic cube
  keeps the device's gradient sample except on the unmeasured route.
- A bias through a sampler without its own is the `Bias` operand on every
  profile (one test over MoltenVK, RADV, lavapipe and the floor); the
  compile-time and anisotropic axis-gradient tests take a constexpr
  sampler with its own bias, the only one that reaches them. The runtime
  slot's word-chosen axis gradients have no reader left: its test goes,
  with the helpers only it used.
- The position kernel writes three words a lane: its record stride is 12
  bytes, not 16, and the by-word gather test's lane floor matches its
  single pass.

Verified: `cargo check -p metal2vulkan --tests --all-features` clean; the
tests run after the rebase onto development.

* Rewrite the sampling tests and notes for the device's sampler

The sampling, texel-conversion and YCbCr-filter emulations are gone, so
the tests that pinned them now pin the device's answer, and the note
docs that described them describe what the module records today.

Tests: the sampler-unk, anisotropic cube, depth-range, bicubic,
dynamic-offset, heap half-texel, shared-switch, sRGB raw view,
swizzled packed and texture-interpreter families. Deleted the tests of
the emulated linear filter over raw sRGB codes (constexpr and runtime),
the runtime sampler's one-texel raw sample and its switch, the shader's
linear depth comparison, the bicubic small-level comparison against the
linear emulation and the depth read's class conversion; the shared
switch keeps the bicubic emulation alone. A NaN texel's half read only
needs to read a NaN under the default policy.

Docs: HalfSampleFilter, FloatSampleFilter, SrgbTexelDecode,
AnisotropicFilter, DeviceAnisotropicFilter, ViewBaseTexelOffset and
HalfTexelConversion in artifact.rs, RuntimeFact::TexelFormat, the heap
class flag, texel_format_spec and a few comments that still named the
emulated linear filter, snapped gathers or the shader's comparisons.

Verified: plain clippy over the workspace with all targets and
features; the touched families under nextest (see the next commits for
the full runs).
2026-10-28 17:24:20 +02:00
Anees Iqbal 4817f3bdfe Take the device's float maths, rounding order and denormals on every device
One work packet, landed as 3 commits (9fd799bdbb..43bdc4ac17 on archive/development-linear-2026-10-28), in order:

* Take the device's float maths, rounding order and denormals on every device

The owner's ruling: promise the GPU's native arithmetic, no exact emulation.
The translation's own Metal-answer forms for float maths go, and the
device's native form is the only form.

What goes:
- DevicePolicy::float_maths (FloatMathsPolicy) and
  DevicePolicy::rounding_order (RoundingOrderPolicy), their exact_answers()
  lines, serde, docs, and the profile state that carried them
  (FloatFunctions::Device, ProfileFields::rounding_order and
  RoundingOrderRoute); RuntimeFact::ExactFormsOverCompilerLimit loses its
  float_maths and rounding_order fields.
- The maths routines of Metal's answers in lower/arith/libm (atan, exp,
  hyper, log, pair, pi, quarter, rcp, root, rsqrt, sincos, tan, trig) and
  their paths in math.rs: off MoltenVK every call takes the device's
  GLSL.std.450 instruction (or Metal's composition of the device's
  instructions), noted NativeTranscendentals; on MoltenVK the device's
  instruction, Metal's own in the module's mode, with its old notes.
- Metal's precise division routine and its fast reciprocal: a precise and a
  fast division are the device's OpFDiv (NativeDivision), and an frem
  without every flag the device's OpFRem.
- The checked OpFmaKHR, the double, integer and half fused multiply-add
  routines, and the tiny-product check (arith.float.tiny): a fused
  multiply-add is OpFmaKHR, the measured 16-bit Fma, OpFmaKHR under the
  16-bit float controls, or the device's Fma (NativeFma).
- Metal's fused chain for dot, mix and fast::sqrt off MoltenVK: OpDot, FMix
  and Sqrt (NativeDot, NativeMix, NativeTranscendentals). MoltenVK, whose
  float functions are Metal's, keeps Metal's chains.
- The f32 denormal flush taken where the device is not measured to read
  denormals as Metal does (no DriverDeviation::MetalFloatDenormals), and the
  floor and ceil flush: those denormals are the device's, noted
  DeviceDenormals.
- FloatTininessAfterRounding is announced on every device off MoltenVK.

What stays: precise fmod's routine (OpFRem is not the exact remainder past a
quotient of 2^24), ldexp on the bits (GLSL Ldexp is undefined past the
exponent range), double support, and every precision note that describes the
native answer. FloatFn::words charges each function a call takes as before
(the device's instruction where a routine's call was counted).

Tests of the deleted forms are deleted; the tests of the native forms now
check the device's instruction, its note and the interpreter's IEEE answer
(the division, remainder, fmod, fused multiply-add, dot, mix, denormal and
tanh tests), and the roll fixture grows to 13,000 operations so two bodies
stay above the roll size without the flushes. The c3 bound and sign-off
tests expect a subnormal product or quotient on lavapipe to stay open
(its multiply and divisions now record DeviceDenormals) and a product on
MoltenVK, measured to flush as Metal does, to keep Apple's verdict.

Docs: FAST-PATHS.md's two rows become device gaps (the maths library and
divisions; dot, mix and fast::sqrt; the tininess; the denormals), API.md's
policy bullet and catalogue entries, ARCHITECTURE.md's decisions bullet.

Versions: SEMANTICS_VERSION 1878, ARTIFACT_FORMAT_VERSION 461,
RUNTIME_VERSION 1660. REFUSALS.md regenerated unchanged; api_signatures.tsv
is re-blessed in a later commit, after the rebase onto development.

Verified on b1ae235a12, before the rebase onto development 4df472aea2
(whose conflicts the commits after this one check): cargo clippy
--workspace --all-targets --all-features -D warnings with --cfg m2v_gpu;
cargo nextest (--test-threads 4) on the touched modules' tests
(lower::arith, lower::sampler face, position and linear, device::tests,
compile::fit, cache, the engine_* suites touched, engine_roll, fast_paths,
api_surface, api_signatures), the runtime's degradation, catalogue, device
and fitted_variant_notice tests, and the whole metal2vulkan-validation
suite but the runtime-sources pin (left to the landing) and
c3::tests::each_moltenvk_device_compares_with_its_own_gpus_metal (a venue
identity check outside the arithmetic). No device tests ran: the device
lanes compile under --cfg m2v_gpu and were adapted, not run.

* Re-bless the public signatures after the float maths switches' removal

The commit before this one was rebased onto development 4df472aea2. This
commit holds what the rebase left to do:

- api_signatures.tsv re-blessed: against development it drops
  FloatMathsPolicy and RoundingOrderPolicy (their records, fields and
  variants) and ExactFormsOverCompilerLimit's float_maths and
  rounding_order fields. docs/REFUSALS.md regenerated, unchanged.
- corpus-draw-ab's --policy error message: the conflict resolution lost the
  string's line continuation and left a run of spaces in it.
- The DeviceDenormals docs (PrecisionNote and the API.md catalogue entry)
  no longer say the minimum and maximum functions and saturate answer
  Metal at a denormal on every device: under the default policy, and on
  every device once Metal's picks go, they are the device's NMin, NMax and
  NClamp, whose pick of a denormal NativeMinMax records.
- Doc comments this lane wrote past 100 columns refilled.

Verified on this tree: cargo clippy --workspace --all-targets
--all-features -- -D warnings, plain and with --cfg m2v_gpu, clean;
RUSTDOCFLAGS='-D warnings' cargo doc --workspace --all-features --no-deps,
clean; cargo nextest (--test-threads 4) of metal2vulkan filtered to the
touched modules (lower::arith, lower::sampler, device::tests, compile::fit,
cache, the touched engine_* suites) and fast_paths, catalogue,
degradation, profile, mechanism, api_surface and api_signatures: 818 run,
817 passed; of the runtime's degradation, catalogue, device and
fitted_variant_notice tests and the whole metal2vulkan-validation suite:
1402 run, 1400 passed. The three failures fail identically on development
4df472aea2 (run there): engine_float_call_notes::
exported_float_notes_are_the_ones_a_compile_records (fabs_f16 on
moltenvk-m3 records NativeHalfConversion, the half decode's note) and
c3::tests::each_moltenvk_device_compares_with_its_own_gpus_metal (a venue
identity check); and the runtime-sources pin, left to the landing. No
device tests ran.

* Re-pin the runtime sources at the landing tip

The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-10-28 17:24:20 +02:00
Anees Iqbal 0175289314 Batch the development-fast round: tessellation without tessellationShader, primitive ids, mesh tooling, color groups, the vk12 floor, runtime timing and teardown fixes
One commit of the 247 on development-fast (720ef1ce9a..9f46fdf80d), squashed at the user's request.

Translator:
- Tessellation on a device without tessellationShader: Metal's tessellator emitted as SPIR-V, a
  one-workgroup scan placing each patch's triangles in Metal's order, and the post-tessellation
  function as a plain vertex stage (EmulatedTessellationDraws; SEMANTICS 1739, ARTIFACT_FORMAT 419).
- [[primitive_id]] on a device without geometry or tessellation shaders, as a flat varying the
  vertex function writes; indexed lists, lines and points drawn de-indexed (RuntimeGap::PrimitiveIdIndices).
- Fragment functions of more colors than the device draws at once, compiled in color groups
  (PrecisionNote::ColorAttachmentGroups).
- Object functions' threadgroup memory from the render encoder; a kernel's mesh draws from an
  indirect command buffer; mesh payload sizing.
- The Vulkan 1.2 floor profile (vk12-floor) and the gates it needs; Metal 27.0.1 answers as the M3 Max.
- Overflow tests in the runtime-built modules by the product's high word (NVIDIA's compiler fails
  the division form), guarded crate-wide by tests::owned_divisions.

Runtime:
- Color-group passes replayed per group over twin depth/stencil; snapshot and copy-back cost cuts.
- Command buffers finish on the queue waiter that saw them; the waiter holds no device handle, so
  a program's drop after its wait is the device's last.
- Every object an encoder was handed held until its command buffer completes; deallocator order
  and announcements.
- Driver defects recorded and announced: ANV counts a visibility sample once per color output
  (visibility-count-per-color); MoltenVK fails pending work when memory that held a device-address
  buffer is freed, so freed memory waits for the work in flight (host-deallocator-delayed).
- RenderCommandEncoder::set_object_threadgroup_memory_length; Visibility::counting().

Validation: mesh tooling (object, mesh and ICB-mesh cases on both executors), the authoring
census closed, the queue storm judged in Metal's unit, load-robust exits and indirect-census
bounds, and the golden hashes, printouts, fixture inventory and authored compile census blessed.

Docs: FAST-PATHS.md trimmed to a ledger of what is true now; API.md's catalogue and accepted
differences, REFUSALS.md and METAL-COVERAGE.md current.

Verified on development-fast before the squash: the full suites on the RTX 5080, RTX 3090,
RX 7900 XTX, Radeon 780M, Iris Xe, lavapipe and the M3 (MoltenVK and the Metal oracle), lint in
every configuration, rustdoc, doc tests, packaging and public case qualification; the timing and
teardown lanes x5 on every venue; the authoring-capability census 16656/16656 with 0 unresolved,
the vk12-floor translation census at 6139 translated with the slowest row 794 ms and peak 126 MiB.
The tree is development-fast's at 9f46fdf80d.
2026-10-16 11:12:03 +03:00
Anees Iqbal 13b279df1b Squash 11203 commits of translator, runtime, and validation work
Rolls up everything since 43c46ac8 into a single commit. Its tree is
identical to the tree of private master at
b3c77f2d2b20a432be10591a2129547c10b1c24b.

- A Cargo workspace of five crates under crates/: metal2vulkan (the
  translator and the metal2vulkan command), metal2vulkan-runtime (the
  Metal API on Vulkan), metal2vulkan-air (the AIR front end),
  metal2vulkan-validation and metal2vulkan-devtools.
- Dual license: GPL-2.0-or-later OR LGPL-3.0-or-later.
- docs/: API, architecture, fast paths, how-to, Metal coverage,
  refusals, runtime porting and validation guides.

Private-Commit: b3c77f2d2b20a432be10591a2129547c10b1c24b
2026-10-11 20:09:13 +03:00
Anees Iqbal c470af1290 Describe the nesting reconstruction step in the architecture guide
The CFG structurization section still described reconstruction as the bounded
relooper alone. Record that nesting runs first for reducible functions, what a
staged edge is, and why the pass checks its own value flow before adopting a
nesting.
2026-08-31 12:17:22 +03:00
Anees Iqbal 52c961b4de Tighten owned numeric conversion contracts
Split ConversionClass so each width-changing conversion carries its own
shape contract instead of sharing IntegerToInteger and FloatToFloat
buckets. OpUConvert, OpSConvert, and OpFConvert now require the source and
result component widths to differ: a same-width conversion is not a no-op,
it is an invalid instruction. OpUConvert additionally requires an unsigned
result type, since it names a zero extension or truncation.

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

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

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

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

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

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

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

Claude-Session: https://claude.ai/code/session_01D1u4vU7Mr5QNWrnnRHC8iS
2026-08-31 09:03:42 +03:00
Anees Iqbal 9ff250502c Make exact kernel grids safe by default
Model kernel dispatch geometry as a typed contract shared by lowering, reflection, validation, and the CLI. Cull surplus dispatchThreads invocations using fixed or reflected push-constant grid bounds, make that safe dynamic-grid path the default, and require an explicit whole-workgroup assertion to omit it.

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

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

Verified with format checking, warnings-denied workspace clippy and Rustdoc, validation tests at concurrency 16, the unchanged downstream repro, a forced 88,819-row audit completing in one invocation at jobs 16, failure retries, and a zero-read warm pass.
2026-08-22 02:16:13 +03:00
Anees Iqbal 8e95e84d0c Close specialization and descriptor audit gaps
Distinguish image descriptors from texel buffers, scope synthesized binding occupancy by descriptor set, and decouple the Metal texture source limit from configurable descriptor ranges. Centralize retry finalization and runtime sampler projection so layout and specialization contracts cannot drift across paths. Refresh consumer documentation and add adversarial descriptor tests.
2026-08-20 08:31:42 +03:00
Anees Iqbal 7cf240e05a Fix descriptor binding band collisions
Replace overlapping resource bases with checked sampled-texture, sampler, color, imageblock, storage-texture, and synthetic descriptor bands shared by emission and reflection. Reject unknown or cross-class descriptor layouts at the final module boundary, keep constexpr/default allocation inside its band, and bump reflection ABI version 22.

Also resolve kernel function-constant resource locations consistently, coalesce compatible aliases in the Vulkan validation consumer, and cover high/last indices plus sampled/storage aliases end to end.

Verified with serial product and validation tests, warnings-denied workspace clippy and Rustdoc, the packaged descriptor collision repro, a 500-row current-fingerprint translation checkpoint, and release translation at 0.02s / 22,216,704-byte max RSS.
2026-08-20 05:14:56 +03:00
Anees Iqbal adb19e2c2c Make AIR vector layout authoritative
Preserve and parse the source datalayout, use allocation strides through aggregate byte walkers, and correctly map uchar vectors from AIR struct metadata. Record typed mapping outcomes so authoritative metadata cannot disappear silently.\n\nCover scalar families, custom vector alignment, raw and inline lowering, retry emission, metadata matching, and path-based translation.
2026-08-20 03:58:18 +03:00
Anees Iqbal 8b78eaca3b Expand macOS 26 AIR translation coverage
Overhaul the validation workflow around sharded authored cases, dependency-exact observations, incremental indexed corpus audits, bounded parallel translation, and native Metal/Vulkan comparison.\n\nExpand native AIR lowering, reflection, linked-function specialization, resource and stage-interface support, and structural CFG/pointer repair across the harvested macOS 26 corpus. Add exact intrinsic inventory, distributed 16x16x16 matrix lowering, explicit opaque tensor linkage, and regression coverage for the newly supported feature classes.\n\nThe final corpus verification accounts for all 88,819 indexed AIR modules under the current product fingerprint: 65,355 translate and validate directly, 23,464 require exact authored linkage, and zero fail or remain unresolved.
2026-08-13 21:46:27 +02:00
Anees Iqbal 3fbe8e516b Harden AIR translation and consumer validation
Expand structural image, buffer, control-flow, and passthrough lowering, including driver-safe relooper limits and regression coverage.\n\nExpose buffer extent, type, and refined access in reflection v4 for downstream consumers.\n\nHarden corpus oracle planning and loop safety, quarantine non-semantic rows, and refresh the affected translation and execution ledgers.\n\nVerified with cargo fmt --all, workspace clippy with warnings denied, and serial product and validation test suites.
2026-08-10 11:44:46 +02:00
Anees Iqbal 6a14365536 Rework validation corpus workflow around ledgers
Replace the old drift/harvest scripts and generated corpus-test path with
Rust validation binaries that use JSONL ledgers as the durable corpus and
execution record.

- Move translate banking from validation/corpus/drift-ledger.jsonl to
  validation/corpus/metal2vulkan-ledger.jsonl, and seed tracked Metal and
  MoltenVK execution ledgers with hash-identified rows and output_b64
  payloads.
- Add corpus-harvest, corpus-mint, corpus-remint, corpus-why, corpus-triage,
  and corpus-run-{metal,vulkan,moltenvk} binaries for shard harvesting,
  additive/remint translate banking, single-case fallback inspection,
  status triage, and backend execution.
- Rework corpus runners to infer execution plans from shard-backed AIR at run
  time, merge per-run deltas into sorted ledgers, support focused reruns, and
  keep Metal oracle coverage available for translate FALLBACK rows while SPIR-V
  backends remain gated on translate status=ok.
- Bound control-parameter seeding and add loop-budget instrumentation,
  quarantine handling, subprocess timeouts, Ctrl-C worker cleanup, slow-case
  logging, panic backtraces, and MoltenVK/Homebrew Vulkan discovery for safer
  offline execution.
- Consolidate validation helpers for AIR stage/entry parsing, corpus source and
  shard resolution, hashing, JSONL I/O, texture shape policy, translate-ledger
  rows, runner status rows, and triage summaries.
- Remove obsolete Python drift/harvest scripts, generated corpus stubs,
  broken/tolerances sidecars, TOOLCHAIN.lock, and unused validation harness
  modules from the repo surface.
- Update validation, corpus, A/B, architecture, contributing, and agent docs,
  plus gitignore rules, to describe the shard-backed ledger workflow and its
  expected generated artifacts.
2026-07-23 20:01:24 +03:00
Anees Iqbal 3007485352 🆕 Open Source metal2vulkan 2026-07-22 13:15:24 +03:00