Apple's open-source XNU kernel on Android phones: its own loader and drivers, Metal on the Adreno. Runs from RAM; a reboot gives the phone back to Android.
C
An AIR frontend for Mesa: Apple's shader bitcode read, and 275 modules compiled for the Adreno
vcvkk6e55a9f08253
diff --git a/docs/air-report.md b/docs/air-report.mdnew file mode 100644index 0000000..7fe96fe--- /dev/null+++ b/docs/air-report.md@@ -0,0 +1,181 @@+# AIR corpus report++What every module of the system's Metal libraries does when put through the+frontend. Generated by `tools/air/corpus.py`; see docs/air.md section 5 for+what the stages mean. **Reaching ir3 means it compiled, not that it is+correct**: correctness needs the CPU reference and a run on the GPU.++## Stages++| stage | modules | of 456 |+| --- | --- | --- |+| container | 456 | 100% |+| reader | 456 | 100% |+| translate | 275 | 60% |+| ir3 | 275 | 60% |++## By stage of the shader++| what the module is | modules | translate | ir3 |+| --- | --- | --- | --- |+| fragment | 271 | 256 | 256 |+| kernel | 47 | 16 | 16 |+| vertex | 3 | 3 | 3 |+| visible | 135 | 0 | 0 |++The container's TYPE tag agrees with the module's own metadata on 456 of 456; 0 disagree.++## By library++| library | modules | translate | ir3 |+| --- | --- | --- | --- |+| AppleMetalGLRenderer.bundle/default.metallib | 274 | 259 | 259 |+| PortraitFilters.cifilter/default.metallib | 36 | 16 | 16 |+| PortraitFilters.cifilter/portrait_filters.metallib | 135 | 0 | 0 |+| VideoDecoders/AV1SW.metallib | 11 | 0 | 0 |++## Modules that call no `air.*` at all++283 of 456 (62%), of which 262 translate and 262 compile through ir3.++## What is not handled yet, by how many modules it stops++| modules | where it stops |+| --- | --- |+| 135 | stage: air.visible, a library function (not yet) |+| 13 | intrinsic: air.get_width_texture_2d |+| 10 | intrinsic: air.sample_texture_3d |+| 7 | intrinsic: air.read_texture_2d |+| 5 | intrinsic: air.sample_texture_2d |+| 4 | intrinsic: air.get_num_samples_texture_2d_ms |+| 3 | intrinsic: air.write_texture_2d |+| 1 | intrinsic: air.sample_depth_2d |+| 1 | intrinsic: air.read_depth_2d_ms |+| 1 | intrinsic: air.read_texture_2d_ms |+| 1 | intrinsic: air.gather_texture_2d |++## The `air.*` functions the corpus calls++119 distinct names in 173 modules.++| calls | name |+| --- | --- |+| 50 | `air.fast_clamp.f32` |+| 45 | `air.mix.v3f32` |+| 36 | `air.dot.v3f32` |+| 27 | `air.fast_fmin.v3f32` |+| 27 | `air.fast_exp.f32` |+| 26 | `air.fast_fmax.f32` |+| 23 | `air.fast_sqrt.f32` |+| 21 | `air.fast_clamp.v3f32` |+| 20 | `air.fast_fmax.v3f32` |+| 19 | `air.fast_fmin.f32` |+| 16 | `air.fast_clamp.v4f32` |+| 15 | `air.fast_pow.v3f32` |+| 15 | `air.fast_pow.f32` |+| 14 | `air.get_height_texture_2d` |+| 14 | `air.get_width_texture_2d` |+| 13 | `air.mix.v4f32` |+| 12 | `air.sample_texture_2d.v4f32` |+| 12 | `air.convert.f.f32.s.i32` |+| 10 | `air.read_texture_2d.u.v4i16` |+| 9 | `air.write_texture_2d.v4f16` |+| 8 | `air.convert.f.f32.u.i32` |+| 8 | `air.mix.f32` |+| 7 | `air.write_texture_3d.v4f16` |+| 7 | `air.sample_texture_3d.v4f16` |+| 7 | `air.fast_sqrt.v3f32` |+| 7 | `air.fast_pow.v4f32` |+| 7 | `air.fast_sqrt.v4f32` |+| 6 | `air.write_texture_2d.u.v4i16` |+| 6 | `air.convert.u.v2i32.f.v2f32` |+| 6 | `air.fast_floor.v2f32` |+| 6 | `air.convert.f.v3f32.u.v3i32` |+| 5 | `air.atomic.global.store.i32` |+| 5 | `air.convert.s.i32.f.f32` |+| 5 | `air.fast_fabs.v3f32` |+| 5 | `air.sign.v3f32` |+| 5 | `air.convert.f.f32.u.i1` |+| 4 | `air.convert.f.f16.u.i32` |+| 4 | `air.convert.f.f16.s.i32` |+| 4 | `air.min.u.i16` |+| 4 | `air.read_texture_2d.s.v4i16` |+| 4 | `air.get_num_samples_texture_2d_ms` |+| 4 | `air.dot.v4f32` |+| 4 | `air.read_texture_2d.v4f32` |+| 4 | `air.convert.u.i32.f.f32` |+| 4 | `air.dot.v2f32` |+| 4 | `air.wg.barrier` |+| 4 | `air.write_texture_2d.i16.v4f32` |+| 4 | `air.fast_fmax.v4f32` |+| 4 | `air.fast_atan2.f32` |+| 4 | `air.fast_fabs.f32` |+| 3 | `air.saturate.f16` |+| 3 | `air.atomic.global.add.s.i32` |+| 3 | `air.read_texture_2d.i16.v4f32` |+| 3 | `air.atomic.global.add.u.i32` |+| 3 | `air.fast_ldexp.f32` |+| 3 | `air.fast_sin.f32` |+| 3 | `air.fast_cos.f32` |+| 2 | `air.clamp.s.i32` |+| 2 | `air.clamp.s.i16` |+| 2 | `air.clamp.s.v2i16` |+| 2 | `air.convert.u.v2i16.s.v2i32` |+| 2 | `air.clamp.s.v2i32` |+| 2 | `air.convert.s.v2i32.u.v2i16` |+| 2 | `air.convert.s.v2i16.s.v2i32` |+| 2 | `air.convert.s.v2i32.s.v2i16` |+| 2 | `air.read_texture_2d_ms.v4f32` |+| 2 | `air.fmin.f32` |+| 2 | `air.floor.f32` |+| 2 | `air.fast_fract.f32` |+| 2 | `air.sample_texture_3d.v4f32` |+| 2 | `air.atomic.global.max.s.i32` |+| 2 | `air.atomic.global.min.s.i32` |+| 2 | `air.max.s.i32` |+| 2 | `air.min.s.i32` |+| 2 | `air.all.v3i1` |+| 2 | `air.fast_round.f32` |+| 2 | `air.atomic.global.load.i32` |+| 2 | `air.all.v2i1` |+| 2 | `air.convert.f.f16.u.i8` |+| 2 | `air.convert.f.v4f32.u.v4i1` |+| 1 | `air.read_texture_2d.v4f16` |+| 1 | `air.convert.f.f16.u.i16` |+| 1 | `air.sample_texture_2d.s.v4i32` |+| 1 | `air.read_texture_2d_ms.s.v4i32` |+| 1 | `air.sample_texture_3d.s.v4i32` |+| 1 | `air.sample_texture_2d.u.v4i32` |+| 1 | `air.read_texture_2d_ms.u.v4i32` |+| 1 | `air.sample_texture_3d.u.v4i32` |+| 1 | `air.sample_depth_2d.f32` |+| 1 | `air.read_depth_2d_ms.f32` |+| 1 | `air.sample_texture_2d.u.v4i16` |+| 1 | `air.read_texture_2d_ms.u.v4i16` |+| 1 | `air.convert.s.v3i32.f.v3f32` |+| 1 | `air.fast_round.v3f32` |+| 1 | `air.convert.u.v3i32.f.v3f32` |+| 1 | `air.fast_floor.v3f32` |+| 1 | `air.min.s.i16` |+| 1 | `air.max.s.i16` |+| 1 | `air.convert.f.v2f32.s.v2i32` |+| 1 | `air.mix.f16` |+| 1 | `air.fast_saturate.f32` |+| 1 | `air.read_texture_2d.i16.u.v4i32` |+| 1 | `air.gather_texture_2d.u.v4i32` |+| 1 | `air.gather_texture_2d.v4f32` |+| 1 | `air.convert.f.v2f32.s.v2i16` |+| 1 | `air.fast_ceil.f32` |+| 1 | `air.fast_floor.f32` |+| 1 | `air.fmax.f16` |+| 1 | `air.fmin.f16` |+| 1 | `air.fmax.v4f16` |+| 1 | `air.fmin.v4f16` |+| 1 | `air.gather_texture_2d.v4f16` |+| 1 | `air.convert.f.v2f32.u.v2i32` |+| 1 | `air.atomic.local.load.i32` |+| 1 | `air.atomic.local.add.u.i32` |+| 1 | `air.sample_texture_2d.v4f16` |+| 1 | `air.atomic.local.store.i32` |+| 1 | `air.fast_fabs.v4f32` |+| 1 | `air.fast_fmax.v2f32` |diff --git a/docs/air.md b/docs/air.mdnew file mode 100644index 0000000..14e6395--- /dev/null+++ b/docs/air.md@@ -0,0 +1,375 @@+# AIR → NIR: a Metal shader frontend for Mesa++This is the compiler third of running Metal on the Adreno of this port: a translator from Apple's+shader bitcode (AIR, the contents of a `.metallib`) to Mesa's NIR, so that ir3 — the same compiler+that already runs the port's OpenGL ES through freedreno — turns Metal shaders into Adreno code.++The other two thirds are **not** here and are not started: the `_MTLDevice`/`IOGPUMetalDevice`+object graph (AGXMetalA11 alone is 53 classes and 1158 methods, IOGPU.framework 711 more), and the+kernel ABI that submits work. Where a decision below constrains them it says so, and section 7+collects those constraints in one list.++Why this is worth doing at all, and what it costs, is argued in `docs/metal.md` section 9. This+document assumes those measurements and records the decisions taken on top of them.++## 1. Where the frontend lives: inside Mesa, as `src/compiler/air`++**Decision: a Mesa frontend in Mesa's tree, shaped like `src/compiler/spirv`.** Its entry point+is one function, `air_to_nir()` (`nir_air.h`), the analogue of `spirv_to_nir()`. In this+repository the sources are `tools/mesa/air/`; `tools/mk-mesa.sh` and `tools/air/mk-host.sh` copy+them to `src/compiler/air/` of the pinned Mesa release, exactly as `tools/mesa/redwood-drm/` is+copied to `src/redwood-drm/`, and `tools/mesa/air.patch` adds the two lines of meson that build+it. The tree is the shape an upstream merge request would have.++Why not a standalone library that Mesa links:++- **NIR has no stable ABI.** A `nir_shader` is a graph of Mesa-internal structures that change+ every release; `nir_builder` is a header of inline functions. A library outside Mesa producing+ NIR would have to be built against one exact Mesa and versioned with it — it would be inside+ Mesa in everything but name. A library producing something *else* (a serialized NIR, or its own+ IR) would add a second translation for nothing.+- **Everything else that feeds ir3 is in Mesa too:** GLSL, SPIR-V, TGSI, CL. Living beside them+ means the same NIR passes, the same `nir_validate`, the same test framework (`nir_tests`), and+ ir3 changes that break us break in Mesa's own CI.++What it costs the eventual Metal runtime, which must compile from `newLibraryWithData:` (or, more+exactly, at pipeline creation — see 7.1) in-process: **nothing extra**. The runtime must have ir3+in its process anyway, and ir3 is only reachable as part of Mesa; the port already ships Mesa as+one dylib (`libOSMesa.8.dylib`, freedreno and ir3 inside). The frontend adds a few hundred KB of+code to that dylib and no dependency. The cost is the inverse one: the runtime's Mesa must be a+build with this frontend in it, and the runtime calls a Mesa-internal API (`air_to_nir`, then+ir3), so it is compiled against Mesa's headers and moves with Mesa's version.++## 2. How the bitcode is read: our own reader, not LLVM's++This is the biggest commitment of the project, so both sides in full.++**For linking LLVM's bitcode reader** (`llvm::parseBitcodeFile`, then walk an `llvm::Module`):++- It is finished work. It reads every bitcode version, upgrades old constructs (typed pointers,+ old intrinsics) and verifies the module. All 456 modules of the corpus are already read by+ stock `llvm-dis` 22.1.8 without a failure; day one would be spent on translation, not parsing.+- It comes with passes. If a shader ever needs SROA, inlining or `mem2reg` before translation, LLVM+ has them, and a hand-written reader means hand-written equivalents (or NIR's, after translation).+- Future AIR versions (iOS 17, 18…) come from newer Apple LLVMs; LLVM's reader follows them for+ free, ours must be extended.++**Against it, and for our own reader:**++- **The cost lands in every Metal process.** libLLVM is 50–100 MB of C++ with global constructors,+ a static option registry and its own copy of libc++ assumptions, loaded into every app that+ touches Metal. On this port that is every app: CoreAnimation, CoreImage and UIKit all link+ Metal. The port's Mesa is built with `-Dllvm=disabled` (`tools/mk-mesa.sh`) for exactly this+ reason today.+- **It would have to be cross-built for iOS** with the port's toolchain (the `xnu-clang` wrapper,+ the iOS SDK, ld64). That is a multi-hour build and a second large dependency to keep building+ — the project's experience with V8 on musl says what such a build costs to keep alive.+- **Apple already has an LLVM in the shared cache** (MTLCompiler, AGXCompilerCore — 3.6 MB). Ours+ would be a second one in the same process, of a different version. Two-level namespaces keep the+ symbols apart, but it is a hazard nobody needs.+- **The subset is small and measured.** Over all 456 modules (`llvm-bcanalyzer -dump`, then a+ histogram of records), the whole of what occurs is: 17 instruction records (BINOP, CAST, LOAD,+ STORE, GEP, CALL, RET, BR, PHI, CMP2, VSELECT, EXTRACTELT, INSERTELT, SHUFFLEVEC, EXTRACTVAL,+ INSERTVAL, ALLOCA), 6 constant records (INTEGER, FLOAT, NULL, UNDEF, AGGREGATE, DATA,+ CE_CAST), 13 type records and 8 metadata records. No switch, no invoke, no atomics as+ instructions (they are `air.*` calls), no `ptrtoint`/`inttoptr`, no `addrspacecast`, no debug+ info. The bitstream container itself is documented ("LLVM Bitcode File Format") and is a few+ hundred lines.+- **The reader has an exact oracle.** `llvm-dis` prints every module; our reader prints its own+ parse in the same `.ll` syntax for the constructs it supports, and the corpus check diffs the+ two. A reader that agrees with LLVM on 456 modules is not a guess. LLVM stays a *test* tool, not+ a runtime one.+- **Mesa already chose this once.** The DXIL backend (`src/microsoft/compiler/dxil_module.c`)+ writes LLVM 3.7 bitcode by hand rather than link LLVM. The same reasoning applies to reading.++**Decision: our own reader** (`air_bitcode.c`: the bitstream; `air_module.c`: records → an+in-memory IR of the subset). The price is accepted with open eyes: about 2–3 thousand lines of C,+and every new record kind in a future AIR version is work. Unknown records are never skipped+silently: they make the module fail with the record's name, and the corpus report counts them, so+the price is visible as a number rather than as a wrong shader.++**It is written, and it agrees with LLVM on all 456 modules of the corpus** —+`tools/air/reader-check.sh`, 1 900 lines of C for the reader and its printer. What the check+compares is described in section 4; the two things it does *not* keep are function and parameter+attributes (`nounwind`, `captures(none)`, the attribute groups) and the order of declarations,+because the translation uses neither. Everything else — types, constants, every instruction,+metadata, fast-math flags, alignments, calling conventions, linkage — comes back byte for byte.++What would reverse this: if a later AIR (a newer `.metallib` corpus) turned out to need large+parts of LLVM's auto-upgrade machinery, or if translation turned out to need LLVM's own passes+before NIR. Neither is true of iOS 16.5.++## 3. What a translation unit is++A `.metallib` is a container of **one LLVM module per function** (`docs/metal.md` 9.1). The unit+of translation is therefore **one module → one `nir_shader`**, and the stage of that shader is read+from the module's named metadata, never from the container: the container's `TYPE` tag and the+metadata are cross-checked by the corpus tool and disagreements are reported.++| module carries | NIR shader | notes |+| --- | --- | --- |+| `!air.vertex` | `MESA_SHADER_VERTEX`, one entry point | |+| `!air.fragment` | `MESA_SHADER_FRAGMENT`, one entry point | |+| `!air.kernel` | `MESA_SHADER_COMPUTE`, one entry point | threadgroup size is an API value (7.4) |+| `!air.visible` | a library shader: one exported, non-entry `nir_function` | linked at pipeline time (7.5) |++Other functions in a module (helpers, `stitching_traits` methods, `air.static_init` constructors)+become non-entry `nir_function`s and are inlined. Constructors listed in `@llvm.global_ctors`+run at the top of the entry point; that is how function-constant-derived program variables get+their values (AV1SW's `kPixelShift` is computed in one from `kBitDepth`).++**Pointers.** Metal buffers are pointers, and AIR passes them as `ptr addrspace(N)` parameters.+The translator keeps every pointer as *(where, byte offset)*: *where* is a buffer binding, the+threadgroup block, a private allocation or a constant global; the offset is an SSA value computed+from GEPs with the datalayout's sizes. This is NIR's `32bit_index_offset` model and is enough for+the whole corpus (no pointer is ever converted to an integer or between address spaces). Pointers+stored to memory — argument buffers, which no system shader here uses — will need 64-bit global+addresses instead (7.2).++### 3.1 The interface: AIR metadata → NIR++The entry-point node is `!{ptr @fn, !{outputs…}, !{inputs…}}`; each input starts with its+parameter number, each output is a field of the returned `<{…}>` struct, in order. Every entry is a+flat list of `!"air.<key>"` strings, some followed by values. This table is the specification the+translator and its tests are written against. "Seen" is the number of corpus modules carrying the+key (of 456), so the order of work follows it.++**Resources (inputs of every stage)**++| AIR | seen | NIR | binding rule |+| --- | --- | --- | --- |+| `air.buffer`, `air.address_space 2` (constant) | 393 total | `load_ubo` | UBO index = `air.location_index` |+| `air.buffer`, `air.address_space 1` (device) | (of buffers) | `load_ssbo`/`store_ssbo`/`ssbo_atomic` | SSBO index = `air.location_index` |+| `air.buffer`, `air.address_space 3` (threadgroup) | 3 | `load_shared`/`store_shared`, base from a driver uniform | sized at dispatch (7.4) |+| `air.buffer_size N` | 309 | UBO range hint (`range` of `load_ubo`) | |+| `air.read` / `air.write` / `air.read_write` | | `ACCESS_NON_WRITEABLE` etc. on the access | |+| `air.texture` + `air.sample`/`air.read` | 96 | `nir_tex_instr`, `texture_index` = `location_index` | sampled/read textures |+| `air.texture` + `air.write`/`air.read_write` | | `image_store`/`image_load`, image index = `location_index` | storage images (7.3) |+| `air.sampler` | 15 | `sampler_index` = `location_index` | |+| `!air.sampler_states` (inline `constexpr sampler`) | 10 | inline sampler, index after the API ones | state word decoded at translation (M3) |+| `!air.function_constants` | 11 | constant folded from the values given to `air_to_nir` | `!{ptr @g, type, name, index, i1}` |+| `air.struct_type_info`, `air.arg_type_*` | | reflection only, not used for code | layout comes from the LLVM types |++**Vertex stage**++| AIR | NIR |+| --- | --- |+| `air.vertex_input` + `air.location_index n` | `shader_in`, `VERT_ATTRIB_GENERIC0 + n` |+| `air.vertex_id` | `load_vertex_id` (includes the base vertex, as Metal's does) |+| `air.instance_id` | `load_instance_id + load_base_instance` (Metal's includes the base instance, GL's does not) |+| `air.base_vertex` / `air.base_instance` | `load_first_vertex` / `load_base_instance` |+| output `air.position` | `VARYING_SLOT_POS` |+| output `air.vertex_output "name"` | `VARYING_SLOT_VAR0 + k`, `k` = position among user outputs; the name is kept on the variable |+| output `air.point_size` | `VARYING_SLOT_PSIZ` |+| output `air.clip_distance` | `VARYING_SLOT_CLIP_DIST0` (array) |+| output `air.render_target_array_index` / `air.viewport_array_index` | `VARYING_SLOT_LAYER` / `VARYING_SLOT_VIEWPORT` |++**Fragment stage**++| AIR | NIR |+| --- | --- |+| `air.position` | `load_frag_coord`; `origin_upper_left`, half-integer centres (Metal's convention, and Adreno's natively); `.w` is 1/w as in GL |+| `air.fragment_input "name"` | `shader_in`, `VARYING_SLOT_VAR0 + k` matched to the vertex output **by name** (7.5) |+| `air.center` / `air.centroid` / `air.sample` | plain / `centroid` / `sample` on the variable |+| `air.perspective` / `air.no_perspective` / `air.flat` | `INTERP_MODE_SMOOTH` / `NOPERSPECTIVE` / `FLAT` |+| `air.front_facing` | `load_front_face` |+| `air.sample_id`, `air.sample_mask` (input) | `load_sample_id`, `load_sample_mask_in` |+| `air.point_coord` | `load_point_coord` |+| output `air.render_target i32 n, i32 idx` | `FRAG_RESULT_DATA0 + n`, dual-source index `idx` |+| output `air.depth` + `air.depth_qualifier any/greater/less` | `FRAG_RESULT_DEPTH`, `info.fs.depth_layout` |+| output `air.sample_mask` / `air.stencil` | `FRAG_RESULT_SAMPLE_MASK` / `FRAG_RESULT_STENCIL` |+| `air.discard_fragment` | `demote` (Metal keeps the fragment alive for derivatives) |++**Compute stage**++| AIR | NIR |+| --- | --- |+| `air.thread_position_in_grid` | `load_global_invocation_id` |+| `air.thread_position_in_threadgroup` | `load_local_invocation_id` |+| `air.threadgroup_position_in_grid` | `load_workgroup_id` |+| `air.threads_per_threadgroup` | `load_workgroup_size` |+| `air.threadgroups_per_grid` | `load_num_workgroups` |+| `air.threads_per_grid` | `load_num_workgroups × load_workgroup_size` |+| `air.thread_index_in_threadgroup` | `load_local_invocation_index` |+| `air.thread_index_in_simdgroup` / `air.simdgroup_index_in_threadgroup` / `air.threads_per_simdgroup` | `load_subgroup_invocation` / `load_subgroup_id` / `load_subgroup_size` |++The scalar-or-vector type of each of these (`uint`, `uint2`, `uint3`, `ushort…`) comes from the+LLVM parameter type, and the NIR value is cut or converted to it.++**Values and operations**++| AIR / LLVM | NIR |+| --- | --- |+| `i1/i8/i16/i32/i64`, `half/float/double`, vectors ≤ 4 | the same bit sizes; wider vectors are split |+| structs and arrays as SSA values (`insertvalue`, `extractvalue`) | trees of SSA values inside the translator, never NIR values |+| `br`, `phi` (unstructured CFG) | an unstructured `nir_function_impl`, then `nir_lower_goto_ifs` — the path Mesa's OpenCL frontend uses |+| `alloca` | `load_scratch`/`store_scratch` on a per-invocation block (ir3 private memory) |+| `addrspace(2)` global `constant` with initializer | `nir->constant_data` + `load_constant` |+| `addrspace(2)` global without `constant` (program-scope variables) | a private copy per invocation (written by the constructors) |+| `fast` flags on an instruction | the NIR ALU is not `exact`; without them it is |+| `air.<op>.<type suffix>` | one handler per op in `air_intrinsics.c`; the suffix is checked against the LLVM types, not trusted |++## 4. How it is proven right++A shader is reported as *working* only when its output was compared, never because it compiled.+Three references, each independent of the translator:++1. **LLVM on the CPU (the strongest).** `tools/air/cpuref` retargets the module to the host,+ compiles it with `llc` and calls the entry point from a harness that fills its parameters from+ the same metadata (buffers with seeded data, varyings, position, thread ids) and implements the+ `air.*` functions in C. LLVM — not our reader, not our translator — decides what the shader+ means. Needs no Apple hardware and no GPU.+2. **The same shader through our NIR on two different Mesa backends.** `air-run` renders (or+ dispatches) the translated NIR with Gallium: on the host through softpipe (NIR → TGSI →+ an interpreter in C), on the phone through freedreno/ir3 on the Adreno. Both outputs are+ compared numerically to (1), per pixel or per buffer element, against a tolerance stated per+ comparison (exact for integer results; a few ULP for arithmetic; looser only where Metal's own+ `fast_` functions allow it, and then it is printed).+3. **NIR's own checks:** `nir_validate` after every pass (the translator runs with validation+ on), and unit tests on Mesa's `nir_tests` framework for the translator's building blocks.++Where a shader has a known GLSL equivalent (AppleMetalGLRenderer's shaders *are* the GL+pipeline's fixed functions), rendering both through the port's GLES and comparing images is a+fourth check; it is not built yet.++The bitcode reader has its own oracle (section 2): its parse is printed as `.ll` and diffed+against `llvm-dis` for every module of the corpus.++## 4a. What it does and does not keep++Written down because a reader that silently drops something is worse than one that refuses:++- **Not kept, and not needed:** attributes (`nounwind`, `memory(none)`, `captures(none)`,+ `dereferenceable`, the `#N` groups), the identification block, debug info, the symbol table's+ order, use lists, operand bundles. None of them carries meaning the translation reads.+- **Kept but unused so far:** `air.struct_type_info` and the `air.arg_type_*` keys (reflection:+ the runtime will want them for `MTLArgument`), TBAA, the module's hash.+- **Refused rather than guessed:** every record kind not in the subset, a pointer stored to memory+ or cast to an integer, a `switch`, a call through a pointer, a struct field chosen at run time,+ a vector `getelementptr`. Each refusal names what it was and lands in the report's table.++Two things the translation leaves to its consumer, by Mesa's convention rather than by choice:+**system values** (`load_global_invocation_id` and the rest are emitted as NIR's own, and the+driver lowers them with `nir_lower_system_values` / `nir_lower_compute_system_values`, exactly as+the SPIR-V frontend does) and **I/O lowering** (variables with locations, then `nir_lower_io`).++## 5. Milestones and how each is measured++The corpus report (`tools/air/corpus.py report`) is the progress meter: every number below comes+out of it, and it runs from `tools/air/check.sh` (section 6). Two corpora:++- **the device image** — the five `.metallib` files the port installs (`ios165/rootfs` ++ `ios165/cryptex`): 456 modules. This is the corpus the milestones are stated against.+- **the full IPSW** — all 134 MTLB libraries of the iOS 16.5 root filesystem and cryptexes,+ 16 841 functions, extracted from `rootfs.dmg` with 7-Zip. Reported alongside, because the+ device image is a selection and the system's own shaders are this set.++Each module goes through stages, and the report counts how many reach each: *container* (the+module is found and unwrapped) → *llvm-dis* (stock LLVM reads it) → *reader* (ours reads it and+agrees with `llvm-dis`) → *translate* (`air_to_nir` succeeds and `nir_validate` passes) → *ir3*+(compiles for Adreno 7c+ Gen 3, chip 0x06030500, without error) → *softpipe* (output matches the+CPU reference) → *adreno* (output on the phone matches the CPU reference). A module that stops is+counted under the first stage it fails and the reason (an unknown record, an unhandled `air.*`,+an unhandled metadata key), so "features not yet handled" is a ranked list, not a guess.++- **M0** — container and corpus: every module reaches *llvm-dis*; the report exists.+ **Done**, and further than stated: all 456 also pass *reader*, our own reader agreeing with+ `llvm-dis` on every one.+- **M1** — `clearFragment01` reaches *adreno*: translated, compiled by ir3, rendered on the+ Adreno, framebuffer equal to the colour in its constant buffer.+ **Compiled, not yet run.** It is `nir_load_ubo` + a store to `FRAG_RESULT_DATA0` as predicted,+ and ir3 turns it into five Adreno instructions (four `mov`s out of the constant file, which is+ where ir3 promoted the UBO load to). The framebuffer half of the test needs the phone.+- **M2** — the 283 modules with no `air.*` call: a stated fraction reach *ir3*, a growing subset+ *softpipe*/*adreno*.+ **262 of the 283 reach ir3.** The other 21 are `air.visible` library functions, which are not+ entry points at all (below). Counting every entry point rather than every module: 275 of 321,+ 86%.+- **M3** — textures and samplers, each form with a test that renders a known image.+ Not started, and it is what nearly everything left is waiting for: 46 modules stop at a texture+ call, including all 11 of AV1SW's.+- **M4** — atomics, barriers, threadgroup memory, compute against the CPU reference.+ Atomics, the barrier and threadgroup memory are written (`air_intrinsics.c`) and 16 kernels+ compile through ir3 with them; none has been *run*, so M4's acceptance test is untouched.++### `air.visible`, and why 135 modules are none of these milestones++135 of the 456 modules — every one in `portrait_filters.metallib` — carry `!air.visible`+instead of a stage. They are CoreImage's stitchable kernels: library functions, with+`air.visible_input`/`air.visible_output` interfaces and `air.stitching_info` describing how+CoreImage assembles them into a shader at run time. They have no entry point, so there is no+`nir_shader` to make of one by itself; each becomes a `nir_function` linked into its caller at+pipeline time (`nir_link_shader_functions`). The translator refuses them with+`stage: air.visible` so that the report counts them as one known thing rather than as 135+failures. 21 of them call no `air.*` at all, which is why the intrinsic-free count (283) and the+M2 count (262) differ.++## 6. Running it++```+tools/air/mk-host.sh # Mesa for this machine (x86-64): the frontend, ir3, softpipe+tools/air/check.sh # the reader against llvm-dis, then the corpus report+```++and on one shader:++```+build/mesa-host/build/src/compiler/air/air2nir --ll FILE[.metallib] [FUNCTION] # what the reader read+build/mesa-host/build/src/compiler/air/air2nir FILE[.metallib] [FUNCTION] # the NIR+build/mesa-host/build/src/gallium/drivers/freedreno/ir3_compiler \+ --chip-id 0x007506030500 FILE[.metallib] [FUNCTION] # Adreno code+```++`0x007506030500` is how freedreno names the redwood's Adreno 7c+ Gen 3 (A635); it has no+`gpu-id`, which is why `tools/mesa/air-ir3.patch` adds `--chip-id` to that tool.++There is no hosted CI: the corpus is Apple's code and stays out of the repository (and out of+GitHub). `check.sh` is the CI; it takes 20 seconds, so it runs before every commit that touches+the frontend, and the report it writes is committed as `docs/air-report.md` with the numbers of+that commit.++The frontend lives in `tools/mesa/air/` and `mk-host.sh` links it into the pinned Mesa as+`src/compiler/air` — a link, not a copy, so there is no stale copy to build by mistake (a trap+this project has already fallen into once with `tools/mk-mesa.sh` and the freedreno patches).+`tools/mesa/air-ir3.patch` is the two-file change that teaches `ir3_compiler` to read AIR;+it also removes a call of `ir3_nir_lower_variant` that tool makes itself, which is a bug of+the tool — `ir3_context_init` already calls it on its own clone, and the const-state setup+inside asserts the second time. It shows on every vertex shader and on anything with image+dimensions, and hid on everything else, which is presumably how it survived.++Needed on this machine: meson, ninja, bison, flex, python3 with venv, and LLVM's `llvm-as` /+`llvm-dis` for the reader check (22.1.8 here). The host build also patches Mesa 25.0's+`src/c11/threads.h`, because glibc 2.43 and later declare C11's `once_flag` and `call_once` in+`<stdlib.h>` and Mesa defines them again; the iOS cross build has its own libc and does not.++## 7. What this decides for the runtime (2) and the kernel ABI (3)++1. **Compilation happens at pipeline creation, not at `newLibraryWithData:`.** Function constants+ (`newFunctionWithName:constantValues:`), vertex/fragment varying linking and visible-function+ linking are only known then. The library step can translate eagerly and cache NIR; the ir3+ step cannot run before the pipeline. (On real iOS the compile also leaves the process, for+ `MTLCompilerService`; whether this runtime does the same is a decision for (2), and NIR+ serialization — `nir_serialize` — makes either possible.)+2. **Buffers are bound per stage by index, as UBOs (constant) and SSBOs (device).**+ `setVertexBuffer:offset:atIndex:` maps to the UBO or SSBO slot `index` of that stage; the+ frontend reports which kind each index is. Adreno's UBO and SSBO base addresses have alignment+ rules Metal's offsets do not (Metal allows 4-byte offsets for constant buffers); the runtime+ must bind an aligned base and the frontend will take the remainder from a driver uniform when+ that becomes necessary. Argument buffers (pointers in memory) will need GPU virtual addresses+ of buffers stable across submissions — a requirement on (3) — and 64-bit global access.+3. **One Metal texture index may be a sampler view or an image** depending on the shader's access+ qualifier; the frontend reports which, the runtime binds accordingly.+4. **Threadgroup memory passed as an argument is sized at dispatch**+ (`setThreadgroupMemoryLength:atIndex:`): the translator addresses it from base offsets in a+ driver uniform and Gallium's `variable_shared_mem` carries the total (as rusticl does for+ OpenCL `__local` arguments). The threadgroup size is a dispatch argument too+ (`dispatchThreadgroups:threadsPerThreadgroup:`), so `workgroup_size` is not fixed in NIR.+5. **Vertex outputs and fragment inputs match by name** (`"generated(8texcoordDv2_f)"`, `user(...)`),+ not by location: a pipeline-time link step assigns the same `VARYING_SLOT_VAR*` to the same+ name on both sides. Visible functions (CoreImage's 135 stitchable kernels are all of this+ kind) are linked into the calling shader by name with `nir_link_shader_functions`.+6. **Clip space and the framebuffer are Metal's:** NDC depth is [0, 1] (`clip_halfz`), the+ framebuffer origin is the top-left; the frontend emits no flips, the runtime's viewport and+ rasterizer state must say this.+7. **Inline samplers** (`constexpr sampler` in the source, `!air.sampler_states`) are created by+ the runtime from the state the frontend decodes and bound after the API's samplers.diff --git a/tools/air/check.sh b/tools/air/check.shnew file mode 100755index 0000000..677f811--- /dev/null+++ b/tools/air/check.sh@@ -0,0 +1,55 @@+#!/bin/bash+# The frontend's whole test run, in the order of what it proves (docs/air.md+# section 4): first that the bitcode reader agrees with LLVM on every module of+# the corpus, then how far every module gets through translation and ir3.+#+# This is the project's CI. There is no hosted one -- the corpus is Apple's+# code and stays off the network -- so this runs before every commit that+# touches the frontend, and docs/air-report.md is the report of that commit.+#+# tools/air/check.sh check, and write docs/air-report.md+# tools/air/check.sh -q only the numbers, write nothing+set -e+ROOT=$(cd "$(dirname "$(readlink -f "$0")")/../.." && pwd)+IOS=${IOS:-$ROOT/ios165}+QUIET=0+[ "${1:-}" = "-q" ] && QUIET=1++# The corpus: the MTLB libraries of the device image. The five are named rather+# than searched for, so a missing one is an error and not a smaller corpus.+LIBS=(+ "$IOS/rootfs/System/Library/VideoDecoders/AV1SW.metallib"+ "$IOS/rootfs/System/Library/Extensions/AppleMetalGLRenderer.bundle/default.metallib"+ "$IOS/rootfs/System/Library/CoreImage/PortraitFilters.cifilter/default.metallib"+ "$IOS/rootfs/System/Library/CoreImage/PortraitFilters.cifilter/portrait_filters.metallib"+)+# SafariSharedUI's default.metallib is in the corpus list of docs/air.md and is+# deliberately not here: it is 118 bytes and holds no functions at all.+for f in "${LIBS[@]}"; do+ [ -f "$f" ] || { echo "check.sh: missing $f"; exit 1; }+done++AIR2NIR=$ROOT/build/mesa-host/build/src/compiler/air/air2nir+[ -x "$AIR2NIR" ] || { echo "check.sh: run tools/air/mk-host.sh first"; exit 1; }++WORK=$(mktemp -d)+trap 'rm -rf "$WORK"' EXIT++echo "== the reader against llvm-dis"+for f in "${LIBS[@]}"; do+ python3 "$ROOT/tools/metallib.py" dump "$f" "$WORK/$(basename "$(dirname "$f")")" > /dev/null+done+"$ROOT/tools/air/reader-check.sh" "$WORK" | tail -3+reader_rc=${PIPESTATUS[0]}++echo+echo "== translation and ir3, over the corpus"+if [ "$QUIET" = 1 ]; then+ python3 "$ROOT/tools/air/corpus.py" --ir3 --md /dev/null "${LIBS[@]}"+else+ python3 "$ROOT/tools/air/corpus.py" --ir3 \+ --md "$ROOT/docs/air-report.md" --json "$ROOT/build/air-report.json" "${LIBS[@]}"+ echo "check.sh: wrote docs/air-report.md"+fi++exit $reader_rcdiff --git a/tools/air/corpus.py b/tools/air/corpus.pynew file mode 100755index 0000000..ad4940d--- /dev/null+++ b/tools/air/corpus.py@@ -0,0 +1,219 @@+#!/usr/bin/env python3+"""The corpus report: how far every module of every .metallib gets.++This is the project's progress meter (docs/air.md section 5). Each module goes+through stages, and each module is counted under the first one it fails:++ container found in the .metallib and unwrapped+ reader our bitcode reader read it (and agrees with llvm-dis: that is+ checked separately, by tools/air/reader-check.sh)+ translate air_to_nir produced a shader and nir_validate passed+ ir3 ir3 compiled it for the Adreno without error++Nothing here says a shader is correct: that needs the CPU reference and a run+on the GPU. A module that reaches ir3 has compiled, which is not the same+thing, and the report never claims otherwise.++usage: corpus.py [--ir3] [--json FILE] [--md FILE] FILE.metallib...+"""+import argparse+import collections+import json+import os+import subprocess+import sys++ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+AIR2NIR = os.environ.get(+ "AIR2NIR", os.path.join(ROOT, "build/mesa-host/build/src/compiler/air/air2nir"))+IR3 = os.environ.get(+ "IR3", os.path.join(ROOT, "build/mesa-host/build/src/gallium/drivers/freedreno/ir3_compiler"))+# the redwood's Adreno 7c+ Gen 3 (A635), as freedreno names it+CHIP_ID = os.environ.get("AIR_CHIP_ID", "0x007506030500")+++def read_report(paths):+ """air2nir --report, which forks per module so one crash is one line."""+ rows = []+ for path in paths:+ out = subprocess.run([AIR2NIR, "--report", path], capture_output=True, text=True)+ for line in out.stdout.splitlines():+ if not line.startswith("module="):+ continue+ row = dict(kv.split("=", 1) for kv in line.split("\t") if "=" in kv)+ # two of the five libraries are both called default.metallib, so+ # the label carries the bundle they are in+ row["library"] = os.path.join(os.path.basename(os.path.dirname(path)),+ os.path.basename(path))+ row["path"] = path+ row["calls"] = [c for c in row.get("calls", "").split(",") if c]+ rows.append(row)+ return rows+++def run_ir3(rows):+ """ir3 on every module that translated, one process each."""+ for row in rows:+ if row.get("translate") != "ok":+ continue+ out = subprocess.run([IR3, "--chip-id", CHIP_ID, row["path"], row["module"]],+ capture_output=True, text=True, timeout=300)+ if out.returncode == 0:+ row["ir3"] = "ok"+ for line in out.stdout.splitlines():+ # "; FRAG prog 0/0: 5 instr, 0 nops, ..."+ if " prog " in line and " instr," in line:+ row["ir3_instr"] = int(line.split(":")[1].split()[0])+ break+ else:+ row["ir3"] = "fail"+ err = (out.stderr or out.stdout).strip().splitlines()+ row["ir3_error"] = err[-1][:200] if err else "no message"+++def reason(row):+ if row.get("crash"):+ return "crashed: " + row["crash"]+ if row.get("reader") != "ok":+ return row.get("error", "reader failed")+ if row.get("translate") != "ok":+ return row.get("error", "translation failed")+ if row.get("ir3") == "fail":+ return "ir3: " + row.get("ir3_error", "")+ return None+++def short_reason(r):+ """Group reasons so the table ranks causes, not instances."""+ if r is None:+ return None+ r = r.split(" (block ")[0]+ if r.startswith("intrinsic: air."):+ name = r.split("intrinsic: ")[1].split("(")[0].strip()+ # air.sample_texture_2d.v4f16 -> air.sample_texture_2d+ base = name.split(".")+ if len(base) > 2:+ name = ".".join(base[:2]) if base[1] in ("atomic", "wg") else ".".join(base[:2])+ return "intrinsic: " + name+ return r+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("libs", nargs="+")+ ap.add_argument("--ir3", action="store_true", help="also compile through ir3")+ ap.add_argument("--json")+ ap.add_argument("--md")+ args = ap.parse_args()++ rows = read_report(args.libs)+ if not rows:+ sys.exit("corpus.py: no modules; is %s built?" % AIR2NIR)+ if args.ir3:+ run_ir3(rows)++ total = len(rows)+ stages = collections.OrderedDict()+ stages["container"] = total+ stages["reader"] = sum(1 for r in rows if r.get("reader") == "ok")+ stages["translate"] = sum(1 for r in rows if r.get("translate") == "ok")+ if args.ir3:+ stages["ir3"] = sum(1 for r in rows if r.get("ir3") == "ok")++ by_stage = collections.Counter(r.get("stage", "?") for r in rows)+ ok_by_stage = collections.Counter(r.get("stage", "?") for r in rows+ if r.get("translate") == "ok")+ ir3_by_stage = collections.Counter(r.get("stage", "?") for r in rows+ if r.get("ir3") == "ok")+ reasons = collections.Counter(short_reason(reason(r)) for r in rows+ if reason(r) is not None)+ intrinsics = collections.Counter(c for r in rows for c in r["calls"])+ no_intrinsics = [r for r in rows if not r["calls"]]++ out = []+ out.append("# AIR corpus report\n")+ out.append("What every module of the system's Metal libraries does when put through the\n"+ "frontend. Generated by `tools/air/corpus.py`; see docs/air.md section 5 for\n"+ "what the stages mean. **Reaching ir3 means it compiled, not that it is\n"+ "correct**: correctness needs the CPU reference and a run on the GPU.\n")+ out.append("## Stages\n")+ out.append("| stage | modules | of %d |" % total)+ out.append("| --- | --- | --- |")+ for name, n in stages.items():+ out.append("| %s | %d | %.0f%% |" % (name, n, 100.0 * n / total))+ out.append("")++ out.append("## By stage of the shader\n")+ out.append("| what the module is | modules | translate | ir3 |")+ out.append("| --- | --- | --- | --- |")+ for st in sorted(by_stage):+ out.append("| %s | %d | %d | %s |" % (st, by_stage[st], ok_by_stage[st],+ ir3_by_stage[st] if args.ir3 else "-"))+ out.append("")++ # The container's TYPE tag and the module's own metadata are two+ # independent statements of what a function is; if they ever disagree, one+ # of the two readings is wrong and the report says so rather than picking.+ same = {"vertex": "vertex", "fragment": "fragment", "kernel": "kernel",+ "visible": "visible"}+ mismatch = [r for r in rows+ if r.get("container") in same and r.get("stage")+ and same[r["container"]] != r.get("stage")]+ out.append("The container's TYPE tag agrees with the module's own metadata on %d of %d; "+ "%d disagree.\n" % (total - len(mismatch), total, len(mismatch)))+ for r in mismatch[:20]:+ out.append("- `%s`: container says %s, metadata says %s" %+ (r["module"], r["container"], r["stage"]))+ if mismatch:+ out.append("")++ out.append("## By library\n")+ out.append("| library | modules | translate | ir3 |")+ out.append("| --- | --- | --- | --- |")+ for lib in sorted({r["library"] for r in rows}):+ rs = [r for r in rows if r["library"] == lib]+ out.append("| %s | %d | %d | %s |" % (+ lib, len(rs), sum(1 for r in rs if r.get("translate") == "ok"),+ sum(1 for r in rs if r.get("ir3") == "ok") if args.ir3 else "-"))+ out.append("")++ out.append("## Modules that call no `air.*` at all\n")+ out.append("%d of %d (%.0f%%), of which %d translate and %s compile through ir3.\n" % (+ len(no_intrinsics), total, 100.0 * len(no_intrinsics) / total,+ sum(1 for r in no_intrinsics if r.get("translate") == "ok"),+ sum(1 for r in no_intrinsics if r.get("ir3") == "ok") if args.ir3 else "-"))++ if reasons:+ out.append("## What is not handled yet, by how many modules it stops\n")+ out.append("| modules | where it stops |")+ out.append("| --- | --- |")+ for why, n in reasons.most_common():+ out.append("| %d | %s |" % (n, why.replace("|", "\\|")))+ out.append("")++ if intrinsics:+ out.append("## The `air.*` functions the corpus calls\n")+ out.append("%d distinct names in %d modules.\n" % (+ len(intrinsics), sum(1 for r in rows if r["calls"])))+ out.append("| calls | name |")+ out.append("| --- | --- |")+ for name, n in intrinsics.most_common():+ out.append("| %d | `%s` |" % (n, name))+ out.append("")++ text = "\n".join(out)+ if args.md:+ with open(args.md, "w") as f:+ f.write(text)+ else:+ print(text)+ if args.json:+ with open(args.json, "w") as f:+ json.dump({"total": total, "stages": stages, "rows": rows}, f, indent=1)++ print("corpus.py: %s" % ", ".join("%s %d/%d" % (k, v, total) for k, v in stages.items()),+ file=sys.stderr)+++if __name__ == "__main__":+ main()diff --git a/tools/air/mk-host.sh b/tools/air/mk-host.shnew file mode 100755index 0000000..35b7711--- /dev/null+++ b/tools/air/mk-host.sh@@ -0,0 +1,100 @@+#!/bin/bash+# Build Mesa for THIS machine (x86-64 Linux) with the AIR frontend in it: the+# frontend itself, ir3 (so a Metal shader can be compiled for the Adreno+# without the phone) and softpipe (so it can be run without a GPU at all).+#+# This is the frontend's development and test build. The one that goes on the+# phone is tools/mk-mesa.sh, which cross-compiles for iOS; both take the+# frontend from tools/mesa/air, so what is tested here is what runs there.+#+# Nothing of Mesa is in the repository: the pinned release is fetched, patched+# with tools/mesa/*.patch, and src/compiler/air is a symbolic link back to+# tools/mesa/air so that editing the frontend needs no copying.+#+# What comes out, in build/mesa-host/build:+# src/compiler/air/air2nir the frontend alone+# src/gallium/drivers/freedreno/ir3_compiler AIR -> NIR -> Adreno+set -e+ROOT=$(cd "$(dirname "$(readlink -f "$0")")/../.." && pwd)+VERSION=25.0.7+SHA256=592272df3cf01e85e7db300c449df5061092574d099da275d19e97ef0510f8a6+B=$ROOT/build/mesa-host+SRC=$B/mesa-$VERSION+mkdir -p "$B"+cd "$B"++PATCHES=$(cat "$ROOT"/tools/mesa/air*.patch | sha256sum | cut -d' ' -f1)+if [ ! -d "$SRC" ] || [ "$(cat "$SRC/.air-patches" 2>/dev/null)" != "$PATCHES" ]; then+ if [ ! -f mesa-$VERSION.tar.xz ]; then+ # the cross build may already have fetched it+ if [ -f "$ROOT/xnu-deps/build/mesa/mesa-$VERSION.tar.xz" ]; then+ cp "$ROOT/xnu-deps/build/mesa/mesa-$VERSION.tar.xz" .+ else+ curl -sL --fail -o mesa-$VERSION.tar.xz \+ https://archive.mesa3d.org/mesa-$VERSION.tar.xz+ fi+ fi+ echo "$SHA256 mesa-$VERSION.tar.xz" | sha256sum -c --quiet+ rm -rf "$SRC" build+ tar xJf mesa-$VERSION.tar.xz+ for p in "$ROOT"/tools/mesa/air-*.patch; do+ patch -s --no-backup-if-mismatch -d "$SRC" -p1 < "$p"+ done++ # glibc 2.43 and later declare C11's once_flag and call_once in <stdlib.h>,+ # which clashes with Mesa 25.0's own definitions in src/c11/threads.h. Only+ # this host build hits it; the iOS cross build has its own libc.+ python3 - "$SRC" <<-'PY'+ import sys+ root = sys.argv[1]+ p = root + '/src/c11/threads.h'+ s = open(p).read()+ old = "typedef pthread_once_t once_flag;\n# define ONCE_FLAG_INIT PTHREAD_ONCE_INIT\n"+ new = ("# if defined(__GLIBC__) && __GLIBC_USE(ISOC23) && !defined(__cplusplus)\n"+ "# define C11_LIBC_HAS_CALL_ONCE 1\n"+ "# else\n"+ "typedef pthread_once_t once_flag;\n"+ "# define ONCE_FLAG_INIT PTHREAD_ONCE_INIT\n"+ "# endif\n")+ if old in s:+ open(p, 'w').write(s.replace(old, new))+ p = root + '/src/c11/impl/threads_posix.c'+ s = open(p).read()+ old = "call_once(once_flag *flag, void (*func)(void))\n{\n pthread_once(flag, func);\n}\n"+ if old in s and 'C11_LIBC_HAS_CALL_ONCE' not in s:+ i = s.index(old)+ j = s.rfind('\n\n', 0, i)+ s = (s[:j] + "\n\n#ifndef C11_LIBC_HAS_CALL_ONCE" + s[j:i + len(old)] ++ "#endif\n" + s[i + len(old):])+ open(p, 'w').write(s)+ PY++ # the frontend itself, as a link: no copy to forget to refresh+ rm -rf "$SRC/src/compiler/air"+ ln -s "$ROOT/tools/mesa/air" "$SRC/src/compiler/air"+ grep -q "subdir('air')" "$SRC/src/compiler/meson.build" ||+ sed -i "s|^subdir('spirv')|subdir('spirv')\nsubdir('air')|" "$SRC/src/compiler/meson.build"++ echo "$PATCHES" > "$SRC/.air-patches"+fi++if [ ! -x venv/bin/python3 ]; then+ python3 -m venv venv+ venv/bin/pip -q install mako pyyaml packaging+fi+export PATH=$B/venv/bin:$PATH++[ -f build/build.ninja ] || meson setup build "$SRC" --buildtype=debugoptimized \+ -Dplatforms= -Dgallium-drivers=softpipe,freedreno -Dfreedreno-kmds=msm \+ -Dvulkan-drivers= -Dglx=disabled -Degl=disabled -Dgbm=disabled -Dllvm=disabled \+ -Dopengl=true -Dgles2=enabled -Dshader-cache=disabled -Dvalgrind=disabled \+ -Dlibunwind=disabled -Dglvnd=disabled -Dvideo-codecs= -Dtools= \+ -Dgallium-vdpau=disabled -Dgallium-va=disabled -Dgallium-xa=disabled \+ -Dlmsensors=disabled -Dbuild-tests=true -Dzstd=disabled -Dxmlconfig=disabled \+ -Dexpat=disabled > meson-setup.log++ninja -C build src/compiler/air/air2nir \+ src/gallium/drivers/freedreno/ir3_compiler > ninja.log++echo "mk-host.sh: $B/build/src/compiler/air/air2nir"+echo "mk-host.sh: $B/build/src/gallium/drivers/freedreno/ir3_compiler"diff --git a/tools/air/reader-check.sh b/tools/air/reader-check.shnew file mode 100755index 0000000..5e14507--- /dev/null+++ b/tools/air/reader-check.sh@@ -0,0 +1,93 @@+#!/bin/bash+# Check our bitcode reader against LLVM's, module by module.+#+# For each module: llvm-dis prints it, and air2nir --ll prints what our reader+# read. Neither output is compared directly -- the two printers differ in+# whitespace, in attribute groups and in how they number metadata -- so both+# go through llvm-as | llvm-dis first, which puts them in one canonical form,+# and then through the same filter (below). What is left is compared exactly.+#+# A module where llvm-as refuses our output is a reader bug or a printer bug+# either way, and is reported as such; a module where the two canonical forms+# differ is printed with its diff.+#+# usage: reader-check.sh [-v] MODULE.bc... (or .metallib, or a directory)+set -u+ROOT=$(cd "$(dirname "$(readlink -f "$0")")/../.." && pwd)+AIR2NIR=${AIR2NIR:-$ROOT/build/mesa-host/build/src/compiler/air/air2nir}+VERBOSE=0+[ "${1:-}" = "-v" ] && { VERBOSE=1; shift; }+WORK=$(mktemp -d)+trap 'rm -rf "$WORK"' EXIT++# What both sides are reduced to: the semantics the reader keeps. Attributes,+# the module identification, and the symbol-table order are not kept, so they+# are dropped from both sides rather than silently differing.+filter() {+ grep -v '^;' |+ grep -v '^attributes #' |+ grep -v '^source_filename' |+ sed -E -e 's/ #[0-9]+//g' -e 's/^(define|declare) (dso_local |dllexport |hidden |protected )*/\1 /' -e 's/(captures|dereferenceable|dereferenceable_or_null|align|range|elementtype|byval|byref|sret|inalloca|preallocated|alignstack|allocsize)\([^)]*\)//g' -e 's/\b(noalias|readonly|readnone|writeonly|writable|nocapture|nonnull|immarg|zeroext|signext|noundef|nofree|nosync|nest|returned|inreg|initializes|allocalign|allocptr|dead_on_unwind|nocallback|willreturn|norecurse|nounwind|speculatable|mustprogress)\b//g' -e 's/ align [0-9]+ (%|@)/ \1/g' -e 's/ +/ /g; s/ +$//; s/\( /(/g; s/ \)/)/g; s/ ,/,/g; s/\(,/(/g' |+ grep -v '^ *$'+}++# Declarations carry no order in LLVM IR, and llvm-as/llvm-dis does not keep+# the one it was given, so both sides put them last and sorted.+sort_declares() {+ cat > "$WORK/c.ll"+ grep -v '^declare ' "$WORK/c.ll"+ grep '^declare ' "$WORK/c.ll" | sort+}++canon() { # stdin: .ll -> canonical .ll on stdout, or nothing and rc != 0+ llvm-as -o "$WORK/a.bc" 2> "$WORK/as.err" &&+ llvm-dis -o - "$WORK/a.bc" | filter | sort_declares+}++modules=0 ok=0 reject=0 differ=0 readfail=0+check_bc() { # $1 = a file holding one module's bitcode, $2 = its name+ modules=$((modules + 1))+ if ! "$AIR2NIR" --ll "$1" > "$WORK/ours.ll" 2> "$WORK/ours.err"; then+ readfail=$((readfail + 1))+ printf 'READER %s: %s\n' "$2" "$(head -1 "$WORK/ours.err")"+ return+ fi+ llvm-dis -o - "$1" 2>/dev/null | canon > "$WORK/theirs.canon" || true+ if ! canon < "$WORK/ours.ll" > "$WORK/ours.canon"; then+ reject=$((reject + 1))+ printf 'LLVM-AS %s: %s\n' "$2" "$(head -1 "$WORK/as.err")"+ return+ fi+ if cmp -s "$WORK/ours.canon" "$WORK/theirs.canon"; then+ ok=$((ok + 1))+ [ "$VERBOSE" = 1 ] && printf 'ok %s\n' "$2"+ else+ differ=$((differ + 1))+ printf 'DIFFER %s\n' "$2"+ [ "$VERBOSE" = 1 ] && diff -u "$WORK/theirs.canon" "$WORK/ours.canon" | head -40+ fi+ return 0+}++for arg in "$@"; do+ if [ -d "$arg" ]; then+ while IFS= read -r f; do check_bc "$f" "${f#"$arg"/}"; done \+ < <(find "$arg" -name '*.bc' | sort)+ elif [ "${arg%.metallib}" != "$arg" ]; then+ dir=$WORK/unpack+ rm -rf "$dir"+ python3 "$ROOT/tools/metallib.py" dump "$arg" "$dir" > /dev/null+ while IFS= read -r f; do+ check_bc "$f" "$(basename "$arg"):$(basename "$f" .bc)"+ done < <(find "$dir" -name '*.bc' | sort)+ else+ check_bc "$arg" "$arg"+ fi+done++printf '\nreader-check: %d modules, %d identical to llvm-dis' "$modules" "$ok"+[ "$readfail" != 0 ] && printf ', %d our reader refused' "$readfail"+[ "$reject" != 0 ] && printf ', %d llvm-as refused' "$reject"+[ "$differ" != 0 ] && printf ', %d differ' "$differ"+printf '\n'+[ "$ok" = "$modules" ]diff --git a/tools/mesa/air-ir3.patch b/tools/mesa/air-ir3.patchnew file mode 100644index 0000000..f8a28ac--- /dev/null+++ b/tools/mesa/air-ir3.patch@@ -0,0 +1,191 @@+Teach ir3_compiler to read AIR, the way it already reads SPIR-V.++ir3_cmdline.c takes GLSL, TGSI and SPIR-V and compiles each for an Adreno. A+.metallib (or one module's bitcode) is one more front end to it, and putting it+here rather than in a tool of our own means the AIR path is compiled by the same+ir3 the port's Mesa uses, with the same options, and that a regression in ir3+shows against AIR as it does against the others.++--chip-id takes the Adreno's chip id instead of the old gpu-id, because the+redwood's Adreno 7c+ Gen 3 (A635) has no gpu-id of its own: freedreno knows it+only as chip_id 0x007506030500.++Also removes this tool's own call of ir3_nir_lower_variant, which is a bug of+the tool: ir3_context_init already calls it on its clone of the NIR, and the+const-state setup inside asserts the second time. It shows on any shader whose+const state reserves something -- every vertex shader, and anything with image+dimensions -- and hides on the rest, which is presumably why it survived.+--- a/src/gallium/drivers/freedreno/ir3/ir3_cmdline.c++++ b/src/gallium/drivers/freedreno/ir3/ir3_cmdline.c+@@ -34,6 +34,7 @@+ #include "compiler/glsl/standalone.h"+ #include "compiler/spirv/nir_spirv.h"+ #include "compiler/spirv/spirv_info.h"++#include "compiler/air/nir_air.h"++ #include "pipe/p_context.h"++@@ -247,10 +248,62 @@+ return nir;+ }++-static const char *shortopts = "g:hv";++/* One function of a .metallib, or one module's bitcode, through the AIR++ * frontend. Function constants are all taken as zero: the command line has no++ * pipeline to get them from, and a module that needs real values says so.++ */++static nir_shader *++load_air(const char *filename, const char *entry)++{++ void *buf;++ size_t size;++ read_file(filename, &buf, &size);++++ const void *bitcode = buf;++ size_t bitcode_size = size;++ struct air_metallib lib;++ const char *err;++ if (size >= 4 && !memcmp(buf, "MTLB", 4)) {++ if (!air_metallib_parse(NULL, buf, size, &lib, &err))++ errx(1, "%s: %s", filename, err);++ unsigned pick = lib.num_functions;++ for (unsigned i = 0; i < lib.num_functions; i++) {++ if (!entry || !strcmp(entry, lib.functions[i].name)) {++ pick = i;++ break;++ }++ }++ if (pick == lib.num_functions)++ errx(1, "%s: no function %s", filename, entry ? entry : "(any)");++ bitcode = lib.functions[pick].bitcode;++ bitcode_size = lib.functions[pick].bitcode_size;++ entry = lib.functions[pick].name;++ }++++ struct air_constant_value *fc;++ unsigned num_fc = air_module_function_constants(NULL, bitcode, bitcode_size, &fc);++ const struct air_to_nir_options options = {++ .constants = fc,++ .num_constants = num_fc,++ };++ struct air_shader_info info;++ nir_shader *nir = air_to_nir(NULL, bitcode, bitcode_size, NULL, &options,++ ir3_get_compiler_options(compiler), &info, &err);++ if (!nir)++ errx(1, "%s: %s", entry ? entry : filename, err);++++ printf("; AIR: %s, %u resources, %u varyings, %u render targets\n",++ info.entry_point, info.num_resources, info.num_varyings,++ info.num_render_targets);++ nir_print_shader(nir, stdout);++ return nir;++}++++static const char *shortopts = "g:c:hv";++ static const struct option longopts[] = {+ {"gpu", required_argument, 0, 'g'},++ {"chip-id", required_argument, 0, 'c'},+ {"help", no_argument, 0, 'h'},+ {"verbose", no_argument, 0, 'v'},+ };+@@ -261,6 +314,7 @@+ printf("Usage: ir3_compiler [OPTIONS]... <file.tgsi | file.spv entry_point "+ "| (file.vert | file.frag)*>\n");+ printf(" -g, --gpu GPU_ID - specify gpu-id (default 320)\n");++ printf(" -c, --chip-id ID - specify chip-id (e.g. 0x007506030500)\n");+ printf(" -h, --help - show this message\n");+ printf(" -v, --verbose - verbose compiler/debug messages\n");+ }+@@ -274,10 +328,12 @@+ unsigned stage = 0;+ struct ir3_shader_key key = {};+ unsigned gpu_id = 320;++ uint64_t chip_id = 0;+ const char *info;+ const char *spirv_entry = NULL;+ void *ptr;+ bool from_tgsi = false;++ const char *air_file = NULL, *air_entry = NULL;+ size_t size;++ while ((opt = getopt_long_only(argc, argv, shortopts, longopts, NULL)) !=+@@ -286,6 +342,9 @@+ case 'g':+ gpu_id = strtol(optarg, NULL, 0);+ break;++ case 'c':++ chip_id = strtoull(optarg, NULL, 0);++ break;+ case 'v':+ ir3_shader_debug |= IR3_DBG_OPTMSGS | IR3_DBG_DISASM;+ break;+@@ -323,6 +382,15 @@+ errx(1, "in SPIR-V mode, an entry point must be specified");+ spirv_entry = argv[n];+ n++;++ } else if (strcmp(ext, ".metallib") == 0 || strcmp(ext, ".bc") == 0 ||++ strcmp(ext, ".air") == 0) {++ if (num_files != 0 || from_tgsi || spirv_entry)++ errx(1, "in AIR mode, only a single file may be specified");++ air_file = filename;++ n++;++ if (n < argc && argv[n][0] != '-')++ air_entry = argv[n++];++ continue;+ } else if (strcmp(ext, ".comp") == 0) {+ if (from_tgsi || spirv_entry)+ errx(1, "cannot mix GLSL/TGSI/SPIRV");+@@ -354,12 +422,24 @@+ nir_shader *nir;++ struct fd_dev_id dev_id = {+- .gpu_id = gpu_id,++ .gpu_id = chip_id ? 0 : gpu_id,++ .chip_id = chip_id,+ };+ compiler = ir3_compiler_create(NULL, &dev_id, fd_dev_info_raw(&dev_id),+ &(struct ir3_compiler_options) {});++- if (from_tgsi) {++ if (air_file) {++ nir = load_air(air_file, air_entry);++ stage = nir->info.stage;++++ /* The frontend emits NIR's own system values, as the SPIR-V one does;++ * lowering them to what the hardware has is the consumer's job.++ */++ NIR_PASS(_, nir, nir_lower_system_values);++ NIR_PASS(_, nir, nir_lower_compute_system_values, NULL);++ NIR_PASS(_, nir, nir_lower_io, nir_var_shader_in | nir_var_shader_out,++ ir3_glsl_type_size, nir_lower_io_use_interpolated_input_intrinsics);++ } else if (from_tgsi) {+ struct tgsi_token toks[65536];+ const nir_shader_compiler_options *nir_options =+ ir3_get_compiler_options(compiler);+@@ -420,8 +500,13 @@+ shader->variants = v;+ shader->variant_count = 1;++- ir3_nir_lower_variant(v, &options, nir);+-++ /* ir3_nir_lower_variant is NOT called here: ir3_context_init does it, on++ * its own clone of the shader's NIR, and the const-state setup inside it++ * asserts when it runs twice on one variant. Calling it here as well is a++ * bug of this tool that only shows on shaders whose const state reserves++ * anything -- any vertex shader (PRIMITIVE_PARAM), or anything with image++ * dimensions -- which is why it went unnoticed.++ */+ info = "NIR compiler";+ ret = ir3_compile_shader_nir(compiler, shader, v);+ if (ret) {+--- a/src/gallium/drivers/freedreno/meson.build++++ b/src/gallium/drivers/freedreno/meson.build+@@ -303,6 +303,7 @@+ include_directories : freedreno_includes,+ dependencies : [+ idep_nir,++ idep_air,+ idep_vtn,+ idep_mesautil,+ ],diff --git a/tools/mesa/air/air2nir.c b/tools/mesa/air/air2nir.cnew file mode 100644index 0000000..dd5915e--- /dev/null+++ b/tools/mesa/air/air2nir.c@@ -0,0 +1,256 @@+/*+ * Copyright © 2026 Darwin on redwood contributors+ * SPDX-License-Identifier: MIT+ */++/*+ * air2nir: the frontend from the command line, as spirv2nir is for SPIR-V.+ *+ * air2nir FILE [FUNCTION] translate and print the NIR+ * air2nir --ll FILE [FUNCTION] print what the bitcode reader read, as LLVM assembly+ * air2nir --list FILE.metallib the functions of a container+ * air2nir --report FILE... one line per module, for tools/air/corpus.py+ *+ * FILE is a .metallib (then FUNCTION picks one; without it, every function)+ * or one module's bitcode, wrapped or not. --report forks for every module,+ * so that an assertion in one is a line in the report and not the end of it.+ */++#include <errno.h>+#include <fcntl.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/mman.h>+#include <sys/stat.h>+#include <sys/wait.h>+#include <unistd.h>++#include "nir.h"+#include "nir_air.h"+#include "air_module.h"+#include "util/ralloc.h"++static const nir_shader_compiler_options default_options = {+ .lower_fdiv = false,+};++static void *+map_file(const char *path, size_t *size)+{+ int fd = open(path, O_RDONLY);+ if (fd < 0) {+ fprintf(stderr, "air2nir: %s: %s\n", path, strerror(errno));+ return NULL;+ }+ struct stat st;+ fstat(fd, &st);+ *size = st.st_size;+ void *p = mmap(NULL, st.st_size ? st.st_size : 1, PROT_READ, MAP_PRIVATE, fd, 0);+ close(fd);+ return p == MAP_FAILED ? NULL : p;+}++struct module_ref {+ const char *name;+ int container_type;+ const void *bitcode;+ size_t size;+};++/* every module of FILE (one, unless it is a container) */+static unsigned+modules_of(void *ctx, const char *path, const char *only, struct module_ref **out)+{+ size_t size;+ const uint8_t *data = map_file(path, &size);+ if (!data)+ return 0;+ if (size >= 4 && !memcmp(data, "MTLB", 4)) {+ struct air_metallib lib;+ const char *err;+ if (!air_metallib_parse(ctx, data, size, &lib, &err)) {+ fprintf(stderr, "air2nir: %s: %s\n", path, err);+ return 0;+ }+ *out = rzalloc_array(ctx, struct module_ref, lib.num_functions ? lib.num_functions : 1);+ unsigned n = 0;+ for (unsigned i = 0; i < lib.num_functions; i++) {+ if (only && strcmp(only, lib.functions[i].name))+ continue;+ (*out)[n++] = (struct module_ref) {+ lib.functions[i].name, lib.functions[i].type,+ lib.functions[i].bitcode, lib.functions[i].bitcode_size,+ };+ }+ return n;+ }+ *out = rzalloc(ctx, struct module_ref);+ (*out)[0] = (struct module_ref) { path, -1, data, size };+ return 1;+}++static const char *+stage_name(int stage)+{+ switch (stage) {+ case MESA_SHADER_VERTEX: return "vertex";+ case MESA_SHADER_FRAGMENT: return "fragment";+ case MESA_SHADER_COMPUTE: return "kernel";+ case MESA_SHADER_NONE: return "visible";+ default: return "unknown";+ }+}++static void+one_line(const char *s, FILE *fp)+{+ for (; *s; s++)+ fputc(*s == '\n' || *s == '\t' ? ' ' : *s, fp);+}++/* tools/air/corpus.py reads these lines: tab-separated key=value */+static void+report_one(const struct module_ref *mod)+{+ void *ctx = ralloc_context(NULL);+ const char *err = NULL, *calls = NULL;++ printf("module=%s\tcontainer=%s", mod->name,+ mod->container_type >= 0 ? air_metallib_type_name(mod->container_type) : "-");++ struct air_module *m = air_module_read(ctx, mod->bitcode, mod->size, &err);+ if (!m) {+ printf("\treader=fail\terror=");+ one_line(err, stdout);+ printf("\n");+ ralloc_free(ctx);+ return;+ }+ printf("\treader=ok");++ int stage = air_module_stage(ctx, mod->bitcode, mod->size, &calls, &err);+ printf("\tstage=%s\tcalls=", stage_name(stage));+ for (const char *c = calls; c && *c; c += strlen(c) + 1)+ printf("%s%s", c == calls ? "" : ",", c);++ /* Function constants are values the API supplies at pipeline creation. The+ * report has no API, so it compiles with every one set to zero and says so:+ * a module that needs values is not a module the translator cannot handle.+ */+ struct air_constant_value *fc;+ unsigned num_fc = air_module_function_constants(ctx, mod->bitcode, mod->size, &fc);+ struct air_to_nir_options options = { .constants = fc, .num_constants = num_fc };+ if (num_fc)+ printf("\tfc=%u", num_fc);++ struct air_shader_info info;+ nir_shader *nir = air_to_nir(ctx, mod->bitcode, mod->size, NULL, &options, &default_options,+ &info, &err);+ if (!nir) {+ printf("\ttranslate=fail\terror=");+ one_line(err, stdout);+ printf("\n");+ ralloc_free(ctx);+ return;+ }+ nir_validate_shader(nir, "after air_to_nir");+ unsigned instrs = 0;+ nir_foreach_function_impl(impl, nir) {+ nir_foreach_block(block, impl) {+ nir_foreach_instr(instr, block)+ instrs++;+ }+ }+ printf("\ttranslate=ok\tnir_instrs=%u\n", instrs);+ ralloc_free(nir);+ ralloc_free(ctx);+}++int+main(int argc, char **argv)+{+ enum { TRANSLATE, LL, LIST, REPORT } mode = TRANSLATE;+ int i = 1;+ if (i < argc && !strcmp(argv[i], "--ll"))+ mode = LL, i++;+ else if (i < argc && !strcmp(argv[i], "--list"))+ mode = LIST, i++;+ else if (i < argc && !strcmp(argv[i], "--report"))+ mode = REPORT, i++;+ if (i >= argc) {+ fprintf(stderr, "usage: air2nir [--ll | --list | --report] FILE [FUNCTION]\n");+ return 2;+ }++ glsl_type_singleton_init_or_ref();+ void *ctx = ralloc_context(NULL);+ int status = 0;++ if (mode == REPORT) {+ setvbuf(stdout, NULL, _IOLBF, 0);+ for (; i < argc; i++) {+ struct module_ref *mods;+ unsigned n = modules_of(ctx, argv[i], NULL, &mods);+ for (unsigned k = 0; k < n; k++) {+ fflush(stdout);+ pid_t pid = fork();+ if (pid == 0) {+ alarm(60);+ report_one(&mods[k]);+ fflush(stdout);+ _exit(0);+ }+ int ws;+ waitpid(pid, &ws, 0);+ if (!WIFEXITED(ws) || WEXITSTATUS(ws) != 0)+ printf("module=%s\tcrash=%s %d\n", mods[k].name,+ WIFSIGNALED(ws) ? "signal" : "exit",+ WIFSIGNALED(ws) ? WTERMSIG(ws) : WEXITSTATUS(ws));+ }+ }+ ralloc_free(ctx);+ glsl_type_singleton_decref();+ return 0;+ }++ struct module_ref *mods;+ unsigned n = modules_of(ctx, argv[i], i + 1 < argc ? argv[i + 1] : NULL, &mods);+ if (n == 0)+ return 1;++ for (unsigned k = 0; k < n; k++) {+ const char *err = NULL;+ if (mode == LIST) {+ printf("%-60s %-12s %zu\n", mods[k].name,+ air_metallib_type_name(mods[k].container_type), mods[k].size);+ continue;+ }+ if (mode == LL) {+ struct air_module *m = air_module_read(ctx, mods[k].bitcode, mods[k].size, &err);+ if (!m) {+ fprintf(stderr, "air2nir: %s: %s\n", mods[k].name, err);+ status = 1;+ continue;+ }+ air_module_print(m, stdout);+ continue;+ }+ struct air_constant_value *fc;+ unsigned num_fc = air_module_function_constants(ctx, mods[k].bitcode, mods[k].size, &fc);+ struct air_to_nir_options options = { .constants = fc, .num_constants = num_fc };+ struct air_shader_info info;+ nir_shader *nir = air_to_nir(ctx, mods[k].bitcode, mods[k].size, NULL, &options,+ &default_options, &info, &err);+ if (!nir) {+ fprintf(stderr, "air2nir: %s: %s\n", mods[k].name, err);+ status = 1;+ continue;+ }+ nir_print_shader(nir, stdout);+ }++ ralloc_free(ctx);+ glsl_type_singleton_decref();+ return status;+}diff --git a/tools/mesa/air/air_bitcode.c b/tools/mesa/air/air_bitcode.cnew file mode 100644index 0000000..da092c9--- /dev/null+++ b/tools/mesa/air/air_bitcode.c@@ -0,0 +1,421 @@+/*+ * Copyright © 2026 Darwin on redwood contributors+ * SPDX-License-Identifier: MIT+ */++#include "air_bitcode.h"++#include <inttypes.h>+#include <stdarg.h>+#include <stdio.h>+#include <string.h>++#include "util/macros.h"+#include "util/ralloc.h"++enum {+ ABBREV_ID_END_BLOCK = 0,+ ABBREV_ID_ENTER_SUBBLOCK = 1,+ ABBREV_ID_DEFINE_ABBREV = 2,+ ABBREV_ID_UNABBREV_RECORD = 3,+ ABBREV_ID_FIRST = 4,+};++enum {+ BLOCKINFO_BLOCK_ID = 0,+ BLOCKINFO_CODE_SETBID = 1,+};++static void+bs_fail(struct air_bitstream *bs, const char *fmt, ...)+{+ if (bs->error[0])+ return; /* the first error is the one that explains */+ va_list ap;+ va_start(ap, fmt);+ vsnprintf(bs->error, sizeof(bs->error), fmt, ap);+ va_end(ap);+ bs->pos = bs->size_bits;+}++static uint64_t+read_fixed(struct air_bitstream *bs, unsigned width)+{+ if (width == 0)+ return 0;+ if (width > 64 || bs->pos + width > bs->size_bits) {+ bs_fail(bs, "read of %u bits past the end at bit %" PRIu64, width, bs->pos);+ return 0;+ }++ uint64_t v = 0;+ unsigned got = 0;+ while (got < width) {+ unsigned bit = bs->pos & 7;+ unsigned take = MIN2(8 - bit, width - got);+ uint64_t chunk = (bs->data[bs->pos >> 3] >> bit) & ((1u << take) - 1);+ v |= chunk << got;+ got += take;+ bs->pos += take;+ }+ return v;+}++static uint64_t+read_vbr(struct air_bitstream *bs, unsigned width)+{+ if (width < 2 || width > 32) {+ bs_fail(bs, "VBR width %u", width);+ return 0;+ }+ const uint64_t hi = 1ull << (width - 1);+ uint64_t v = 0;+ unsigned shift = 0;+ for (;;) {+ uint64_t chunk = read_fixed(bs, width);+ if (shift < 64)+ v |= (chunk & (hi - 1)) << shift;+ else if (chunk & (hi - 1))+ bs_fail(bs, "VBR value wider than 64 bits");+ if (!(chunk & hi) || bs->error[0])+ return v;+ shift += width - 1;+ }+}++static void+align32(struct air_bitstream *bs)+{+ bs->pos = MIN2(ALIGN_POT(bs->pos, 32), bs->size_bits);+}++static void+list_add(void *mem_ctx, struct air_abbrev_list *l, struct air_abbrev *a)+{+ if (l->num == l->cap) {+ l->cap = MAX2(8, l->cap * 2);+ l->abbrevs = reralloc(mem_ctx, l->abbrevs, struct air_abbrev *, l->cap);+ }+ l->abbrevs[l->num++] = a;+}++static struct air_abbrev_list *+blockinfo_for(struct air_bitstream *bs, unsigned block_id, bool create)+{+ for (unsigned i = 0; i < bs->num_blockinfo; i++) {+ if (bs->blockinfo[i].block_id == block_id)+ return &bs->blockinfo[i].abbrevs;+ }+ if (!create)+ return NULL;+ bs->blockinfo = reralloc(bs->mem_ctx, bs->blockinfo, __typeof__(*bs->blockinfo),+ bs->num_blockinfo + 1);+ bs->blockinfo[bs->num_blockinfo].block_id = block_id;+ memset(&bs->blockinfo[bs->num_blockinfo].abbrevs, 0, sizeof(struct air_abbrev_list));+ return &bs->blockinfo[bs->num_blockinfo++].abbrevs;+}++static struct air_abbrev *+read_abbrev(struct air_bitstream *bs)+{+ unsigned n = read_vbr(bs, 5);+ struct air_abbrev *a = rzalloc(bs->mem_ctx, struct air_abbrev);+ a->ops = rzalloc_array(bs->mem_ctx, struct air_abbrev_op, MAX2(n, 1));+ for (unsigned i = 0; i < n && !bs->error[0]; i++) {+ struct air_abbrev_op *op = &a->ops[a->num_ops++];+ if (read_fixed(bs, 1)) {+ op->kind = AIR_ABBREV_LITERAL;+ op->value = read_vbr(bs, 8);+ continue;+ }+ switch (read_fixed(bs, 3)) {+ case 1:+ op->kind = AIR_ABBREV_FIXED;+ op->value = read_vbr(bs, 5);+ break;+ case 2:+ op->kind = AIR_ABBREV_VBR;+ op->value = read_vbr(bs, 5);+ break;+ case 3:+ op->kind = AIR_ABBREV_ARRAY;+ break;+ case 4:+ op->kind = AIR_ABBREV_CHAR6;+ break;+ case 5:+ op->kind = AIR_ABBREV_BLOB;+ break;+ default:+ bs_fail(bs, "unknown abbreviation encoding");+ return a;+ }+ /* a zero-width fixed or VBR field reads nothing: it is the literal 0 */+ if ((op->kind == AIR_ABBREV_FIXED || op->kind == AIR_ABBREV_VBR) && op->value == 0) {+ op->kind = AIR_ABBREV_LITERAL;+ op->value = 0;+ }+ }+ return a;+}++static void+push_op(struct air_bitstream *bs, unsigned *n, uint64_t v)+{+ if (*n == bs->ops_cap) {+ bs->ops_cap = MAX2(64, bs->ops_cap * 2);+ bs->ops = reralloc(bs->mem_ctx, bs->ops, uint64_t, bs->ops_cap);+ }+ bs->ops[(*n)++] = v;+}++static uint64_t+read_scalar(struct air_bitstream *bs, const struct air_abbrev_op *op)+{+ static const char char6[] =+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._";+ switch (op->kind) {+ case AIR_ABBREV_LITERAL:+ return op->value;+ case AIR_ABBREV_FIXED:+ return read_fixed(bs, op->value);+ case AIR_ABBREV_VBR:+ return read_vbr(bs, op->value);+ case AIR_ABBREV_CHAR6:+ return char6[read_fixed(bs, 6)];+ default:+ bs_fail(bs, "array or blob where a scalar belongs");+ return 0;+ }+}++static struct air_bs_entry+read_abbreviated(struct air_bitstream *bs, const struct air_abbrev *a)+{+ struct air_bs_entry e = { .kind = AIR_BS_RECORD };+ unsigned n = 0;++ if (a->num_ops == 0 || a->ops[0].kind == AIR_ABBREV_ARRAY || a->ops[0].kind == AIR_ABBREV_BLOB) {+ bs_fail(bs, "abbreviation without a record code");+ e.kind = AIR_BS_ERROR;+ return e;+ }+ e.id = read_scalar(bs, &a->ops[0]);++ for (unsigned i = 1; i < a->num_ops && !bs->error[0]; i++) {+ const struct air_abbrev_op *op = &a->ops[i];+ if (op->kind == AIR_ABBREV_ARRAY) {+ if (i + 2 != a->num_ops) {+ bs_fail(bs, "array not second to last in its abbreviation");+ break;+ }+ unsigned len = read_vbr(bs, 6);+ for (unsigned j = 0; j < len && !bs->error[0]; j++)+ push_op(bs, &n, read_scalar(bs, &a->ops[i + 1]));+ break;+ } else if (op->kind == AIR_ABBREV_BLOB) {+ uint64_t len = read_vbr(bs, 6);+ align32(bs);+ if (bs->pos + len * 8 > bs->size_bits) {+ bs_fail(bs, "blob past the end");+ break;+ }+ e.blob = bs->data + bs->pos / 8;+ e.blob_size = len;+ bs->pos += len * 8;+ align32(bs);+ } else {+ push_op(bs, &n, read_scalar(bs, op));+ }+ }++ e.num_ops = n;+ e.ops = bs->ops;+ if (bs->error[0])+ e.kind = AIR_BS_ERROR;+ return e;+}++static struct air_bs_scope *+cur(struct air_bitstream *bs)+{+ return &bs->scopes[bs->depth];+}++bool+air_bs_init(struct air_bitstream *bs, void *mem_ctx, const void *data, size_t size)+{+ memset(bs, 0, sizeof(*bs));+ bs->mem_ctx = mem_ctx;+ bs->data = data;+ bs->size_bits = (uint64_t)size * 8;+ bs->scope_cap = 16;+ bs->scopes = rzalloc_array(mem_ctx, struct air_bs_scope, bs->scope_cap);+ bs->scopes[0].block_id = ~0u;+ bs->scopes[0].abbrev_width = 2;+ bs->scopes[0].end_bit = bs->size_bits;++ const uint8_t *b = data;+ if (size < 4 || b[0] != 'B' || b[1] != 'C' || b[2] != 0xc0 || b[3] != 0xde) {+ bs_fail(bs, "not LLVM bitcode (no 'BC' 0xC0DE magic)");+ return false;+ }+ bs->pos = 32;+ return true;+}++static bool+read_blockinfo(struct air_bitstream *bs, unsigned width, uint64_t end)+{+ struct air_abbrev_list *target = NULL;+ for (;;) {+ if (bs->error[0] || bs->pos >= end)+ return false;+ unsigned id = read_fixed(bs, width);+ if (id == ABBREV_ID_END_BLOCK) {+ align32(bs);+ return true;+ } else if (id == ABBREV_ID_DEFINE_ABBREV) {+ struct air_abbrev *a = read_abbrev(bs);+ if (!target) {+ bs_fail(bs, "BLOCKINFO abbreviation before SETBID");+ return false;+ }+ list_add(bs->mem_ctx, target, a);+ } else if (id == ABBREV_ID_UNABBREV_RECORD) {+ unsigned code = read_vbr(bs, 6);+ unsigned n = read_vbr(bs, 6);+ uint64_t first = 0;+ for (unsigned i = 0; i < n; i++) {+ uint64_t v = read_vbr(bs, 6);+ if (i == 0)+ first = v;+ }+ if (code == BLOCKINFO_CODE_SETBID)+ target = blockinfo_for(bs, first, true);+ /* BLOCKNAME and SETRECORDNAME only name things for dumpers */+ } else if (id == ABBREV_ID_ENTER_SUBBLOCK) {+ bs_fail(bs, "a block inside BLOCKINFO");+ return false;+ } else {+ bs_fail(bs, "an abbreviated record in BLOCKINFO");+ return false;+ }+ }+}++struct air_bs_entry+air_bs_next(struct air_bitstream *bs)+{+ for (;;) {+ struct air_bs_entry e = { .kind = AIR_BS_ERROR };+ struct air_bs_scope *s = cur(bs);++ if (bs->error[0])+ return e;+ if (bs->depth == 0 && bs->pos + 32 > bs->size_bits) {+ e.kind = AIR_BS_END;+ return e;+ }+ if (bs->pos >= s->end_bit) {+ bs_fail(bs, "block %u runs past its length", s->block_id);+ return e;+ }++ unsigned id = read_fixed(bs, s->abbrev_width);+ switch (id) {+ case ABBREV_ID_END_BLOCK:+ align32(bs);+ if (bs->depth == 0) {+ bs_fail(bs, "END_BLOCK at the top level");+ return e;+ }+ bs->depth--;+ e.kind = AIR_BS_END_BLOCK;+ return e;++ case ABBREV_ID_ENTER_SUBBLOCK: {+ unsigned block_id = read_vbr(bs, 8);+ bs->pending_width = read_vbr(bs, 4);+ align32(bs);+ uint64_t words = read_fixed(bs, 32);+ bs->pending_end = bs->pos + words * 32;+ if (bs->pending_end > bs->size_bits) {+ bs_fail(bs, "block %u longer than the stream", block_id);+ return e;+ }+ if (block_id == BLOCKINFO_BLOCK_ID) {+ if (!read_blockinfo(bs, bs->pending_width, bs->pending_end))+ return e;+ continue;+ }+ e.kind = AIR_BS_ENTER_BLOCK;+ e.id = block_id;+ return e;+ }++ case ABBREV_ID_DEFINE_ABBREV:+ list_add(bs->mem_ctx, &s->abbrevs, read_abbrev(bs));+ continue;++ case ABBREV_ID_UNABBREV_RECORD: {+ unsigned n = 0;+ e.kind = AIR_BS_RECORD;+ e.id = read_vbr(bs, 6);+ unsigned count = read_vbr(bs, 6);+ for (unsigned i = 0; i < count && !bs->error[0]; i++)+ push_op(bs, &n, read_vbr(bs, 6));+ e.num_ops = n;+ e.ops = bs->ops;+ if (bs->error[0])+ e.kind = AIR_BS_ERROR;+ return e;+ }++ default:+ if (id - ABBREV_ID_FIRST >= s->abbrevs.num) {+ bs_fail(bs, "undefined abbreviation %u in block %u", id, s->block_id);+ return e;+ }+ return read_abbreviated(bs, s->abbrevs.abbrevs[id - ABBREV_ID_FIRST]);+ }+ }+}++bool+air_bs_enter(struct air_bitstream *bs, unsigned block_id)+{+ if (bs->depth + 1 == bs->scope_cap) {+ bs->scope_cap *= 2;+ bs->scopes = reralloc(bs->mem_ctx, bs->scopes, struct air_bs_scope, bs->scope_cap);+ }+ struct air_bs_scope *s = &bs->scopes[++bs->depth];+ memset(s, 0, sizeof(*s));+ s->block_id = block_id;+ s->abbrev_width = bs->pending_width;+ s->end_bit = bs->pending_end;++ struct air_abbrev_list *info = blockinfo_for(bs, block_id, false);+ if (info) {+ for (unsigned i = 0; i < info->num; i++)+ list_add(bs->mem_ctx, &s->abbrevs, info->abbrevs[i]);+ }+ return true;+}++bool+air_bs_skip_block(struct air_bitstream *bs)+{+ bs->pos = bs->pending_end;+ return true;+}++char *+air_bs_ops_to_string(void *mem_ctx, const uint64_t *ops, unsigned n)+{+ char *s = ralloc_size(mem_ctx, n + 1);+ for (unsigned i = 0; i < n; i++)+ s[i] = (char)ops[i];+ s[n] = 0;+ return s;+}diff --git a/tools/mesa/air/air_bitcode.h b/tools/mesa/air/air_bitcode.hnew file mode 100644index 0000000..2707c13--- /dev/null+++ b/tools/mesa/air/air_bitcode.h@@ -0,0 +1,129 @@+/*+ * Copyright © 2026 Darwin on redwood contributors+ * SPDX-License-Identifier: MIT+ */++/*+ * The LLVM bitstream: the container format below LLVM IR bitcode. It knows+ * blocks, abbreviations and records, and nothing of what they mean; that is+ * air_module.c's business. Written from the "LLVM Bitcode File Format"+ * document, not from LLVM's sources, so that the frontend links no LLVM.+ */++#ifndef AIR_BITCODE_H+#define AIR_BITCODE_H++#include <stdbool.h>+#include <stddef.h>+#include <stdint.h>++#ifdef __cplusplus+extern "C" {+#endif++enum air_abbrev_op_kind {+ AIR_ABBREV_LITERAL,+ AIR_ABBREV_FIXED,+ AIR_ABBREV_VBR,+ AIR_ABBREV_ARRAY,+ AIR_ABBREV_CHAR6,+ AIR_ABBREV_BLOB,+};++struct air_abbrev_op {+ enum air_abbrev_op_kind kind;+ uint64_t value; /* the literal, or the width of FIXED/VBR */+};++struct air_abbrev {+ unsigned num_ops;+ struct air_abbrev_op *ops;+};++struct air_abbrev_list {+ unsigned num, cap;+ struct air_abbrev **abbrevs;+};++struct air_bs_scope {+ unsigned block_id;+ unsigned abbrev_width;+ uint64_t end_bit;+ struct air_abbrev_list abbrevs;+};++enum air_bs_entry_kind {+ AIR_BS_ERROR,+ AIR_BS_END, /* end of the stream */+ AIR_BS_ENTER_BLOCK, /* .id; the caller enters it or skips it */+ AIR_BS_END_BLOCK,+ AIR_BS_RECORD, /* .id is the record code, ops/blob below */+};++struct air_bs_entry {+ enum air_bs_entry_kind kind;+ unsigned id;+ unsigned num_ops;+ const uint64_t *ops;+ const uint8_t *blob;+ size_t blob_size;+};++struct air_bitstream {+ void *mem_ctx;+ const uint8_t *data;+ uint64_t size_bits;+ uint64_t pos;++ unsigned depth, scope_cap;+ struct air_bs_scope *scopes;++ /* BLOCKINFO: the abbreviations that every block of an id starts with */+ unsigned num_blockinfo;+ struct {+ unsigned block_id;+ struct air_abbrev_list abbrevs;+ } *blockinfo;++ /* an ENTER_SUBBLOCK header, read but not yet entered or skipped */+ unsigned pending_width;+ uint64_t pending_end;++ /* the current record's operands */+ unsigned ops_cap;+ uint64_t *ops;++ char error[160];+};++/* data must be the bitstream itself: after the 0x0B17C0DE wrapper, starting+ * with the 'BC' 0xC0DE magic, which this checks and skips.+ */+bool air_bs_init(struct air_bitstream *bs, void *mem_ctx,+ const void *data, size_t size);++/* The next thing at the current level. Records of BLOCKINFO are taken in+ * here and never returned; an ENTER_BLOCK must be followed by+ * air_bs_enter() or air_bs_skip_block().+ */+struct air_bs_entry air_bs_next(struct air_bitstream *bs);+bool air_bs_enter(struct air_bitstream *bs, unsigned block_id);+bool air_bs_skip_block(struct air_bitstream *bs);++/* Word offset (32-bit units) of the current position, for VSTOFFSET and+ * function-entry offsets.+ */+static inline uint64_t+air_bs_word_offset(const struct air_bitstream *bs)+{+ return bs->pos / 32;+}++/* Copies the operands of a record into a NUL-terminated string. */+char *air_bs_ops_to_string(void *mem_ctx, const uint64_t *ops, unsigned n);++#ifdef __cplusplus+}+#endif++#endif /* AIR_BITCODE_H */diff --git a/tools/mesa/air/air_intrinsics.c b/tools/mesa/air/air_intrinsics.cnew file mode 100644index 0000000..10bdbda--- /dev/null+++ b/tools/mesa/air/air_intrinsics.c@@ -0,0 +1,396 @@+/*+ * Copyright © 2026 Darwin on redwood contributors+ * SPDX-License-Identifier: MIT+ */++/*+ * The air.* functions. There are 125 distinct declarations in the corpus but+ * their names are <operation>.<type suffix>, so this is a table of about 50+ * operations in four families (docs/metal.md 9.2). The suffix is not trusted+ * for anything: the types come from the call's own LLVM types, and the suffix+ * is only what picks the handler.+ *+ * Where Metal's definition of an operation is not certain from its name --+ * air.fast_exp could be exp or exp2 -- the choice is marked UNVERIFIED and+ * has to be settled against the CPU reference (docs/air.md section 4) before+ * any shader using it is called correct.+ */++#include "air_private.h"++#include <string.h>++#include "nir_builtin_builder.h"+#include "util/u_math.h"++/* the dot-separated parts of an air.* name, after "air." */+#define AIR_MAX_PARTS 8+struct air_name {+ unsigned num;+ char part[AIR_MAX_PARTS][32];+};++static bool+split_name(const char *name, struct air_name *out)+{+ out->num = 0;+ const char *p = name + 4; /* past "air." */+ while (*p && out->num < AIR_MAX_PARTS) {+ const char *dot = strchr(p, '.');+ size_t len = dot ? (size_t)(dot - p) : strlen(p);+ if (len >= sizeof(out->part[0]))+ return false;+ memcpy(out->part[out->num], p, len);+ out->part[out->num][len] = 0;+ out->num++;+ if (!dot)+ return true;+ p = dot + 1;+ }+ return out->num < AIR_MAX_PARTS;+}++static bool+is_signed_part(const char *s)+{+ return !strcmp(s, "s");+}++/* -- the families ------------------------------------------------------- */++static bool+math_op(struct air_ctx *c, const struct air_inst *in, const struct air_name *n, bool *handled)+{+ const char *op = n->part[0];+ unsigned argc = in->num_operands - 1;++ /* the families this file does not handle are named before the arguments+ * are touched, so that their error says so rather than complaining about+ * a texture handle used as a number+ */+ if (strstr(op, "texture") || strstr(op, "_depth_") || !strncmp(op, "sample", 6) ||+ !strncmp(op, "gather", 6) || !strncmp(op, "read_", 5) || !strncmp(op, "write_", 6)) {+ *handled = false;+ return true;+ }++ nir_def *a[4] = { 0 };+ for (unsigned i = 0; i < argc && i < 4; i++)+ if (!(a[i] = air_get_ssa(c, in->operands[1 + i])))+ return false;++ bool is_float = air_type_is_float(air_type_scalar(in->base.type));+ /* the sign of an integer operation is the last-but-one part: air.min.s.i32 */+ bool is_signed = n->num >= 3 ? is_signed_part(n->part[1]) : true;+ nir_def *r = NULL;+ *handled = true;++ /* fast math is what every one of these means: Metal's "fast" library */+ bool was_exact = c->b.exact;+ c->b.exact = false;++ if (!strcmp(op, "fast_fabs") || !strcmp(op, "fabs")) {+ r = nir_fabs(&c->b, a[0]);+ } else if (!strcmp(op, "fast_sqrt") || !strcmp(op, "sqrt")) {+ r = nir_fsqrt(&c->b, a[0]);+ } else if (!strcmp(op, "fast_rsqrt") || !strcmp(op, "rsqrt")) {+ r = nir_frsq(&c->b, a[0]);+ } else if (!strcmp(op, "fast_floor") || !strcmp(op, "floor")) {+ r = nir_ffloor(&c->b, a[0]);+ } else if (!strcmp(op, "fast_ceil") || !strcmp(op, "ceil")) {+ r = nir_fceil(&c->b, a[0]);+ } else if (!strcmp(op, "fast_round") || !strcmp(op, "round")) {+ /* Metal's round() goes away from zero at .5; rint() is the even one */+ r = nir_fround_even(&c->b, a[0]); /* UNVERIFIED: round vs rint */+ } else if (!strcmp(op, "fast_trunc") || !strcmp(op, "trunc")) {+ r = nir_ftrunc(&c->b, a[0]);+ } else if (!strcmp(op, "fast_fract") || !strcmp(op, "fract")) {+ r = nir_ffract(&c->b, a[0]);+ } else if (!strcmp(op, "fast_sin") || !strcmp(op, "sin")) {+ r = nir_fsin(&c->b, a[0]);+ } else if (!strcmp(op, "fast_cos") || !strcmp(op, "cos")) {+ r = nir_fcos(&c->b, a[0]);+ } else if (!strcmp(op, "fast_tan") || !strcmp(op, "tan")) {+ r = nir_fdiv(&c->b, nir_fsin(&c->b, a[0]), nir_fcos(&c->b, a[0]));+ } else if (!strcmp(op, "fast_atan2") || !strcmp(op, "atan2")) {+ r = nir_atan2(&c->b, a[0], a[1]);+ } else if (!strcmp(op, "fast_exp") || !strcmp(op, "exp")) {+ /* UNVERIFIED: exp or exp2. Taken as the natural exp, which is what+ * Metal's exp() is; exp2 has its own name in the language.+ */+ r = nir_fexp2(&c->b, nir_fmul_imm(&c->b, a[0], M_LOG2E));+ } else if (!strcmp(op, "fast_exp2") || !strcmp(op, "exp2")) {+ r = nir_fexp2(&c->b, a[0]);+ } else if (!strcmp(op, "fast_log") || !strcmp(op, "log")) {+ r = nir_fmul_imm(&c->b, nir_flog2(&c->b, a[0]), 1.0 / M_LOG2E);+ } else if (!strcmp(op, "fast_log2") || !strcmp(op, "log2")) {+ r = nir_flog2(&c->b, a[0]);+ } else if (!strcmp(op, "fast_pow") || !strcmp(op, "pow")) {+ r = nir_fpow(&c->b, a[0], a[1]);+ } else if (!strcmp(op, "fast_divide") || !strcmp(op, "divide")) {+ r = nir_fdiv(&c->b, a[0], a[1]);+ } else if (!strcmp(op, "saturate") || !strcmp(op, "fast_saturate")) {+ r = nir_fsat(&c->b, a[0]);+ } else if (!strcmp(op, "sign")) {+ r = is_float ? nir_fsign(&c->b, a[0]) : nir_isign(&c->b, a[0]);+ } else if (!strcmp(op, "mix")) {+ /* mix(x, y, a) = x + a * (y - x), and that is what Metal defines */+ r = nir_fadd(&c->b, a[0],+ nir_fmul(&c->b, a[2], nir_fsub(&c->b, a[1], a[0])));+ } else if (!strcmp(op, "dot")) {+ r = nir_fdot(&c->b, a[0], a[1]);+ } else if (!strcmp(op, "fast_fmin") || !strcmp(op, "fmin") || !strcmp(op, "min")) {+ r = is_float ? nir_fmin(&c->b, a[0], a[1])+ : (is_signed ? nir_imin(&c->b, a[0], a[1]) : nir_umin(&c->b, a[0], a[1]));+ } else if (!strcmp(op, "fast_fmax") || !strcmp(op, "fmax") || !strcmp(op, "max")) {+ r = is_float ? nir_fmax(&c->b, a[0], a[1])+ : (is_signed ? nir_imax(&c->b, a[0], a[1]) : nir_umax(&c->b, a[0], a[1]));+ } else if (!strcmp(op, "fast_clamp") || !strcmp(op, "clamp")) {+ if (is_float)+ r = nir_fmin(&c->b, nir_fmax(&c->b, a[0], a[1]), a[2]);+ else if (is_signed)+ r = nir_imin(&c->b, nir_imax(&c->b, a[0], a[1]), a[2]);+ else+ r = nir_umin(&c->b, nir_umax(&c->b, a[0], a[1]), a[2]);+ } else if (!strcmp(op, "fast_ldexp") || !strcmp(op, "ldexp")) {+ r = nir_ldexp(&c->b, a[0], nir_i2i32(&c->b, a[1]));+ } else if (!strcmp(op, "fast_fma") || !strcmp(op, "fma")) {+ r = nir_ffma(&c->b, a[0], a[1], a[2]);+ } else if (!strcmp(op, "all")) {+ r = nir_ball(&c->b, a[0]);+ } else if (!strcmp(op, "any")) {+ r = nir_bany(&c->b, a[0]);+ } else if (!strcmp(op, "convert")) {+ /* air.convert.<dst sign>.<dst type>.<src sign>.<src type> */+ if (n->num < 5) {+ c->b.exact = was_exact;+ return air_error(c, "intrinsic: %s (a convert without both types)", op);+ }+ const struct air_type *dt = in->base.type;+ const struct air_type *st = in->operands[1]->type;+ unsigned bits = air_nir_bit_size(c, dt);+ bool dst_float = n->part[1][0] == 'f';+ bool src_float = n->part[3][0] == 'f';+ bool src_signed = n->part[3][0] == 's';+ nir_def *x = a[0];+ if (!src_float && air_type_bit_size(air_type_scalar(st)) == 1)+ x = src_signed ? nir_ineg(&c->b, nir_b2i32(&c->b, x)) : nir_b2i32(&c->b, x);+ if (dst_float && src_float)+ r = nir_f2fN(&c->b, x, bits);+ else if (dst_float)+ r = src_signed ? nir_i2fN(&c->b, x, bits) : nir_u2fN(&c->b, x, bits);+ else if (src_float)+ r = n->part[1][0] == 's' ? nir_f2iN(&c->b, x, bits) : nir_f2uN(&c->b, x, bits);+ else+ r = src_signed ? nir_i2iN(&c->b, x, bits) : nir_u2uN(&c->b, x, bits);+ } else {+ *handled = false;+ }++ c->b.exact = was_exact;+ if (!*handled)+ return true;+ if (!r)+ return false;+ air_set(c, &in->base, air_val_ssa(c, r));+ return true;+}++/* -- atomics ------------------------------------------------------------ */++static bool+atomic_op(struct air_ctx *c, const struct air_inst *in, const struct air_name *n)+{+ /* air.atomic.{global,local}.<op>[.<sign>].<type>(ptr, value?, order,+ * scope, volatile)+ */+ if (n->num < 3)+ return air_error(c, "intrinsic: an atomic without a name");+ const char *where = n->part[1];+ const char *op = n->part[2];+ bool is_signed = n->num >= 5 ? is_signed_part(n->part[3]) : true;++ struct air_val *pv = air_get(c, in->operands[1]);+ if (!pv)+ return false;+ if (pv->kind != AIR_VAL_PTR)+ return air_error(c, "intrinsic: an atomic on something that is not a pointer");+ struct air_ptr p = pv->ptr;++ bool shared = !strcmp(where, "local");+ if (shared != (p.class == AIR_PTR_SHARED))+ return air_error(c, "intrinsic: air.atomic.%s on %s memory", where,+ p.class == AIR_PTR_SHARED ? "threadgroup" : "device");++ nir_def *off = p.offset ? p.offset : nir_imm_int(&c->b, 0);++ if (!strcmp(op, "load")) {+ nir_def *r = air_load_ptr(c, p, in->base.type, 0);+ if (!r)+ return false;+ air_set(c, &in->base, air_val_ssa(c, r));+ return true;+ }+ if (!strcmp(op, "store")) {+ nir_def *v = air_get_ssa(c, in->operands[2]);+ return v && air_store_ptr(c, p, v, 0);+ }++ nir_atomic_op aop;+ if (!strcmp(op, "add")) aop = nir_atomic_op_iadd;+ else if (!strcmp(op, "min")) aop = is_signed ? nir_atomic_op_imin : nir_atomic_op_umin;+ else if (!strcmp(op, "max")) aop = is_signed ? nir_atomic_op_imax : nir_atomic_op_umax;+ else if (!strcmp(op, "and")) aop = nir_atomic_op_iand;+ else if (!strcmp(op, "or")) aop = nir_atomic_op_ior;+ else if (!strcmp(op, "xor")) aop = nir_atomic_op_ixor;+ else if (!strcmp(op, "xchg")) aop = nir_atomic_op_xchg;+ else return air_error(c, "intrinsic: atomic %s", op);++ nir_def *v = air_get_ssa(c, in->operands[2]);+ if (!v)+ return false;+ nir_def *r;+ if (shared) {+ r = nir_shared_atomic(&c->b, v->bit_size, off, v, .atomic_op = aop);+ } else if (p.class == AIR_PTR_SSBO) {+ r = nir_ssbo_atomic(&c->b, v->bit_size, nir_imm_int(&c->b, p.binding), off, v,+ .atomic_op = aop);+ } else {+ return air_error(c, "intrinsic: an atomic on a pointer that is not a buffer");+ }+ if (in->base.type && in->base.type->kind != AIR_TYPE_VOID)+ air_set(c, &in->base, air_val_ssa(c, r));+ return true;+}++/* -- barriers ----------------------------------------------------------- */++static bool+barrier_op(struct air_ctx *c, const struct air_inst *in)+{+ /* air.wg.barrier(i32 flags, i32 scope): the flags say which memory is+ * ordered. 2 is threadgroup memory, 1 device, 4 texture; the corpus only+ * ever passes 2 with scope 1 (the threadgroup).+ */+ uint64_t flags = 2;+ const struct air_constant *k =+ in->num_operands > 1 ? air_value_as_constant(in->operands[1]) : NULL;+ if (k && k->ckind == AIR_CONST_INT)+ flags = k->u;++ nir_variable_mode modes = 0;+ if (flags & 1)+ modes |= nir_var_mem_ssbo | nir_var_mem_global;+ if (flags & 2)+ modes |= nir_var_mem_shared;+ if (flags & 4)+ modes |= nir_var_image;+ if (!modes)+ modes = nir_var_mem_shared;++ nir_barrier(&c->b, .execution_scope = SCOPE_WORKGROUP,+ .memory_scope = SCOPE_WORKGROUP, .memory_semantics = NIR_MEMORY_ACQ_REL,+ .memory_modes = modes);+ return true;+}++/* -- llvm.* ------------------------------------------------------------- */++static bool+llvm_op(struct air_ctx *c, const struct air_inst *in, const char *name)+{+ if (!strncmp(name, "llvm.lifetime.", 14))+ return true; /* scope markers: nothing to emit */+ if (!strncmp(name, "llvm.memcpy.", 12)) {+ /* a copy between two of our pointers, of a constant length */+ struct air_val *dst = air_get(c, in->operands[1]);+ struct air_val *src = air_get(c, in->operands[2]);+ const struct air_constant *len = air_value_as_constant(in->operands[3]);+ if (!dst || !src)+ return false;+ if (dst->kind != AIR_VAL_PTR || src->kind != AIR_VAL_PTR)+ return air_error(c, "intrinsic: memcpy that is not between pointers");+ if (!len || len->ckind != AIR_CONST_INT)+ return air_error(c, "intrinsic: memcpy of a run-time length");+ /* in 4-byte pieces, which is what every memcpy in the corpus is a+ * multiple of (they copy float vectors out of constant buffers)+ */+ if (len->u % 4)+ return air_error(c, "intrinsic: memcpy of %u bytes", (unsigned)len->u);+ for (uint64_t off = 0; off < len->u; off += 4) {+ struct air_ptr s = air_ptr_add(c, src->ptr, nir_imm_int(&c->b, off));+ struct air_ptr d = air_ptr_add(c, dst->ptr, nir_imm_int(&c->b, off));+ static const struct air_type u32 = { .kind = AIR_TYPE_INT, .bits = 32 };+ nir_def *v = air_load_ptr(c, s, &u32, 4);+ if (!v || !air_store_ptr(c, d, v, 4))+ return false;+ }+ return true;+ }+ if (!strncmp(name, "llvm.memset.", 12)) {+ struct air_val *dst = air_get(c, in->operands[1]);+ nir_def *byte = air_get_ssa(c, in->operands[2]);+ const struct air_constant *len = air_value_as_constant(in->operands[3]);+ if (!dst || !byte)+ return false;+ if (dst->kind != AIR_VAL_PTR)+ return air_error(c, "intrinsic: memset of something that is not a pointer");+ if (!len || len->ckind != AIR_CONST_INT || len->u % 4)+ return air_error(c, "intrinsic: memset of a length that is not a multiple of 4");+ if (!nir_src_is_const(nir_src_for_ssa(byte)))+ return air_error(c, "intrinsic: memset of a run-time byte");+ uint32_t b = nir_src_as_uint(nir_src_for_ssa(byte)) & 0xff;+ uint32_t word = b | b << 8 | b << 16 | b << 24;+ for (uint64_t off = 0; off < len->u; off += 4) {+ struct air_ptr d = air_ptr_add(c, dst->ptr, nir_imm_int(&c->b, off));+ if (!air_store_ptr(c, d, nir_imm_int(&c->b, word), 4))+ return false;+ }+ return true;+ }+ if (!strcmp(name, "llvm.trap"))+ return air_error(c, "intrinsic: llvm.trap");+ return air_error(c, "intrinsic: %s", name);+}++/* -- the dispatcher ----------------------------------------------------- */++bool+air_translate_call(struct air_ctx *c, const struct air_inst *in, const char *name)+{+ if (!strncmp(name, "llvm.", 5))+ return llvm_op(c, in, name);++ if (strncmp(name, "air.", 4)) {+ /* a call of another function in the module: inlining them is the+ * translator's job and is not done yet (no system shader needs it:+ * every one is a single function after Apple's own inliner)+ */+ return air_error(c, "intrinsic: a call of %s, a function in the module", name);+ }++ struct air_name n;+ if (!split_name(name, &n))+ return air_error(c, "intrinsic: %s (a name this cannot take apart)", name);++ if (n.num >= 2 && !strcmp(n.part[0], "wg") && !strcmp(n.part[1], "barrier"))+ return barrier_op(c, in);+ if (!strcmp(n.part[0], "atomic"))+ return atomic_op(c, in, &n);++ bool handled = false;+ if (!math_op(c, in, &n, &handled))+ return false;+ if (handled)+ return true;++ /* textures: the largest family, and M3's whole subject. Named here so the+ * corpus report counts them as one thing rather than as unknown calls.+ */+ const char *op = n.part[0];+ if (strstr(op, "texture") || strstr(op, "_depth_") || !strncmp(op, "sample", 6) ||+ !strncmp(op, "gather", 6) || !strncmp(op, "read_", 5) || !strncmp(op, "write_", 6))+ return air_error(c, "intrinsic: %s (textures, not yet)", name);++ return air_error(c, "intrinsic: %s", name);+}diff --git a/tools/mesa/air/air_layout.c b/tools/mesa/air/air_layout.cnew file mode 100644index 0000000..60e194c--- /dev/null+++ b/tools/mesa/air/air_layout.c@@ -0,0 +1,164 @@+/*+ * Copyright © 2026 Darwin on redwood contributors+ * SPDX-License-Identifier: MIT+ */++/*+ * Sizes and alignments from the module's datalayout string, by LLVM's rules+ * (LangRef, "Data Layout"). Every AIR module of iOS 16.5 has the same layout,+ * but it is read rather than assumed: GEP offsets are computed from it, and+ * a wrong offset is a wrong read.+ */++#include "air_module.h"++#include <stdlib.h>+#include <string.h>++#include "util/macros.h"+#include "util/u_math.h"++struct layout_entry {+ char kind; /* 'i', 'f', 'v' */+ unsigned bits;+ unsigned abi_bits;+};++static unsigned+layout_lookup(const struct air_module *m, char kind, unsigned bits, bool *found)+{+ /* parsed on every call: the string is short and this is not hot */+ const char *s = m->datalayout ? m->datalayout : "";+ unsigned best_bigger = 0, best_bigger_bits = ~0u, largest = 0, largest_bits = 0;+ *found = false;+ while (*s) {+ const char *end = strchr(s, '-');+ size_t len = end ? (size_t)(end - s) : strlen(s);+ if (len > 1 && s[0] == kind && s[1] >= '0' && s[1] <= '9') {+ char *q;+ unsigned b = strtoul(s + 1, &q, 10);+ unsigned abi = (*q == ':') ? strtoul(q + 1, NULL, 10) : b;+ if (b == bits) {+ *found = true;+ return abi;+ }+ if (b > bits && b < best_bigger_bits) {+ best_bigger_bits = b;+ best_bigger = abi;+ }+ if (b > largest_bits) {+ largest_bits = b;+ largest = abi;+ }+ }+ s += len + (end != NULL);+ }+ if (kind == 'i') {+ /* the smallest wider integer's, or failing that the widest */+ if (best_bigger_bits != ~0u)+ return best_bigger;+ if (largest_bits)+ return largest;+ }+ return 0;+}++unsigned+air_type_bit_size(const struct air_type *t)+{+ switch (t->kind) {+ case AIR_TYPE_INT: return t->bits;+ case AIR_TYPE_HALF:+ case AIR_TYPE_BFLOAT: return 16;+ case AIR_TYPE_FLOAT: return 32;+ case AIR_TYPE_DOUBLE: return 64;+ case AIR_TYPE_POINTER: return 64;+ case AIR_TYPE_VECTOR: return air_type_bit_size(t->elem);+ default: return 0;+ }+}++static uint64_t+store_size(const struct air_module *m, const struct air_type *t)+{+ switch (t->kind) {+ case AIR_TYPE_VECTOR:+ return DIV_ROUND_UP(t->count * air_type_bit_size(t->elem), 8);+ case AIR_TYPE_ARRAY:+ case AIR_TYPE_STRUCT:+ return air_type_alloc_size(m, t);+ default:+ return DIV_ROUND_UP(air_type_bit_size(t), 8);+ }+}++unsigned+air_type_abi_align(const struct air_module *m, const struct air_type *t)+{+ bool found;+ switch (t->kind) {+ case AIR_TYPE_INT: {+ unsigned a = layout_lookup(m, 'i', t->bits, &found);+ return a ? a / 8 : MAX2(1, util_next_power_of_two(DIV_ROUND_UP(t->bits, 8)));+ }+ case AIR_TYPE_HALF:+ case AIR_TYPE_BFLOAT:+ case AIR_TYPE_FLOAT:+ case AIR_TYPE_DOUBLE: {+ unsigned bits = air_type_bit_size(t);+ unsigned a = layout_lookup(m, 'f', bits, &found);+ return found ? a / 8 : bits / 8;+ }+ case AIR_TYPE_POINTER:+ return 8; /* p:64:64:64 */+ case AIR_TYPE_VECTOR: {+ unsigned bits = t->count * air_type_bit_size(t->elem);+ unsigned a = layout_lookup(m, 'v', bits, &found);+ if (found)+ return a / 8;+ return MAX2(1, util_next_power_of_two64(store_size(m, t)));+ }+ case AIR_TYPE_ARRAY:+ return air_type_abi_align(m, t->elem);+ case AIR_TYPE_STRUCT: {+ if (t->packed)+ return 1;+ unsigned a = 1;+ for (unsigned i = 0; i < t->num_members; i++)+ a = MAX2(a, air_type_abi_align(m, t->members[i]));+ return a;+ }+ default:+ return 1;+ }+}++uint64_t+air_struct_member_offset(const struct air_module *m, const struct air_type *t, unsigned n)+{+ uint64_t off = 0;+ for (unsigned i = 0; i < t->num_members; i++) {+ const struct air_type *mt = t->members[i];+ if (!t->packed)+ off = ALIGN_NPOT(off, air_type_abi_align(m, mt));+ if (i == n)+ return off;+ off += air_type_alloc_size(m, mt);+ }+ return off;+}++uint64_t+air_type_alloc_size(const struct air_module *m, const struct air_type *t)+{+ switch (t->kind) {+ case AIR_TYPE_ARRAY:+ return t->count * air_type_alloc_size(m, t->elem);+ case AIR_TYPE_STRUCT: {+ uint64_t end = air_struct_member_offset(m, t, t->num_members);+ return ALIGN_NPOT(end, air_type_abi_align(m, t));+ }+ default:+ return ALIGN_NPOT(store_size(m, t), air_type_abi_align(m, t));+ }+}diff --git a/tools/mesa/air/air_metallib.c b/tools/mesa/air/air_metallib.cnew file mode 100644index 0000000..f94492e--- /dev/null+++ b/tools/mesa/air/air_metallib.c@@ -0,0 +1,132 @@+/*+ * Copyright © 2026 Darwin on redwood contributors+ * SPDX-License-Identifier: MIT+ */++/*+ * The MTLB container of a .metallib: a header, a function list of tagged+ * fields, and one LLVM module per function. Worked out against the files of+ * iOS 16.5 (docs/metal.md, section 9.1; tools/metallib.py is the same in+ * Python).+ */++#include "nir_air.h"++#include <string.h>++#include "util/ralloc.h"++static uint64_t+rd64(const uint8_t *p)+{+ uint64_t v = 0;+ for (int i = 7; i >= 0; i--)+ v = v << 8 | p[i];+ return v;+}++static uint32_t+rd32(const uint8_t *p)+{+ return p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24;+}++static uint16_t+rd16(const uint8_t *p)+{+ return p[0] | p[1] << 8;+}++bool+air_metallib_parse(void *mem_ctx, const void *data, size_t size, struct air_metallib *lib,+ const char **error)+{+ const uint8_t *b = data;+ memset(lib, 0, sizeof(*lib));+ *error = NULL;++ if (size < 0x58 || memcmp(b, "MTLB", 4) != 0) {+ *error = "not an MTLB container";+ return false;+ }+ lib->version_major = rd16(b + 4);+ lib->version_minor = rd16(b + 6);+ uint64_t total = rd64(b + 0x10);+ uint64_t funcs = rd64(b + 0x18);+ uint64_t bc_off = rd64(b + 0x48);+ uint64_t bc_len = rd64(b + 0x50);+ if (total > size || funcs + 4 > size || bc_off + bc_len > size) {+ *error = "MTLB header points past the file";+ return false;+ }++ const uint8_t *p = b + funcs;+ uint32_t count = rd32(p);+ p += 4;+ lib->functions = rzalloc_array(mem_ctx, struct air_metallib_function, count ? count : 1);+ for (uint32_t i = 0; i < count; i++) {+ if (p + 4 > b + size) {+ *error = "function list runs past the file";+ return false;+ }+ uint32_t len = rd32(p);+ const uint8_t *q = p + 4, *end = p + len;+ if (len < 4 || end > b + size) {+ *error = "function entry runs past the file";+ return false;+ }+ struct air_metallib_function *f = &lib->functions[lib->num_functions++];+ f->type = -1;+ uint64_t module_off = 0, module_size = 0;+ bool have_off = false;+ while (q + 6 <= end && memcmp(q, "ENDT", 4) != 0) {+ uint16_t vlen = rd16(q + 4);+ const uint8_t *v = q + 6;+ if (v + vlen > end) {+ *error = "function field runs past its entry";+ return false;+ }+ if (!memcmp(q, "NAME", 4)) {+ f->name = ralloc_strndup(mem_ctx, (const char *)v, vlen);+ } else if (!memcmp(q, "TYPE", 4) && vlen >= 1) {+ f->type = v[0];+ } else if (!memcmp(q, "OFFT", 4) && vlen >= 24) {+ module_off = rd64(v + 16);+ have_off = true;+ } else if (!memcmp(q, "MDSZ", 4) && vlen >= 8) {+ module_size = rd64(v);+ }+ q = v + vlen;+ }+ if (!f->name || !have_off || !module_size) {+ *error = "function entry without NAME, OFFT or MDSZ";+ return false;+ }+ if (module_off + module_size > bc_len) {+ *error = "function module outside the bitcode section";+ return false;+ }+ f->bitcode = b + bc_off + module_off;+ f->bitcode_size = module_size;+ p = end;+ }+ return true;+}++const char *+air_metallib_type_name(int type)+{+ /* the container's TYPE tag; 4 is what the 135 stitchable functions of+ * PortraitFilters carry, whose metadata says air.visible+ */+ switch (type) {+ case 0: return "vertex";+ case 1: return "fragment";+ case 2: return "kernel";+ case 3: return "unqualified";+ case 4: return "visible";+ case 5: return "extern";+ case 6: return "intersection";+ default: return "unknown";+ }+}diff --git a/tools/mesa/air/air_module.c b/tools/mesa/air/air_module.cnew file mode 100644index 0000000..d908885--- /dev/null+++ b/tools/mesa/air/air_module.c@@ -0,0 +1,1911 @@+/*+ * Copyright © 2026 Darwin on redwood contributors+ * SPDX-License-Identifier: MIT+ */++/*+ * Bitcode records -> struct air_module. The record layouts are those LLVM+ * has written since the 4.0/5.0 days (string table, relative value ids,+ * explicit types on loads, GEPs and calls), which is what Apple's+ * metalfe-31001 emits: typed pointers, MODULE_CODE_VERSION 2.+ */++#include "air_module.h"+#include "air_bitcode.h"++#include <inttypes.h>+#include <stdarg.h>+#include <string.h>++#include "util/macros.h"+#include "util/ralloc.h"++/* block ids */+enum {+ MODULE_BLOCK_ID = 8,+ PARAMATTR_BLOCK_ID = 9,+ PARAMATTR_GROUP_BLOCK_ID = 10,+ CONSTANTS_BLOCK_ID = 11,+ FUNCTION_BLOCK_ID = 12,+ IDENTIFICATION_BLOCK_ID = 13,+ VALUE_SYMTAB_BLOCK_ID = 14,+ METADATA_BLOCK_ID = 15,+ METADATA_ATTACHMENT_ID = 16,+ TYPE_BLOCK_ID_NEW = 17,+ USELIST_BLOCK_ID = 18,+ OPERAND_BUNDLE_TAGS_BLOCK_ID = 21,+ METADATA_KIND_BLOCK_ID = 22,+ STRTAB_BLOCK_ID = 23,+ SYMTAB_BLOCK_ID = 25,+ SYNC_SCOPE_NAMES_BLOCK_ID = 26,+};++/* module records */+enum {+ MODULE_CODE_VERSION = 1,+ MODULE_CODE_TRIPLE = 2,+ MODULE_CODE_DATALAYOUT = 3,+ MODULE_CODE_SECTIONNAME = 5,+ MODULE_CODE_GLOBALVAR = 7,+ MODULE_CODE_FUNCTION = 8,+ MODULE_CODE_GCNAME = 11,+ MODULE_CODE_VSTOFFSET = 13,+ MODULE_CODE_SOURCE_FILENAME = 16,+ MODULE_CODE_HASH = 17,+};++/* type records */+enum {+ TYPE_CODE_NUMENTRY = 1,+ TYPE_CODE_VOID = 2,+ TYPE_CODE_FLOAT = 3,+ TYPE_CODE_DOUBLE = 4,+ TYPE_CODE_LABEL = 5,+ TYPE_CODE_OPAQUE = 6,+ TYPE_CODE_INTEGER = 7,+ TYPE_CODE_POINTER = 8,+ TYPE_CODE_HALF = 10,+ TYPE_CODE_ARRAY = 11,+ TYPE_CODE_VECTOR = 12,+ TYPE_CODE_X86_FP80 = 13,+ TYPE_CODE_FP128 = 14,+ TYPE_CODE_PPC_FP128 = 15,+ TYPE_CODE_METADATA = 16,+ TYPE_CODE_X86_MMX = 17,+ TYPE_CODE_STRUCT_ANON = 18,+ TYPE_CODE_STRUCT_NAME = 19,+ TYPE_CODE_STRUCT_NAMED = 20,+ TYPE_CODE_FUNCTION = 21,+ TYPE_CODE_TOKEN = 22,+ TYPE_CODE_BFLOAT = 23,+ TYPE_CODE_OPAQUE_POINTER = 25,+};++/* constants records */+enum {+ CST_CODE_SETTYPE = 1,+ CST_CODE_NULL = 2,+ CST_CODE_UNDEF = 3,+ CST_CODE_INTEGER = 4,+ CST_CODE_WIDE_INTEGER = 5,+ CST_CODE_FLOAT = 6,+ CST_CODE_AGGREGATE = 7,+ CST_CODE_STRING = 8,+ CST_CODE_CSTRING = 9,+ CST_CODE_CE_BINOP = 10,+ CST_CODE_CE_CAST = 11,+ CST_CODE_CE_GEP_OLD = 12,+ CST_CODE_CE_SELECT = 13,+ CST_CODE_CE_EXTRACTELT = 14,+ CST_CODE_CE_INSERTELT = 15,+ CST_CODE_CE_SHUFFLEVEC = 16,+ CST_CODE_CE_CMP = 17,+ CST_CODE_CE_INBOUNDS_GEP = 20,+ CST_CODE_DATA = 22,+ CST_CODE_CE_GEP_WITH_INRANGE_INDEX = 24,+ CST_CODE_CE_UNOP = 25,+ CST_CODE_POISON = 26,+};++/* function records */+enum {+ FUNC_CODE_DECLAREBLOCKS = 1,+ FUNC_CODE_INST_BINOP = 2,+ FUNC_CODE_INST_CAST = 3,+ FUNC_CODE_INST_SELECT = 5,+ FUNC_CODE_INST_EXTRACTELT = 6,+ FUNC_CODE_INST_INSERTELT = 7,+ FUNC_CODE_INST_SHUFFLEVEC = 8,+ FUNC_CODE_INST_CMP = 9,+ FUNC_CODE_INST_RET = 10,+ FUNC_CODE_INST_BR = 11,+ FUNC_CODE_INST_SWITCH = 12,+ FUNC_CODE_INST_UNREACHABLE = 15,+ FUNC_CODE_INST_PHI = 16,+ FUNC_CODE_INST_ALLOCA = 19,+ FUNC_CODE_INST_LOAD = 20,+ FUNC_CODE_INST_EXTRACTVAL = 26,+ FUNC_CODE_INST_INSERTVAL = 27,+ FUNC_CODE_INST_CMP2 = 28,+ FUNC_CODE_INST_VSELECT = 29,+ FUNC_CODE_DEBUG_LOC_AGAIN = 33,+ FUNC_CODE_INST_CALL = 34,+ FUNC_CODE_DEBUG_LOC = 35,+ FUNC_CODE_INST_FENCE = 36,+ FUNC_CODE_INST_GEP = 43,+ FUNC_CODE_INST_STORE = 44,+ FUNC_CODE_INST_CMPXCHG = 46,+ FUNC_CODE_OPERAND_BUNDLE = 55,+ FUNC_CODE_INST_UNOP = 56,+ FUNC_CODE_INST_FREEZE = 58,+ FUNC_CODE_INST_ATOMICRMW = 59,+};++/* metadata records */+enum {+ METADATA_STRING_OLD = 1,+ METADATA_VALUE = 2,+ METADATA_NODE = 3,+ METADATA_NAME = 4,+ METADATA_DISTINCT_NODE = 5,+ METADATA_KIND = 6,+ METADATA_LOCATION = 7,+ METADATA_OLD_NODE = 8,+ METADATA_OLD_FN_NODE = 9,+ METADATA_NAMED_NODE = 10,+ METADATA_ATTACHMENT = 11,+ METADATA_STRINGS = 35,+ METADATA_GLOBAL_DECL_ATTACHMENT = 36,+ METADATA_INDEX_OFFSET = 38,+ METADATA_INDEX = 39,+ METADATA_ARG_LIST = 46,+};++enum { VST_CODE_ENTRY = 1, VST_CODE_BBENTRY = 2, VST_CODE_FNENTRY = 3 };++/* call record CC field */+#define CALL_TAIL_BIT 0+#define CALL_CCONV_SHIFT 1+#define CALL_EXPLICIT_TYPE_BIT 15+#define CALL_FMF_BIT 17++struct reader {+ struct air_module *m;+ struct air_bitstream bs;++ /* values of the function being read, after the module's */+ unsigned num_values, cap_values;+ struct air_value **values;++ /* the types the record gave for operands not yet defined, by value id */+ unsigned cap_fwd;+ const struct air_type **fwd;++ /* metadata ids: the module's, then the current function's */+ unsigned num_md, cap_md;+ struct air_md **md;++ const uint8_t *strtab;+ size_t strtab_size;++ unsigned num_bodies_read;+ struct air_function *cur_fn;+ unsigned cur_inst_id; /* all instructions, for attachments */+ unsigned num_fn_insts, cap_fn_insts;+ struct air_inst **fn_insts;++ const char *pending_md_name;+};++static bool+fail(struct reader *r, const char *fmt, ...)+{+ if (r->m->error[0])+ return false;+ va_list ap;+ va_start(ap, fmt);+ vsnprintf(r->m->error, sizeof(r->m->error), fmt, ap);+ va_end(ap);+ return false;+}++static bool+check_bs(struct reader *r)+{+ if (r->bs.error[0])+ return fail(r, "bitstream: %s", r->bs.error);+ return true;+}++/* -- types -------------------------------------------------------------- */++static const struct air_type *+type_by_id(struct reader *r, uint64_t id)+{+ if (id >= r->m->num_types) {+ fail(r, "type id %" PRIu64 " out of range (%u types)", id, r->m->num_types);+ return NULL;+ }+ return &r->m->types[id];+}++/* pointers that the bitcode does not list (to functions, to globals with an+ * explicit type), made on the side+ */+static const struct air_type *+pointer_to(struct reader *r, const struct air_type *elem, unsigned as)+{+ for (unsigned i = 0; i < r->m->num_types; i++) {+ const struct air_type *t = &r->m->types[i];+ if (t->kind == AIR_TYPE_POINTER && t->elem == elem && t->addrspace == as)+ return t;+ }+ struct air_type *t = rzalloc(r->m, struct air_type);+ t->kind = AIR_TYPE_POINTER;+ t->id = ~0u;+ t->elem = elem;+ t->addrspace = as;+ return t;+}++static bool+read_type_block(struct reader *r)+{+ struct air_module *m = r->m;+ unsigned next = 0;+ const char *pending_name = NULL;++ for (;;) {+ struct air_bs_entry e = air_bs_next(&r->bs);+ if (e.kind == AIR_BS_END_BLOCK)+ return true;+ if (e.kind == AIR_BS_ENTER_BLOCK) {+ air_bs_skip_block(&r->bs);+ continue;+ }+ if (e.kind != AIR_BS_RECORD)+ return check_bs(r) && fail(r, "type block ends early");++ if (e.id == TYPE_CODE_NUMENTRY) {+ if (e.num_ops < 1)+ return fail(r, "NUMENTRY without a count");+ m->num_types = e.ops[0];+ m->types = rzalloc_array(m, struct air_type, MAX2(m->num_types, 1));+ for (unsigned i = 0; i < m->num_types; i++) {+ m->types[i].id = i;+ m->types[i].kind = AIR_TYPE_UNKNOWN;+ }+ continue;+ }+ if (e.id == TYPE_CODE_STRUCT_NAME) {+ pending_name = air_bs_ops_to_string(m, e.ops, e.num_ops);+ continue;+ }+ if (next >= m->num_types)+ return fail(r, "more types than NUMENTRY said");++ struct air_type *t = &m->types[next];+ switch (e.id) {+ case TYPE_CODE_VOID: t->kind = AIR_TYPE_VOID; break;+ case TYPE_CODE_HALF: t->kind = AIR_TYPE_HALF; break;+ case TYPE_CODE_BFLOAT: t->kind = AIR_TYPE_BFLOAT; break;+ case TYPE_CODE_FLOAT: t->kind = AIR_TYPE_FLOAT; break;+ case TYPE_CODE_DOUBLE: t->kind = AIR_TYPE_DOUBLE; break;+ case TYPE_CODE_LABEL: t->kind = AIR_TYPE_LABEL; break;+ case TYPE_CODE_METADATA: t->kind = AIR_TYPE_METADATA; break;+ case TYPE_CODE_TOKEN: t->kind = AIR_TYPE_TOKEN; break;+ case TYPE_CODE_X86_FP80:+ case TYPE_CODE_FP128:+ case TYPE_CODE_PPC_FP128:+ case TYPE_CODE_X86_MMX:+ t->kind = AIR_TYPE_UNKNOWN;+ break;+ case TYPE_CODE_INTEGER:+ if (e.num_ops < 1)+ return fail(r, "INTEGER type without a width");+ t->kind = AIR_TYPE_INT;+ t->bits = e.ops[0];+ break;+ case TYPE_CODE_POINTER:+ if (e.num_ops < 1)+ return fail(r, "POINTER type without a pointee");+ t->kind = AIR_TYPE_POINTER;+ t->elem = type_by_id(r, e.ops[0]);+ t->addrspace = e.num_ops > 1 ? e.ops[1] : 0;+ break;+ case TYPE_CODE_OPAQUE_POINTER:+ t->kind = AIR_TYPE_POINTER;+ t->addrspace = e.num_ops > 0 ? e.ops[0] : 0;+ break;+ case TYPE_CODE_ARRAY:+ case TYPE_CODE_VECTOR:+ if (e.num_ops < 2)+ return fail(r, "ARRAY/VECTOR type without a size and element");+ t->kind = e.id == TYPE_CODE_ARRAY ? AIR_TYPE_ARRAY : AIR_TYPE_VECTOR;+ t->count = e.ops[0];+ t->elem = type_by_id(r, e.ops[1]);+ if (e.id == TYPE_CODE_VECTOR && e.num_ops > 2 && e.ops[2])+ return fail(r, "scalable vector type");+ break;+ case TYPE_CODE_OPAQUE:+ t->kind = AIR_TYPE_STRUCT;+ t->opaque = true;+ t->name = pending_name;+ pending_name = NULL;+ break;+ case TYPE_CODE_STRUCT_ANON:+ case TYPE_CODE_STRUCT_NAMED:+ if (e.num_ops < 1)+ return fail(r, "STRUCT type without the packed flag");+ t->kind = AIR_TYPE_STRUCT;+ t->packed = e.ops[0];+ t->num_members = e.num_ops - 1;+ t->members = ralloc_array(m, const struct air_type *, MAX2(t->num_members, 1));+ for (unsigned i = 0; i < t->num_members; i++)+ t->members[i] = type_by_id(r, e.ops[1 + i]);+ if (e.id == TYPE_CODE_STRUCT_NAMED) {+ t->name = pending_name;+ pending_name = NULL;+ }+ break;+ case TYPE_CODE_FUNCTION:+ if (e.num_ops < 2)+ return fail(r, "FUNCTION type without vararg and return");+ t->kind = AIR_TYPE_FUNCTION;+ t->vararg = e.ops[0];+ t->elem = type_by_id(r, e.ops[1]);+ t->num_members = e.num_ops - 2;+ t->members = ralloc_array(m, const struct air_type *, MAX2(t->num_members, 1));+ for (unsigned i = 0; i < t->num_members; i++)+ t->members[i] = type_by_id(r, e.ops[2 + i]);+ break;+ default:+ return fail(r, "unknown type record %u", e.id);+ }+ if (m->error[0])+ return false;+ next++;+ }+}++/* -- values ------------------------------------------------------------- */++static void+push_value(struct reader *r, struct air_value *v)+{+ if (r->num_values == r->cap_values) {+ r->cap_values = MAX2(256, r->cap_values * 2);+ r->values = reralloc(r->m, r->values, struct air_value *, r->cap_values);+ }+ v->id = r->num_values;+ r->values[r->num_values++] = v;+}++static struct air_value *+value_by_id(struct reader *r, unsigned id)+{+ if (id >= r->num_values || !r->values[id]) {+ fail(r, "value %u is not defined (%u values)", id, r->num_values);+ return NULL;+ }+ return r->values[id];+}++static int64_t+decode_signed(uint64_t v)+{+ if ((v & 1) == 0)+ return (int64_t)(v >> 1);+ if (v != 1)+ return -(int64_t)(v >> 1);+ return INT64_MIN;+}++static uint64_t+truncate_to(const struct air_type *t, uint64_t v)+{+ const struct air_type *s = air_type_scalar(t);+ if (s->kind == AIR_TYPE_INT && s->bits < 64)+ return v & ((1ull << s->bits) - 1);+ return v;+}++static struct air_constant *+new_constant(struct reader *r, const struct air_type *t, enum air_const_kind k)+{+ struct air_constant *c = rzalloc(r->m, struct air_constant);+ c->base.kind = AIR_VALUE_CONSTANT;+ c->base.type = t;+ c->ckind = k;+ push_value(r, &c->base);+ return c;+}++static void+expr_operands(struct reader *r, struct air_constant *c, unsigned n)+{+ c->num_operands = n;+ c->operands = rzalloc_array(r->m, struct air_value *, MAX2(n, 1));+ c->pending = rzalloc_array(r->m, unsigned, MAX2(n, 1));+}++static bool+read_constants_block(struct reader *r)+{+ const struct air_type *cur = NULL;+ unsigned first = r->num_values;++ for (;;) {+ struct air_bs_entry e = air_bs_next(&r->bs);+ if (e.kind == AIR_BS_END_BLOCK)+ break;+ if (e.kind == AIR_BS_ENTER_BLOCK) {+ air_bs_skip_block(&r->bs);+ continue;+ }+ if (e.kind != AIR_BS_RECORD)+ return check_bs(r) && fail(r, "constants block ends early");++ if (e.id == CST_CODE_SETTYPE) {+ if (e.num_ops < 1 || !(cur = type_by_id(r, e.ops[0])))+ return fail(r, "SETTYPE without a type");+ continue;+ }+ if (!cur)+ return fail(r, "constant before SETTYPE");++ struct air_constant *c;+ switch (e.id) {+ case CST_CODE_NULL:+ new_constant(r, cur, AIR_CONST_NULL);+ break;+ case CST_CODE_UNDEF:+ new_constant(r, cur, AIR_CONST_UNDEF);+ break;+ case CST_CODE_POISON:+ new_constant(r, cur, AIR_CONST_POISON);+ break;+ case CST_CODE_INTEGER:+ if (e.num_ops < 1)+ return fail(r, "INTEGER constant without a value");+ c = new_constant(r, cur, AIR_CONST_INT);+ c->u = truncate_to(cur, (uint64_t)decode_signed(e.ops[0]));+ break;+ case CST_CODE_WIDE_INTEGER:+ return fail(r, "integer constant wider than 64 bits");+ case CST_CODE_FLOAT:+ if (e.num_ops < 1)+ return fail(r, "FLOAT constant without a value");+ if (!air_type_is_float(cur))+ return fail(r, "FLOAT constant of a non-float type");+ c = new_constant(r, cur, AIR_CONST_FLOAT);+ c->u = e.ops[0];+ break;+ case CST_CODE_AGGREGATE:+ c = new_constant(r, cur, AIR_CONST_AGGREGATE);+ c->num_elems = e.num_ops;+ c->elems = rzalloc_array(r->m, struct air_value *, MAX2(e.num_ops, 1));+ c->pending = rzalloc_array(r->m, unsigned, MAX2(e.num_ops, 1));+ for (unsigned i = 0; i < e.num_ops; i++)+ c->pending[i] = e.ops[i];+ break;+ case CST_CODE_STRING:+ case CST_CODE_CSTRING:+ case CST_CODE_DATA: {+ unsigned n = e.num_ops + (e.id == CST_CODE_CSTRING);+ c = new_constant(r, cur, AIR_CONST_DATA);+ c->num_elems = n;+ c->data = rzalloc_array(r->m, uint64_t, MAX2(n, 1));+ for (unsigned i = 0; i < e.num_ops; i++)+ c->data[i] = e.ops[i];+ break;+ }+ case CST_CODE_CE_CAST:+ if (e.num_ops < 3)+ return fail(r, "CE_CAST too short");+ c = new_constant(r, cur, AIR_CONST_EXPR);+ c->expr_op = AIR_OP_CAST;+ c->expr_sub = e.ops[0];+ expr_operands(r, c, 1);+ c->pending[0] = e.ops[2];+ break;+ case CST_CODE_CE_BINOP:+ if (e.num_ops < 3)+ return fail(r, "CE_BINOP too short");+ c = new_constant(r, cur, AIR_CONST_EXPR);+ c->expr_op = AIR_OP_BINOP;+ c->expr_sub = e.ops[0];+ expr_operands(r, c, 2);+ c->pending[0] = e.ops[1];+ c->pending[1] = e.ops[2];+ break;+ case CST_CODE_CE_UNOP:+ if (e.num_ops < 2)+ return fail(r, "CE_UNOP too short");+ c = new_constant(r, cur, AIR_CONST_EXPR);+ c->expr_op = AIR_OP_UNOP;+ c->expr_sub = e.ops[0];+ expr_operands(r, c, 1);+ c->pending[0] = e.ops[1];+ break;+ case CST_CODE_CE_GEP_OLD:+ case CST_CODE_CE_INBOUNDS_GEP:+ case CST_CODE_CE_GEP_WITH_INRANGE_INDEX: {+ unsigned i = 0;+ c = new_constant(r, cur, AIR_CONST_EXPR);+ c->expr_op = AIR_OP_GEP;+ if (e.id == CST_CODE_CE_GEP_WITH_INRANGE_INDEX || (e.num_ops & 1))+ c->src_type = type_by_id(r, e.ops[i++]);+ if (e.id == CST_CODE_CE_GEP_WITH_INRANGE_INDEX)+ c->inbounds = e.ops[i++] & 1;+ else+ c->inbounds = e.id == CST_CODE_CE_INBOUNDS_GEP;+ if ((e.num_ops - i) & 1)+ return fail(r, "CE_GEP with an odd operand list");+ expr_operands(r, c, (e.num_ops - i) / 2);+ for (unsigned k = 0; i < e.num_ops; i += 2, k++)+ c->pending[k] = e.ops[i + 1]; /* (type, value) pairs */+ break;+ }+ case CST_CODE_CE_SELECT:+ if (e.num_ops < 3)+ return fail(r, "CE_SELECT too short");+ c = new_constant(r, cur, AIR_CONST_EXPR);+ c->expr_op = AIR_OP_SELECT;+ expr_operands(r, c, 3);+ for (unsigned i = 0; i < 3; i++)+ c->pending[i] = e.ops[i];+ break;+ case CST_CODE_CE_EXTRACTELT:+ if (e.num_ops < 3)+ return fail(r, "CE_EXTRACTELT too short");+ c = new_constant(r, cur, AIR_CONST_EXPR);+ c->expr_op = AIR_OP_EXTRACTELT;+ expr_operands(r, c, 2);+ c->pending[0] = e.ops[1];+ c->pending[1] = e.ops[e.num_ops == 4 ? 3 : 2];+ break;+ case CST_CODE_CE_INSERTELT:+ if (e.num_ops < 3)+ return fail(r, "CE_INSERTELT too short");+ c = new_constant(r, cur, AIR_CONST_EXPR);+ c->expr_op = AIR_OP_INSERTELT;+ expr_operands(r, c, 3);+ c->pending[0] = e.ops[0];+ c->pending[1] = e.ops[1];+ c->pending[2] = e.ops[e.num_ops == 4 ? 3 : 2];+ break;+ case CST_CODE_CE_SHUFFLEVEC:+ if (e.num_ops < 3)+ return fail(r, "CE_SHUFFLEVEC too short");+ c = new_constant(r, cur, AIR_CONST_EXPR);+ c->expr_op = AIR_OP_SHUFFLEVEC;+ expr_operands(r, c, 3);+ for (unsigned i = 0; i < 3; i++)+ c->pending[i] = e.ops[i];+ break;+ case CST_CODE_CE_CMP:+ if (e.num_ops < 4)+ return fail(r, "CE_CMP too short");+ c = new_constant(r, cur, AIR_CONST_EXPR);+ c->expr_op = AIR_OP_CMP;+ c->expr_sub = e.ops[3];+ expr_operands(r, c, 2);+ c->pending[0] = e.ops[1];+ c->pending[1] = e.ops[2];+ break;+ default:+ return fail(r, "unknown constant record %u", e.id);+ }+ if (r->m->error[0])+ return false;+ }++ /* aggregates and expressions may name constants that come after them */+ for (unsigned i = first; i < r->num_values; i++) {+ struct air_constant *c = (struct air_constant *)r->values[i];+ if (!c->pending)+ continue;+ if (c->ckind == AIR_CONST_AGGREGATE) {+ for (unsigned k = 0; k < c->num_elems; k++)+ if (!(c->elems[k] = value_by_id(r, c->pending[k])))+ return false;+ } else {+ for (unsigned k = 0; k < c->num_operands; k++)+ if (!(c->operands[k] = value_by_id(r, c->pending[k])))+ return false;+ }+ c->pending = NULL;+ }+ return true;+}++/* -- metadata ----------------------------------------------------------- */++static struct air_md *+new_md(struct reader *r, enum air_md_kind k)+{+ struct air_md *md = rzalloc(r->m, struct air_md);+ md->kind = k;+ md->id = r->num_md;+ md->function_local = r->cur_fn != NULL;+ if (r->num_md == r->cap_md) {+ r->cap_md = MAX2(256, r->cap_md * 2);+ r->md = reralloc(r->m, r->md, struct air_md *, r->cap_md);+ }+ r->md[r->num_md++] = md;+ return md;+}++static bool+read_md_strings(struct reader *r, const struct air_bs_entry *e)+{+ if (e->num_ops < 2 || !e->blob)+ return fail(r, "METADATA_STRINGS without counts or blob");+ unsigned count = e->ops[0];+ size_t lengths_size = e->ops[1];+ if (lengths_size > e->blob_size)+ return fail(r, "METADATA_STRINGS offsets past the blob");++ /* the lengths are a little bitstream of VBR6 values */+ struct air_bitstream lens = {+ .mem_ctx = r->m,+ .data = e->blob,+ .size_bits = lengths_size * 8,+ };+ const char *chars = (const char *)e->blob + lengths_size;+ size_t avail = e->blob_size - lengths_size;+ size_t off = 0;+ for (unsigned i = 0; i < count; i++) {+ uint64_t len = 0, shift = 0, chunk;+ do {+ if (lens.pos + 6 > lens.size_bits)+ return fail(r, "METADATA_STRINGS lengths run out");+ chunk = 0;+ for (unsigned b = 0; b < 6; b++, lens.pos++)+ chunk |= (uint64_t)((lens.data[lens.pos >> 3] >> (lens.pos & 7)) & 1) << b;+ len |= (chunk & 31) << shift;+ shift += 5;+ } while (chunk & 32);+ if (off + len > avail)+ return fail(r, "METADATA_STRINGS string past the blob");+ struct air_md *md = new_md(r, AIR_MD_STRING);+ md->str = chars + off;+ md->len = len;+ off += len;+ }+ return true;+}++static bool+md_other_code(unsigned code)+{+ /* records that define one metadata node each and that the frontend does+ * not look into: locations and the DI* family+ */+ return code == METADATA_LOCATION || (code >= 12 && code <= 34) || code == 37 ||+ code == 40 || code == 41 || code == 44 || code == 45 || code == 47;+}++static bool+read_metadata_block(struct reader *r)+{+ unsigned first = r->num_md;++ for (;;) {+ struct air_bs_entry e = air_bs_next(&r->bs);+ if (e.kind == AIR_BS_END_BLOCK)+ break;+ if (e.kind == AIR_BS_ENTER_BLOCK) {+ air_bs_skip_block(&r->bs);+ continue;+ }+ if (e.kind != AIR_BS_RECORD)+ return check_bs(r) && fail(r, "metadata block ends early");++ struct air_md *md;+ switch (e.id) {+ case METADATA_STRINGS:+ if (!read_md_strings(r, &e))+ return false;+ break;+ case METADATA_STRING_OLD:+ md = new_md(r, AIR_MD_STRING);+ md->str = air_bs_ops_to_string(r->m, e.ops, e.num_ops);+ md->len = e.num_ops;+ break;+ case METADATA_VALUE:+ if (e.num_ops != 2)+ return fail(r, "METADATA_VALUE of %u operands", e.num_ops);+ md = new_md(r, AIR_MD_VALUE);+ md->value_type = type_by_id(r, e.ops[0]);+ md->value_id = e.ops[1];+ break;+ case METADATA_NODE:+ case METADATA_DISTINCT_NODE:+ md = new_md(r, AIR_MD_NODE);+ md->distinct = e.id == METADATA_DISTINCT_NODE;+ md->num_ops = e.num_ops;+ md->ops = rzalloc_array(r->m, struct air_md *, MAX2(e.num_ops, 1));+ md->pending = rzalloc_array(r->m, unsigned, MAX2(e.num_ops, 1));+ for (unsigned i = 0; i < e.num_ops; i++)+ md->pending[i] = e.ops[i]; /* id + 1, 0 for null */+ break;+ case METADATA_NAME:+ r->pending_md_name = air_bs_ops_to_string(r->m, e.ops, e.num_ops);+ break;+ case METADATA_NAMED_NODE: {+ if (!r->pending_md_name)+ return fail(r, "NAMED_NODE without a NAME");+ struct air_module *m = r->m;+ m->named_md = reralloc(m, m->named_md, struct air_named_md, m->num_named_md + 1);+ struct air_named_md *n = &m->named_md[m->num_named_md++];+ n->name = r->pending_md_name;+ r->pending_md_name = NULL;+ n->num_ops = e.num_ops;+ n->ops = rzalloc_array(m, struct air_md *, MAX2(e.num_ops, 1));+ /* resolved below: these ids are plain, not + 1 */+ for (unsigned i = 0; i < e.num_ops; i++)+ n->ops[i] = (struct air_md *)(uintptr_t)(e.ops[i] + 1);+ break;+ }+ case METADATA_KIND: {+ if (e.num_ops < 1)+ return fail(r, "METADATA_KIND without an id");+ struct air_module *m = r->m;+ unsigned id = e.ops[0];+ if (id >= m->num_md_kinds) {+ m->md_kind_names = rerzalloc(m, m->md_kind_names, const char *, m->num_md_kinds, id + 1);+ m->num_md_kinds = id + 1;+ }+ m->md_kind_names[id] = air_bs_ops_to_string(m, e.ops + 1, e.num_ops - 1);+ break;+ }+ case METADATA_INDEX_OFFSET:+ case METADATA_INDEX:+ case METADATA_GLOBAL_DECL_ATTACHMENT:+ break; /* for lazy loading and global attachments; nothing AIR needs */+ case METADATA_OLD_NODE:+ case METADATA_OLD_FN_NODE:+ case METADATA_ARG_LIST:+ return fail(r, "unsupported metadata record %u", e.id);+ default:+ if (md_other_code(e.id)) {+ md = new_md(r, AIR_MD_OTHER);+ md->code = e.id;+ break;+ }+ return fail(r, "unknown metadata record %u", e.id);+ }+ if (r->m->error[0])+ return false;+ }++ /* nodes may name later nodes */+ for (unsigned i = first; i < r->num_md; i++) {+ struct air_md *md = r->md[i];+ if (md->kind != AIR_MD_NODE || !md->pending)+ continue;+ for (unsigned k = 0; k < md->num_ops; k++) {+ unsigned id = md->pending[k];+ if (id == 0)+ continue;+ if (id - 1 >= r->num_md)+ return fail(r, "metadata node names !%u of %u", id - 1, r->num_md);+ md->ops[k] = r->md[id - 1];+ }+ md->pending = NULL;+ }+ return true;+}++/* values named by metadata, once the values exist */+static bool+resolve_md_values(struct reader *r, unsigned first)+{+ for (unsigned i = first; i < r->num_md; i++) {+ struct air_md *md = r->md[i];+ if (md->kind == AIR_MD_VALUE && !md->value)+ if (!(md->value = value_by_id(r, md->value_id)))+ return false;+ }+ return true;+}++static bool+resolve_named_md(struct reader *r)+{+ struct air_module *m = r->m;+ for (unsigned i = 0; i < m->num_named_md; i++) {+ struct air_named_md *n = &m->named_md[i];+ for (unsigned k = 0; k < n->num_ops; k++) {+ uintptr_t id = (uintptr_t)n->ops[k] - 1;+ if (id >= r->num_md)+ return fail(r, "named metadata %s names !%u", n->name, (unsigned)id);+ n->ops[k] = r->md[id];+ }+ }+ return true;+}++static bool+read_metadata_kind_block(struct reader *r)+{+ for (;;) {+ struct air_bs_entry e = air_bs_next(&r->bs);+ if (e.kind == AIR_BS_END_BLOCK)+ return true;+ if (e.kind != AIR_BS_RECORD)+ return check_bs(r) && fail(r, "metadata kind block ends early");+ if (e.id == METADATA_KIND && e.num_ops >= 1) {+ struct air_module *m = r->m;+ unsigned id = e.ops[0];+ if (id >= m->num_md_kinds) {+ m->md_kind_names = rerzalloc(m, m->md_kind_names, const char *, m->num_md_kinds, id + 1);+ m->num_md_kinds = id + 1;+ }+ m->md_kind_names[id] = air_bs_ops_to_string(m, e.ops + 1, e.num_ops - 1);+ }+ }+}++/* -- module records ----------------------------------------------------- */++static bool+read_globalvar(struct reader *r, const struct air_bs_entry *e)+{+ struct air_module *m = r->m;+ if (r->m->version < 2)+ return fail(r, "module version %u: only bitcode with a string table is read", m->version);+ if (e->num_ops < 8)+ return fail(r, "GLOBALVAR too short");++ struct air_global *g = rzalloc(m, struct air_global);+ g->base.kind = AIR_VALUE_GLOBAL;+ g->strtab_offset = e->ops[0];+ g->strtab_size = e->ops[1];+ const struct air_type *t = type_by_id(r, e->ops[2]);+ if (!t)+ return false;+ uint64_t flags = e->ops[3];+ g->is_const = flags & 1;+ if (flags & 2) {+ g->value_type = t;+ g->addrspace = flags >> 2;+ } else {+ if (t->kind != AIR_TYPE_POINTER || !t->elem)+ return fail(r, "GLOBALVAR of a non-pointer type");+ g->value_type = t->elem;+ g->addrspace = t->addrspace;+ }+ g->base.type = pointer_to(r, g->value_type, g->addrspace);+ g->init_id = e->ops[4];+ g->linkage = e->ops[5];+ g->align = e->ops[6] ? 1u << (e->ops[6] - 1) : 0;+ if (e->ops[7]) {+ if (e->ops[7] - 1 >= m->num_section_names)+ return fail(r, "GLOBALVAR names section %" PRIu64, e->ops[7] - 1);+ g->section = m->section_names[e->ops[7] - 1];+ }+ if (e->num_ops > 10)+ g->unnamed_addr = e->ops[10];+ if (e->num_ops > 11)+ g->externally_initialized = e->ops[11];+ if (e->num_ops > 9 && e->ops[9])+ return fail(r, "thread-local global");++ m->globals = reralloc(m, m->globals, struct air_global *, m->num_globals + 1);+ m->globals[m->num_globals++] = g;+ push_value(r, &g->base);+ return true;+}++static bool+read_function_record(struct reader *r, const struct air_bs_entry *e)+{+ struct air_module *m = r->m;+ if (m->version < 2)+ return fail(r, "module version %u: only bitcode with a string table is read", m->version);+ if (e->num_ops < 8)+ return fail(r, "FUNCTION too short");++ struct air_function *f = rzalloc(m, struct air_function);+ f->base.kind = AIR_VALUE_FUNCTION;+ f->strtab_offset = e->ops[0];+ f->strtab_size = e->ops[1];+ const struct air_type *t = type_by_id(r, e->ops[2]);+ if (!t)+ return false;+ if (t->kind == AIR_TYPE_POINTER && t->elem)+ t = t->elem;+ if (t->kind != AIR_TYPE_FUNCTION)+ return fail(r, "FUNCTION record of a non-function type");+ f->fn_type = t;+ unsigned as = e->num_ops > 18 ? e->ops[18] : 0;+ f->base.type = pointer_to(r, t, as);+ f->cc = e->ops[3];+ f->is_declaration = e->ops[4];+ f->linkage = e->ops[5];+ f->paramattr = e->ops[6];+ f->align = e->ops[7] ? 1u << (e->ops[7] - 1) : 0;+ if (e->ops[8]) {+ if (e->ops[8] - 1 >= m->num_section_names)+ return fail(r, "FUNCTION names section %" PRIu64, e->ops[8] - 1);+ f->section = m->section_names[e->ops[8] - 1];+ }+ if (e->num_ops > 11)+ f->unnamed_addr = e->ops[11];+ if (e->num_ops > 16 && e->ops[16])+ return fail(r, "function with a personality");++ f->num_args = t->num_members;+ f->args = rzalloc_array(m, struct air_value, MAX2(f->num_args, 1));+ for (unsigned i = 0; i < f->num_args; i++) {+ f->args[i].kind = AIR_VALUE_ARGUMENT;+ f->args[i].type = t->members[i];+ }++ m->functions = reralloc(m, m->functions, struct air_function *, m->num_functions + 1);+ m->functions[m->num_functions++] = f;+ push_value(r, &f->base);+ return true;+}++/* -- function bodies ---------------------------------------------------- */++struct rec {+ const struct air_bs_entry *e;+ unsigned i;+ bool bad;+};++static uint64_t+take(struct rec *rc)+{+ if (rc->i >= rc->e->num_ops) {+ rc->bad = true;+ return 0;+ }+ return rc->e->ops[rc->i++];+}++static bool+more(const struct rec *rc)+{+ return rc->i < rc->e->num_ops;+}++/* a relative operand without a type (the type is known from context) */+static unsigned+take_value(struct reader *r, struct rec *rc)+{+ return (uint32_t)r->num_values - (uint32_t)take(rc);+}++/* a relative operand that carries its type when it is a forward reference */+static unsigned+take_value_type(struct reader *r, struct rec *rc)+{+ unsigned id = (uint32_t)r->num_values - (uint32_t)take(rc);+ if (id >= r->num_values) {+ const struct air_type *t = type_by_id(r, take(rc));+ if (id >= r->cap_fwd) {+ unsigned cap = MAX2(id + 1, MAX2(64, r->cap_fwd * 2));+ r->fwd = rerzalloc(r->m, r->fwd, const struct air_type *, r->cap_fwd, cap);+ r->cap_fwd = cap;+ }+ r->fwd[id] = t;+ }+ return id;+}++static struct air_inst *+new_inst(struct reader *r, enum air_opcode op, const struct air_type *type, unsigned num_operands)+{+ struct air_inst *in = rzalloc(r->m, struct air_inst);+ in->base.kind = AIR_VALUE_INSTRUCTION;+ in->base.type = type;+ in->op = op;+ in->num_operands = num_operands;+ in->operands = rzalloc_array(r->m, struct air_value *, MAX2(num_operands, 1));+ in->operand_ids = rzalloc_array(r->m, unsigned, MAX2(num_operands, 1));+ return in;+}++static const struct air_type *+type_of_id(struct reader *r, unsigned id)+{+ if (id < r->num_values && r->values[id])+ return r->values[id]->type;+ if (id < r->cap_fwd && r->fwd[id])+ return r->fwd[id];+ fail(r, "operand %u has no type (a forward reference whose record gave none)", id);+ return NULL;+}++static unsigned+decode_align(uint64_t v)+{+ unsigned log2 = v & 31;+ return log2 ? 1u << (log2 - 1) : 0;+}++static const struct air_type *+gep_result_type(struct reader *r, const struct air_type *src, const struct air_type *ptr_type,+ struct air_inst *in, unsigned first_index)+{+ /* the result is a pointer in the base's address space; its element type+ * (for printing typed pointers) is what the indices reach+ */+ /* index 0 steps over the pointer; the ones after it go into the type */+ const struct air_type *t = src;+ for (unsigned i = first_index + 2; i < in->num_operands && t; i++) {+ if (t->kind == AIR_TYPE_STRUCT) {+ unsigned id = in->operand_ids[i];+ uint64_t n;+ if (id >= r->num_values || !r->values[id] || !air_const_uint(r->values[id], &n) ||+ n >= t->num_members)+ return NULL;+ t = t->members[n];+ } else if (t->kind == AIR_TYPE_ARRAY || t->kind == AIR_TYPE_VECTOR) {+ t = t->elem;+ } else {+ return NULL;+ }+ }+ unsigned as = air_type_scalar(ptr_type)->addrspace;+ if (ptr_type->kind == AIR_TYPE_VECTOR)+ return NULL; /* vector GEPs: not in AIR */+ return pointer_to(r, t, as);+}++static bool+add_inst(struct reader *r, struct air_block **block, struct air_inst *in)+{+ struct air_block *b = *block;+ if (!b)+ return fail(r, "instruction after the last block");+ if (b->num_insts == b->cap_insts) {+ b->cap_insts = MAX2(16, b->cap_insts * 2);+ b->insts = reralloc(r->m, b->insts, struct air_inst *, b->cap_insts);+ }+ b->insts[b->num_insts++] = in;+ in->parent = b;++ if (r->num_fn_insts == r->cap_fn_insts) {+ r->cap_fn_insts = MAX2(64, r->cap_fn_insts * 2);+ r->fn_insts = reralloc(r->m, r->fn_insts, struct air_inst *, r->cap_fn_insts);+ }+ r->fn_insts[r->num_fn_insts++] = in;++ if (in->base.type && in->base.type->kind != AIR_TYPE_VOID)+ push_value(r, &in->base);++ /* terminators move on to the next block */+ if (in->op == AIR_OP_RET || in->op == AIR_OP_BR || in->op == AIR_OP_SWITCH ||+ in->op == AIR_OP_UNREACHABLE) {+ struct air_function *f = r->cur_fn;+ unsigned next = b->index + 1;+ *block = next < f->num_blocks ? &f->blocks[next] : NULL;+ }+ return true;+}++static bool+read_instruction(struct reader *r, const struct air_bs_entry *e, struct air_block **block)+{+ struct air_module *m = r->m;+ struct rec rc = { .e = e };+ struct air_inst *in = NULL;+ unsigned a, b, c;++ switch (e->id) {+ case FUNC_CODE_INST_BINOP: {+ a = take_value_type(r, &rc);+ b = take_value(r, &rc);+ unsigned opc = take(&rc);+ const struct air_type *t = type_of_id(r, a);+ if (!t)+ return false;+ in = new_inst(r, AIR_OP_BINOP, t, 2);+ in->operand_ids[0] = a;+ in->operand_ids[1] = b;+ in->sub = opc;+ if (more(&rc))+ in->flags = take(&rc);+ break;+ }+ case FUNC_CODE_INST_UNOP: {+ a = take_value_type(r, &rc);+ unsigned opc = take(&rc);+ const struct air_type *t = type_of_id(r, a);+ if (!t)+ return false;+ in = new_inst(r, AIR_OP_UNOP, t, 1);+ in->operand_ids[0] = a;+ in->sub = opc;+ if (more(&rc))+ in->flags = take(&rc);+ break;+ }+ case FUNC_CODE_INST_CAST: {+ a = take_value_type(r, &rc);+ const struct air_type *t = type_by_id(r, take(&rc));+ unsigned opc = take(&rc);+ if (!t)+ return false;+ in = new_inst(r, AIR_OP_CAST, t, 1);+ in->operand_ids[0] = a;+ in->sub = opc;+ if (more(&rc))+ in->flags = take(&rc);+ break;+ }+ case FUNC_CODE_INST_GEP: {+ bool inbounds = take(&rc) & 1;+ const struct air_type *src = type_by_id(r, take(&rc));+ unsigned ids[64], n = 0;+ while (more(&rc) && n < ARRAY_SIZE(ids))+ ids[n++] = take_value_type(r, &rc);+ if (!src || n == 0 || more(&rc))+ return fail(r, "GEP of %u operands", n);+ const struct air_type *pt = type_of_id(r, ids[0]);+ if (!pt)+ return false;+ in = new_inst(r, AIR_OP_GEP, NULL, n);+ memcpy(in->operand_ids, ids, n * sizeof(unsigned));+ in->inbounds = inbounds;+ in->aux_type = src;+ in->base.type = gep_result_type(r, src, pt, in, 0);+ if (!in->base.type)+ return fail(r, "GEP whose result type cannot be worked out");+ break;+ }+ case FUNC_CODE_INST_SELECT:+ case FUNC_CODE_INST_VSELECT: {+ a = take_value_type(r, &rc);+ b = take_value(r, &rc);+ c = e->id == FUNC_CODE_INST_VSELECT ? take_value_type(r, &rc) : take_value(r, &rc);+ const struct air_type *t = type_of_id(r, a);+ if (!t)+ return false;+ in = new_inst(r, AIR_OP_SELECT, t, 3);+ in->operand_ids[0] = c; /* condition first, like LLVM's operand order */+ in->operand_ids[1] = a;+ in->operand_ids[2] = b;+ if (more(&rc))+ in->flags = take(&rc);+ break;+ }+ case FUNC_CODE_INST_EXTRACTELT: {+ a = take_value_type(r, &rc);+ b = take_value_type(r, &rc);+ const struct air_type *t = type_of_id(r, a);+ if (!t)+ return false;+ if (t->kind != AIR_TYPE_VECTOR)+ return fail(r, "extractelement of a non-vector");+ in = new_inst(r, AIR_OP_EXTRACTELT, t->elem, 2);+ in->operand_ids[0] = a;+ in->operand_ids[1] = b;+ break;+ }+ case FUNC_CODE_INST_INSERTELT: {+ a = take_value_type(r, &rc);+ b = take_value(r, &rc);+ c = take_value_type(r, &rc);+ const struct air_type *t = type_of_id(r, a);+ if (!t)+ return false;+ in = new_inst(r, AIR_OP_INSERTELT, t, 3);+ in->operand_ids[0] = a;+ in->operand_ids[1] = b;+ in->operand_ids[2] = c;+ break;+ }+ case FUNC_CODE_INST_SHUFFLEVEC: {+ a = take_value_type(r, &rc);+ b = take_value(r, &rc);+ c = take_value_type(r, &rc);+ const struct air_type *t = type_of_id(r, a);+ const struct air_type *mt = type_of_id(r, c);+ if (!t || !mt)+ return false;+ if (t->kind != AIR_TYPE_VECTOR || mt->kind != AIR_TYPE_VECTOR)+ return fail(r, "shufflevector of non-vectors");+ /* the result has the mask's length and the inputs' element */+ const struct air_type *rt = NULL;+ for (unsigned i = 0; i < m->num_types; i++) {+ const struct air_type *x = &m->types[i];+ if (x->kind == AIR_TYPE_VECTOR && x->elem == t->elem && x->count == mt->count) {+ rt = x;+ break;+ }+ }+ if (!rt)+ return fail(r, "shufflevector result type not in the type table");+ in = new_inst(r, AIR_OP_SHUFFLEVEC, rt, 3);+ in->operand_ids[0] = a;+ in->operand_ids[1] = b;+ in->operand_ids[2] = c;+ break;+ }+ case FUNC_CODE_INST_CMP:+ case FUNC_CODE_INST_CMP2: {+ a = take_value_type(r, &rc);+ b = take_value(r, &rc);+ unsigned pred = take(&rc);+ const struct air_type *t = type_of_id(r, a);+ if (!t)+ return false;+ /* i1, or a vector of i1 as long as the operands */+ const struct air_type *rt = NULL;+ for (unsigned i = 0; i < m->num_types; i++) {+ const struct air_type *x = &m->types[i];+ if (t->kind == AIR_TYPE_VECTOR) {+ if (x->kind == AIR_TYPE_VECTOR && x->count == t->count && x->elem->kind == AIR_TYPE_INT &&+ x->elem->bits == 1) {+ rt = x;+ break;+ }+ } else if (x->kind == AIR_TYPE_INT && x->bits == 1) {+ rt = x;+ break;+ }+ }+ if (!rt)+ return fail(r, "compare result type not in the type table");+ in = new_inst(r, AIR_OP_CMP, rt, 2);+ in->operand_ids[0] = a;+ in->operand_ids[1] = b;+ in->sub = pred;+ if (more(&rc))+ in->flags = take(&rc);+ break;+ }+ case FUNC_CODE_INST_RET:+ if (e->num_ops == 0) {+ in = new_inst(r, AIR_OP_RET, NULL, 0);+ } else {+ a = take_value_type(r, &rc);+ in = new_inst(r, AIR_OP_RET, NULL, 1);+ in->operand_ids[0] = a;+ }+ break;+ case FUNC_CODE_INST_BR:+ if (e->num_ops == 1) {+ in = new_inst(r, AIR_OP_BR, NULL, 0);+ in->num_targets = 1;+ in->target_ids = ralloc_array(m, unsigned, 1);+ in->target_ids[0] = take(&rc);+ } else if (e->num_ops == 3) {+ in = new_inst(r, AIR_OP_BR, NULL, 1);+ in->num_targets = 2;+ in->target_ids = ralloc_array(m, unsigned, 2);+ in->target_ids[0] = take(&rc);+ in->target_ids[1] = take(&rc);+ in->operand_ids[0] = take_value(r, &rc);+ } else {+ return fail(r, "br of %u operands", e->num_ops);+ }+ break;+ case FUNC_CODE_INST_UNREACHABLE:+ in = new_inst(r, AIR_OP_UNREACHABLE, NULL, 0);+ break;+ case FUNC_CODE_INST_PHI: {+ const struct air_type *t = type_by_id(r, take(&rc));+ if (!t)+ return false;+ unsigned n = (e->num_ops - 1) / 2;+ in = new_inst(r, AIR_OP_PHI, t, n);+ in->num_targets = n;+ in->target_ids = ralloc_array(m, unsigned, MAX2(n, 1));+ for (unsigned i = 0; i < n; i++) {+ int64_t rel = decode_signed(take(&rc));+ in->operand_ids[i] = (uint32_t)((int64_t)r->num_values - rel);+ in->target_ids[i] = take(&rc);+ }+ if (more(&rc))+ in->flags = take(&rc);+ break;+ }+ case FUNC_CODE_INST_ALLOCA: {+ uint64_t ty = take(&rc), opty = take(&rc), size = take(&rc), align = take(&rc);+ (void)opty;+ const struct air_type *t = type_by_id(r, ty);+ if (!t)+ return false;+ bool explicit_type = align & (1u << 6);+ const struct air_type *allocated = explicit_type ? t : t->elem;+ if (!allocated)+ return fail(r, "alloca without an allocated type");+ unsigned as = more(&rc) ? take(&rc) : 0;+ in = new_inst(r, AIR_OP_ALLOCA, pointer_to(r, allocated, as), 1);+ in->aux_type = allocated;+ in->operand_ids[0] = size; /* absolute, unlike other operands */+ in->align = ((align & 31) | ((align >> 8) << 5)) ? 1u << (((align & 31) | ((align >> 8) << 5)) - 1) : 0;+ break;+ }+ case FUNC_CODE_INST_LOAD: {+ a = take_value_type(r, &rc);+ const struct air_type *t;+ if (rc.e->num_ops - rc.i == 3) {+ t = type_by_id(r, take(&rc));+ } else {+ const struct air_type *pt = type_of_id(r, a);+ t = pt ? pt->elem : NULL;+ }+ if (!t)+ return fail(r, "load of unknown type");+ in = new_inst(r, AIR_OP_LOAD, t, 1);+ in->operand_ids[0] = a;+ in->align = decode_align(take(&rc));+ in->is_volatile = take(&rc);+ break;+ }+ case FUNC_CODE_INST_STORE: {+ a = take_value_type(r, &rc); /* the pointer */+ b = take_value_type(r, &rc); /* the value */+ in = new_inst(r, AIR_OP_STORE, NULL, 2);+ in->operand_ids[0] = b; /* value first, as LLVM orders them */+ in->operand_ids[1] = a;+ in->align = decode_align(take(&rc));+ in->is_volatile = take(&rc);+ break;+ }+ case FUNC_CODE_INST_EXTRACTVAL: {+ a = take_value_type(r, &rc);+ const struct air_type *t = type_of_id(r, a);+ if (!t)+ return false;+ unsigned n = e->num_ops - rc.i;+ uint32_t *idx = ralloc_array(m, uint32_t, MAX2(n, 1));+ for (unsigned i = 0; i < n; i++) {+ idx[i] = take(&rc);+ if (t->kind == AIR_TYPE_STRUCT && idx[i] < t->num_members)+ t = t->members[idx[i]];+ else if (t->kind == AIR_TYPE_ARRAY && idx[i] < t->count)+ t = t->elem;+ else+ return fail(r, "extractvalue index out of the aggregate");+ }+ in = new_inst(r, AIR_OP_EXTRACTVAL, t, 1);+ in->operand_ids[0] = a;+ in->num_indices = n;+ in->indices = idx;+ break;+ }+ case FUNC_CODE_INST_INSERTVAL: {+ a = take_value_type(r, &rc);+ b = take_value_type(r, &rc);+ const struct air_type *t = type_of_id(r, a);+ if (!t)+ return false;+ unsigned n = e->num_ops - rc.i;+ in = new_inst(r, AIR_OP_INSERTVAL, t, 2);+ in->operand_ids[0] = a;+ in->operand_ids[1] = b;+ in->num_indices = n;+ in->indices = ralloc_array(m, uint32_t, MAX2(n, 1));+ for (unsigned i = 0; i < n; i++)+ in->indices[i] = take(&rc);+ break;+ }+ case FUNC_CODE_INST_CALL: {+ take(&rc); /* paramattrs: an index into PARAMATTR, nothing the translation uses */+ uint64_t cc = take(&rc);+ unsigned fmf = 0;+ if (cc & (1u << CALL_FMF_BIT))+ fmf = take(&rc);+ const struct air_type *fty = NULL;+ if (cc & (1u << CALL_EXPLICIT_TYPE_BIT))+ fty = type_by_id(r, take(&rc));+ unsigned callee = take_value_type(r, &rc);+ if (!fty) {+ const struct air_type *pt = type_of_id(r, callee);+ fty = pt ? pt->elem : NULL;+ }+ if (!fty || fty->kind != AIR_TYPE_FUNCTION)+ return fail(r, "call without a function type");+ unsigned n = fty->num_members;+ unsigned ids[64];+ if (n >= ARRAY_SIZE(ids))+ return fail(r, "call of %u arguments", n);+ for (unsigned i = 0; i < n; i++) {+ if (fty->members[i]->kind == AIR_TYPE_LABEL)+ return fail(r, "call with a label argument");+ ids[i] = take_value(r, &rc);+ }+ unsigned extra = 0;+ if (fty->vararg) {+ while (more(&rc) && n + extra < ARRAY_SIZE(ids)) {+ ids[n + extra] = take_value_type(r, &rc);+ extra++;+ }+ }+ if (rc.bad || more(&rc))+ return fail(r, "call record does not match its function type");+ in = new_inst(r, AIR_OP_CALL, fty->elem, 1 + n + extra);+ in->operand_ids[0] = callee;+ memcpy(in->operand_ids + 1, ids, (n + extra) * sizeof(unsigned));+ in->aux_type = fty;+ in->tail = cc & (1u << CALL_TAIL_BIT);+ in->flags = fmf;+ in->cc = (cc >> CALL_CCONV_SHIFT) & 0x3ff;+ break;+ }+ case FUNC_CODE_INST_FREEZE: {+ a = take_value_type(r, &rc);+ const struct air_type *t = type_of_id(r, a);+ if (!t)+ return false;+ in = new_inst(r, AIR_OP_FREEZE, t, 1);+ in->operand_ids[0] = a;+ break;+ }+ case FUNC_CODE_DEBUG_LOC:+ case FUNC_CODE_DEBUG_LOC_AGAIN:+ return true; /* not instructions */+ case FUNC_CODE_DECLAREBLOCKS:+ return fail(r, "DECLAREBLOCKS twice");+ case FUNC_CODE_OPERAND_BUNDLE:+ return fail(r, "operand bundles");+ default:+ return fail(r, "unsupported instruction record %u", e->id);+ }++ if (rc.bad)+ return fail(r, "instruction record %u too short", e->id);+ r->cur_inst_id++;+ return add_inst(r, block, in);+}++static bool+read_attachments(struct reader *r)+{+ for (;;) {+ struct air_bs_entry e = air_bs_next(&r->bs);+ if (e.kind == AIR_BS_END_BLOCK)+ return true;+ if (e.kind != AIR_BS_RECORD)+ return check_bs(r) && fail(r, "attachment block ends early");+ if (e.id != METADATA_ATTACHMENT)+ continue;+ if (e.num_ops % 2 == 0)+ continue; /* attachments of the function itself */+ unsigned inst = e.ops[0];+ if (inst >= r->num_fn_insts)+ return fail(r, "attachment to instruction %u of %u", inst, r->num_fn_insts);+ struct air_inst *in = r->fn_insts[inst];+ unsigned n = (e.num_ops - 1) / 2;+ in->attachments = ralloc_array(r->m, __typeof__(*in->attachments), n);+ in->num_attachments = n;+ for (unsigned i = 0; i < n; i++) {+ unsigned id = e.ops[2 + 2 * i];+ if (id >= r->num_md)+ return fail(r, "attachment of !%u of %u", id, r->num_md);+ in->attachments[i].kind = e.ops[1 + 2 * i];+ in->attachments[i].md = r->md[id];+ }+ }+}++static bool+read_function_vst(struct reader *r, unsigned first_local)+{+ struct air_function *f = r->cur_fn;+ for (;;) {+ struct air_bs_entry e = air_bs_next(&r->bs);+ if (e.kind == AIR_BS_END_BLOCK)+ return true;+ if (e.kind != AIR_BS_RECORD)+ return check_bs(r) && fail(r, "symbol table ends early");+ if (e.num_ops < 1)+ continue;+ const char *name = air_bs_ops_to_string(r->m, e.ops + 1, e.num_ops - 1);+ if (e.id == VST_CODE_ENTRY) {+ if (e.ops[0] < first_local)+ continue;+ struct air_value *v = value_by_id(r, e.ops[0]);+ if (!v)+ return false;+ v->name = name;+ } else if (e.id == VST_CODE_BBENTRY) {+ if (e.ops[0] >= f->num_blocks)+ return fail(r, "name for block %" PRIu64, e.ops[0]);+ f->blocks[e.ops[0]].name = name;+ }+ }+}++static struct air_function *+next_body(struct reader *r)+{+ struct air_module *m = r->m;+ unsigned seen = 0;+ for (unsigned i = 0; i < m->num_functions; i++) {+ if (m->functions[i]->is_declaration)+ continue;+ if (seen++ == r->num_bodies_read) {+ r->num_bodies_read++;+ return m->functions[i];+ }+ }+ return NULL;+}++static bool+read_function_block(struct reader *r)+{+ struct air_function *f = next_body(r);+ if (!f)+ return fail(r, "a function body for no function");++ unsigned module_values = r->num_values;+ unsigned module_md = r->num_md;+ r->cur_fn = f;+ r->cur_inst_id = 0;+ r->num_fn_insts = 0;+ if (r->cap_fwd)+ memset(r->fwd, 0, r->cap_fwd * sizeof(*r->fwd));++ for (unsigned i = 0; i < f->num_args; i++)+ push_value(r, &f->args[i]);+ unsigned first_local = module_values;++ struct air_block *block = NULL;+ for (;;) {+ struct air_bs_entry e = air_bs_next(&r->bs);+ if (e.kind == AIR_BS_END_BLOCK)+ break;+ if (e.kind == AIR_BS_ENTER_BLOCK) {+ bool ok;+ switch (e.id) {+ case CONSTANTS_BLOCK_ID:+ air_bs_enter(&r->bs, e.id);+ ok = read_constants_block(r);+ break;+ case METADATA_BLOCK_ID:+ air_bs_enter(&r->bs, e.id);+ ok = read_metadata_block(r);+ break;+ case METADATA_ATTACHMENT_ID:+ air_bs_enter(&r->bs, e.id);+ ok = read_attachments(r);+ break;+ case VALUE_SYMTAB_BLOCK_ID:+ air_bs_enter(&r->bs, e.id);+ ok = read_function_vst(r, first_local);+ break;+ default:+ ok = air_bs_skip_block(&r->bs); /* USELIST and the like */+ break;+ }+ if (!ok)+ return false;+ continue;+ }+ if (e.kind != AIR_BS_RECORD)+ return check_bs(r) && fail(r, "function block ends early");++ if (e.id == FUNC_CODE_DECLAREBLOCKS) {+ if (e.num_ops < 1 || f->blocks)+ return fail(r, "bad DECLAREBLOCKS");+ f->num_blocks = e.ops[0];+ f->blocks = rzalloc_array(r->m, struct air_block, MAX2(f->num_blocks, 1));+ for (unsigned i = 0; i < f->num_blocks; i++)+ f->blocks[i].index = i;+ block = f->num_blocks ? &f->blocks[0] : NULL;+ continue;+ }+ if (!read_instruction(r, &e, &block))+ return false;+ }++ /* operands, now that every value of the function exists */+ for (unsigned i = 0; i < r->num_fn_insts; i++) {+ struct air_inst *in = r->fn_insts[i];+ for (unsigned k = 0; k < in->num_operands; k++) {+ if (in->op == AIR_OP_CALL && k > 0 && k - 1 < in->aux_type->num_members &&+ in->aux_type->members[k - 1]->kind == AIR_TYPE_METADATA) {+ /* a metadata argument: the id is a metadata id */+ unsigned id = in->operand_ids[k];+ if (id >= r->num_md)+ return fail(r, "metadata argument !%u", id);+ struct air_value *v = rzalloc(r->m, struct air_value);+ v->kind = AIR_VALUE_METADATA;+ v->type = in->aux_type->members[k - 1];+ v->id = id;+ in->operands[k] = v;+ continue;+ }+ if (!(in->operands[k] = value_by_id(r, in->operand_ids[k])))+ return fail(r, "instruction %u of %s: operand %u (value %u) undefined", i,+ f->base.name ? f->base.name : "?", k, in->operand_ids[k]);+ }+ if (in->num_targets) {+ in->targets = ralloc_array(r->m, struct air_block *, in->num_targets);+ for (unsigned k = 0; k < in->num_targets; k++) {+ if (in->target_ids[k] >= f->num_blocks)+ return fail(r, "branch to block %u of %u", in->target_ids[k], f->num_blocks);+ in->targets[k] = &f->blocks[in->target_ids[k]];+ }+ }+ in->operand_ids = NULL;+ in->target_ids = NULL;+ }+ for (unsigned i = 0; i < f->num_blocks; i++) {+ if (f->blocks[i].num_insts == 0)+ return fail(r, "block %u of a function is empty", i);+ }+ if (!resolve_md_values(r, module_md))+ return false;++ f->num_values = r->num_values - module_values;+ /* the function's values and metadata are its own: the next one starts over */+ r->num_values = module_values;+ r->num_md = module_md;+ r->cur_fn = NULL;+ return true;+}++/* -- the module block --------------------------------------------------- */++static bool+read_module_block(struct reader *r)+{+ struct air_module *m = r->m;+ bool module_md_resolved = false;++ for (;;) {+ struct air_bs_entry e = air_bs_next(&r->bs);+ if (e.kind == AIR_BS_END_BLOCK)+ break;++ if (e.kind == AIR_BS_ENTER_BLOCK) {+ bool ok = true;+ switch (e.id) {+ case TYPE_BLOCK_ID_NEW:+ air_bs_enter(&r->bs, e.id);+ ok = read_type_block(r);+ break;+ case CONSTANTS_BLOCK_ID:+ air_bs_enter(&r->bs, e.id);+ ok = read_constants_block(r);+ break;+ case METADATA_BLOCK_ID:+ air_bs_enter(&r->bs, e.id);+ ok = read_metadata_block(r);+ break;+ case METADATA_KIND_BLOCK_ID:+ air_bs_enter(&r->bs, e.id);+ ok = read_metadata_kind_block(r);+ break;+ case FUNCTION_BLOCK_ID:+ if (!module_md_resolved) {+ /* module-level values are complete once bodies begin */+ m->num_module_values = r->num_values;+ ok = resolve_md_values(r, 0) && resolve_named_md(r);+ m->num_md = r->num_md;+ module_md_resolved = true;+ }+ air_bs_enter(&r->bs, e.id);+ ok = ok && read_function_block(r);+ break;+ default:+ /* attributes, symbol table, operand bundle tags, sync scopes,+ * use lists: nothing the translation depends on+ */+ ok = air_bs_skip_block(&r->bs);+ break;+ }+ if (!ok)+ return false;+ continue;+ }+ if (e.kind != AIR_BS_RECORD)+ return check_bs(r) && fail(r, "module block ends early");++ switch (e.id) {+ case MODULE_CODE_VERSION:+ m->version = e.num_ops ? e.ops[0] : 0;+ break;+ case MODULE_CODE_TRIPLE:+ m->triple = air_bs_ops_to_string(m, e.ops, e.num_ops);+ break;+ case MODULE_CODE_DATALAYOUT:+ m->datalayout = air_bs_ops_to_string(m, e.ops, e.num_ops);+ break;+ case MODULE_CODE_SOURCE_FILENAME:+ m->source_filename = air_bs_ops_to_string(m, e.ops, e.num_ops);+ break;+ case MODULE_CODE_SECTIONNAME:+ m->section_names = reralloc(m, m->section_names, const char *, m->num_section_names + 1);+ m->section_names[m->num_section_names++] = air_bs_ops_to_string(m, e.ops, e.num_ops);+ break;+ case MODULE_CODE_GLOBALVAR:+ if (!read_globalvar(r, &e))+ return false;+ break;+ case MODULE_CODE_FUNCTION:+ if (!read_function_record(r, &e))+ return false;+ break;+ case MODULE_CODE_VSTOFFSET:+ case MODULE_CODE_HASH:+ case MODULE_CODE_GCNAME:+ break;+ default:+ return fail(r, "unsupported module record %u", e.id);+ }+ }++ if (!module_md_resolved) {+ m->num_module_values = r->num_values;+ if (!resolve_md_values(r, 0) || !resolve_named_md(r))+ return false;+ m->num_md = r->num_md;+ }+ /* (the arrays may have moved while function bodies grew them) */+ m->module_values = r->values;+ m->md = r->md;++ /* global initializers name module-level constants */+ for (unsigned i = 0; i < m->num_globals; i++) {+ struct air_global *g = m->globals[i];+ if (g->init_id && !(g->init = value_by_id(r, g->init_id - 1)))+ return false;+ }+ if (r->num_bodies_read != 0) {+ unsigned bodies = 0;+ for (unsigned i = 0; i < m->num_functions; i++)+ bodies += !m->functions[i]->is_declaration;+ if (bodies != r->num_bodies_read)+ return fail(r, "%u function bodies for %u definitions", r->num_bodies_read, bodies);+ }+ return true;+}++static bool+read_strtab_block(struct reader *r)+{+ for (;;) {+ struct air_bs_entry e = air_bs_next(&r->bs);+ if (e.kind == AIR_BS_END_BLOCK)+ return true;+ if (e.kind != AIR_BS_RECORD)+ return check_bs(r) && fail(r, "string table ends early");+ if (e.id == 1 && e.blob) {+ r->strtab = e.blob;+ r->strtab_size = e.blob_size;+ }+ }+}++static bool+read_identification_block(struct reader *r)+{+ for (;;) {+ struct air_bs_entry e = air_bs_next(&r->bs);+ if (e.kind == AIR_BS_END_BLOCK)+ return true;+ if (e.kind != AIR_BS_RECORD)+ return check_bs(r) && fail(r, "identification block ends early");+ if (e.id == 1)+ r->m->identification = air_bs_ops_to_string(r->m, e.ops, e.num_ops);+ }+}++static const char *+strtab_name(struct reader *r, uint64_t off, uint64_t size)+{+ if (!r->strtab || off + size > r->strtab_size) {+ fail(r, "name at %" PRIu64 "+%" PRIu64 " outside the string table", off, size);+ return NULL;+ }+ return ralloc_strndup(r->m, (const char *)r->strtab + off, size);+}++struct air_module *+air_module_read(void *mem_ctx, const void *data, size_t size, const char **error)+{+ struct air_module *m = rzalloc(mem_ctx, struct air_module);+ struct reader r = { .m = m };+ m->mem_ctx = m;++ const uint8_t *p = data;+ if (size >= 20 && p[0] == 0xde && p[1] == 0xc0 && p[2] == 0x17 && p[3] == 0x0b) {+ uint32_t off = p[8] | p[9] << 8 | p[10] << 16 | (uint32_t)p[11] << 24;+ uint32_t len = p[12] | p[13] << 8 | p[14] << 16 | (uint32_t)p[15] << 24;+ if ((uint64_t)off + len > size) {+ fail(&r, "bitcode wrapper points past the data");+ goto out;+ }+ p += off;+ size = len;+ }++ if (!air_bs_init(&r.bs, m, p, size)) {+ fail(&r, "%s", r.bs.error);+ goto out;+ }++ bool seen_module = false;+ for (;;) {+ struct air_bs_entry e = air_bs_next(&r.bs);+ if (e.kind == AIR_BS_END)+ break;+ if (e.kind != AIR_BS_ENTER_BLOCK) {+ check_bs(&r) || fail(&r, "a record at the top level");+ goto out;+ }+ bool ok;+ switch (e.id) {+ case MODULE_BLOCK_ID:+ if (seen_module) {+ fail(&r, "two modules in one bitcode file");+ goto out;+ }+ seen_module = true;+ air_bs_enter(&r.bs, e.id);+ ok = read_module_block(&r);+ break;+ case STRTAB_BLOCK_ID:+ air_bs_enter(&r.bs, e.id);+ ok = read_strtab_block(&r);+ break;+ case IDENTIFICATION_BLOCK_ID:+ air_bs_enter(&r.bs, e.id);+ ok = read_identification_block(&r);+ break;+ default:+ ok = air_bs_skip_block(&r.bs); /* SYMTAB */+ break;+ }+ if (!ok)+ goto out;+ }+ if (!seen_module) {+ fail(&r, "no module block");+ goto out;+ }++ /* the string table comes after the module, so names come last */+ for (unsigned i = 0; i < m->num_globals; i++)+ if (!(m->globals[i]->base.name =+ strtab_name(&r, m->globals[i]->strtab_offset, m->globals[i]->strtab_size)))+ goto out;+ for (unsigned i = 0; i < m->num_functions; i++)+ if (!(m->functions[i]->base.name =+ strtab_name(&r, m->functions[i]->strtab_offset, m->functions[i]->strtab_size)))+ goto out;++out:+ if (m->error[0]) {+ if (error)+ *error = ralloc_strdup(mem_ctx, m->error);+ ralloc_free(m);+ return NULL;+ }+ if (error)+ *error = NULL;+ return m;+}++const struct air_function *+air_module_find_function(const struct air_module *m, const char *name)+{+ for (unsigned i = 0; i < m->num_functions; i++)+ if (m->functions[i]->base.name && !strcmp(m->functions[i]->base.name, name))+ return m->functions[i];+ return NULL;+}++const char *+air_md_string(const struct air_md *md)+{+ if (!md || md->kind != AIR_MD_STRING)+ return NULL;+ /* strings from METADATA_STRINGS point into the blob and are not terminated */+ return ralloc_strndup((void *)md, md->str, md->len);+}diff --git a/tools/mesa/air/air_module.h b/tools/mesa/air/air_module.hnew file mode 100644index 0000000..7ea7c95--- /dev/null+++ b/tools/mesa/air/air_module.h@@ -0,0 +1,372 @@+/*+ * Copyright © 2026 Darwin on redwood contributors+ * SPDX-License-Identifier: MIT+ */++/*+ * The part of LLVM IR that AIR uses, read from bitcode into plain C+ * structures. It is a reader, not an IR library: nothing here is modified+ * after reading, and only what the 456 modules of iOS 16.5's system+ * libraries contain (plus a little margin) is understood. Anything else is an+ * error that names the record, never a silent skip, because a skipped+ * instruction is a wrong shader.+ *+ * air_module_print() writes the module back as LLVM assembly. That output is+ * the reader's test: llvm-as must accept it, and after llvm-as | llvm-dis it+ * must equal what llvm-dis prints for the original bitcode.+ */++#ifndef AIR_MODULE_H+#define AIR_MODULE_H++#include <stdbool.h>+#include <stddef.h>+#include <stdint.h>+#include <stdio.h>++#ifdef __cplusplus+extern "C" {+#endif++enum air_type_kind {+ AIR_TYPE_VOID,+ AIR_TYPE_HALF,+ AIR_TYPE_BFLOAT,+ AIR_TYPE_FLOAT,+ AIR_TYPE_DOUBLE,+ AIR_TYPE_LABEL,+ AIR_TYPE_METADATA,+ AIR_TYPE_TOKEN,+ AIR_TYPE_INT,+ AIR_TYPE_POINTER,+ AIR_TYPE_ARRAY,+ AIR_TYPE_VECTOR,+ AIR_TYPE_STRUCT,+ AIR_TYPE_FUNCTION,+ AIR_TYPE_UNKNOWN, /* x86_fp80 and the like: legal bitcode, never AIR */+};++struct air_type {+ enum air_type_kind kind;+ unsigned id;+ unsigned bits; /* INT */+ unsigned addrspace; /* POINTER */+ const struct air_type *elem; /* POINTER (NULL: opaque), ARRAY, VECTOR; FUNCTION: return */+ uint64_t count; /* ARRAY, VECTOR */+ unsigned num_members; /* STRUCT members, FUNCTION parameters */+ const struct air_type **members;+ bool packed; /* STRUCT */+ bool opaque; /* STRUCT without a body */+ bool vararg; /* FUNCTION */+ const char *name; /* named STRUCT */+};++enum air_value_kind {+ AIR_VALUE_GLOBAL,+ AIR_VALUE_FUNCTION,+ AIR_VALUE_CONSTANT,+ AIR_VALUE_ARGUMENT,+ AIR_VALUE_INSTRUCTION,+ AIR_VALUE_METADATA, /* a metadata operand of a call (llvm.* intrinsics only) */+};++struct air_value {+ enum air_value_kind kind;+ const struct air_type *type;+ unsigned id; /* value number: module-wide for globals/constants, per function otherwise */+ const char *name; /* NULL when the module has none (stripped) */+};++enum air_const_kind {+ AIR_CONST_INT,+ AIR_CONST_FLOAT,+ AIR_CONST_NULL, /* zeroinitializer / null */+ AIR_CONST_UNDEF,+ AIR_CONST_POISON,+ AIR_CONST_AGGREGATE, /* struct, array or vector of other constants */+ AIR_CONST_DATA, /* array or vector of plain integers/floats, in .data */+ AIR_CONST_EXPR, /* a constant expression: .expr_op, .operands */+};++enum air_opcode {+ AIR_OP_RET,+ AIR_OP_BR,+ AIR_OP_SWITCH,+ AIR_OP_UNREACHABLE,+ AIR_OP_BINOP,+ AIR_OP_UNOP,+ AIR_OP_CAST,+ AIR_OP_GEP,+ AIR_OP_SELECT,+ AIR_OP_EXTRACTELT,+ AIR_OP_INSERTELT,+ AIR_OP_SHUFFLEVEC,+ AIR_OP_CMP,+ AIR_OP_PHI,+ AIR_OP_ALLOCA,+ AIR_OP_LOAD,+ AIR_OP_STORE,+ AIR_OP_CALL,+ AIR_OP_EXTRACTVAL,+ AIR_OP_INSERTVAL,+ AIR_OP_FREEZE,+ AIR_OP_FENCE,+ AIR_OP_ATOMICRMW,+ AIR_OP_CMPXCHG,+};++/* the bitcode's numbering, which is also the order of LLVM's own enums */+enum air_binop {+ AIR_BINOP_ADD, AIR_BINOP_SUB, AIR_BINOP_MUL, AIR_BINOP_UDIV, AIR_BINOP_SDIV,+ AIR_BINOP_UREM, AIR_BINOP_SREM, AIR_BINOP_SHL, AIR_BINOP_LSHR, AIR_BINOP_ASHR,+ AIR_BINOP_AND, AIR_BINOP_OR, AIR_BINOP_XOR,+};++enum air_cast {+ AIR_CAST_TRUNC, AIR_CAST_ZEXT, AIR_CAST_SEXT, AIR_CAST_FPTOUI, AIR_CAST_FPTOSI,+ AIR_CAST_UITOFP, AIR_CAST_SITOFP, AIR_CAST_FPTRUNC, AIR_CAST_FPEXT,+ AIR_CAST_PTRTOINT, AIR_CAST_INTTOPTR, AIR_CAST_BITCAST, AIR_CAST_ADDRSPACECAST,+};++enum air_pred {+ AIR_FCMP_FALSE = 0, AIR_FCMP_OEQ, AIR_FCMP_OGT, AIR_FCMP_OGE, AIR_FCMP_OLT,+ AIR_FCMP_OLE, AIR_FCMP_ONE, AIR_FCMP_ORD, AIR_FCMP_UNO, AIR_FCMP_UEQ,+ AIR_FCMP_UGT, AIR_FCMP_UGE, AIR_FCMP_ULT, AIR_FCMP_ULE, AIR_FCMP_UNE,+ AIR_FCMP_TRUE,+ AIR_ICMP_EQ = 32, AIR_ICMP_NE, AIR_ICMP_UGT, AIR_ICMP_UGE, AIR_ICMP_ULT,+ AIR_ICMP_ULE, AIR_ICMP_SGT, AIR_ICMP_SGE, AIR_ICMP_SLT, AIR_ICMP_SLE,+};++/* fast-math flags as the bitcode stores them */+#define AIR_FMF_UNSAFE_ALGEBRA (1u << 0) /* the old "fast": everything below */+#define AIR_FMF_NNAN (1u << 1)+#define AIR_FMF_NINF (1u << 2)+#define AIR_FMF_NSZ (1u << 3)+#define AIR_FMF_ARCP (1u << 4)+#define AIR_FMF_CONTRACT (1u << 5)+#define AIR_FMF_AFN (1u << 6)+#define AIR_FMF_REASSOC (1u << 7)++/* integer flags */+#define AIR_FLAG_NUW (1u << 0)+#define AIR_FLAG_NSW (1u << 1)+#define AIR_FLAG_EXACT (1u << 0)++struct air_block;+struct air_md;++struct air_constant {+ struct air_value base;+ enum air_const_kind ckind;+ uint64_t u; /* INT (two's complement, low bits), FLOAT (the bits) */+ unsigned num_elems;+ struct air_value **elems; /* AGGREGATE */+ uint64_t *data; /* DATA */+ /* EXPR */+ enum air_opcode expr_op; /* CAST, BINOP, GEP, CMP, SELECT, EXTRACTELT, ... */+ unsigned expr_sub; /* the cast/binop opcode or predicate */+ bool inbounds;+ const struct air_type *src_type; /* GEP source element type */+ unsigned num_operands;+ struct air_value **operands;+ /* while reading: value numbers not yet resolved */+ unsigned *pending;+};++struct air_global {+ struct air_value base; /* type: the pointer */+ const struct air_type *value_type;+ unsigned addrspace;+ bool is_const;+ bool externally_initialized;+ unsigned linkage;+ unsigned align;+ unsigned unnamed_addr; /* 0 none, 1 unnamed_addr, 2 local_unnamed_addr */+ const char *section;+ struct air_value *init; /* NULL for a declaration */+ unsigned init_id; /* while reading: value number + 1, 0 for none */+ uint64_t strtab_offset, strtab_size;+};++struct air_inst {+ struct air_value base; /* type: the result (void when none) */+ enum air_opcode op;+ unsigned sub; /* binop/cast/unop opcode, cmp predicate, rmw operation */+ unsigned flags; /* AIR_FLAG_*, AIR_FMF_* */+ unsigned align; /* bytes; 0 when not given */+ bool is_volatile;+ bool inbounds;+ bool tail;+ unsigned cc; /* call: LLVM's calling convention number */+ const struct air_type *aux_type; /* GEP source type, alloca's allocated type, call's function type */+ unsigned num_operands;+ struct air_value **operands; /* call: callee first, then the arguments */+ unsigned *operand_ids; /* while reading */+ unsigned num_indices;+ uint32_t *indices; /* extractvalue/insertvalue */+ unsigned num_targets;+ struct air_block **targets; /* br: dest, or then/else; phi: the incoming blocks */+ unsigned *target_ids; /* while reading */+ struct air_block *parent;+ unsigned num_attachments;+ struct { unsigned kind; struct air_md *md; } *attachments;+};++struct air_block {+ unsigned index;+ const char *name;+ unsigned num_insts, cap_insts;+ struct air_inst **insts;+};++struct air_function {+ struct air_value base; /* type: pointer to the function type */+ const struct air_type *fn_type;+ bool is_declaration;+ unsigned linkage;+ unsigned cc;+ unsigned unnamed_addr;+ unsigned align;+ const char *section;+ unsigned paramattr; /* index into the module's attribute lists, 0 for none */+ unsigned num_args;+ struct air_value *args;+ unsigned num_blocks;+ struct air_block *blocks;+ unsigned num_values; /* per-function value numbers in use, all kinds */+ uint64_t strtab_offset, strtab_size;+};++enum air_md_kind {+ AIR_MD_STRING,+ AIR_MD_VALUE,+ AIR_MD_NODE,+ AIR_MD_OTHER, /* debug info and other specialized nodes, kept only to keep the numbering */+};++struct air_md {+ enum air_md_kind kind;+ unsigned id;+ bool distinct;+ unsigned code; /* OTHER: the record code */+ const char *str; /* STRING (not NUL-safe: see len) */+ unsigned len;+ struct air_value *value; /* VALUE */+ unsigned num_ops;+ struct air_md **ops; /* NODE; NULL operands are null */+ unsigned *pending; /* while reading: md ids + 1 */+ unsigned value_id; /* while reading */+ const struct air_type *value_type;+ bool function_local;+};++struct air_named_md {+ const char *name;+ unsigned num_ops;+ struct air_md **ops;+};++struct air_module {+ void *mem_ctx;+ unsigned version; /* MODULE_CODE_VERSION: 2 = relative ids + strtab */+ const char *identification;+ const char *triple;+ const char *datalayout;+ const char *source_filename;++ unsigned num_types;+ struct air_type *types;++ unsigned num_globals;+ struct air_global **globals;+ unsigned num_functions;+ struct air_function **functions;++ unsigned num_module_values; /* globals + functions + module-level constants */+ struct air_value **module_values;++ unsigned num_md; /* module-level metadata */+ struct air_md **md;+ unsigned num_named_md;+ struct air_named_md *named_md;++ unsigned num_md_kinds;+ const char **md_kind_names; /* indexed by kind id; NULL where none */++ const char **section_names;+ unsigned num_section_names;++ /* first error, with the record that caused it */+ char error[256];+};++/* Reads one module. data may start with the 0x0B17C0DE wrapper or directly+ * with 'BC' 0xC0DE. Returns NULL and fills *error (when non-NULL, allocated+ * under mem_ctx) on failure.+ */+struct air_module *air_module_read(void *mem_ctx, const void *data, size_t size,+ const char **error);++void air_module_print(const struct air_module *m, FILE *fp);++/* helpers for the translator */+static inline const struct air_constant *+air_value_as_constant(const struct air_value *v)+{+ return v && v->kind == AIR_VALUE_CONSTANT ? (const struct air_constant *)v : NULL;+}++static inline const struct air_inst *+air_value_as_inst(const struct air_value *v)+{+ return v && v->kind == AIR_VALUE_INSTRUCTION ? (const struct air_inst *)v : NULL;+}++/* A constant integer, where zero may be stored as a null/zeroinitializer+ * rather than as an INTEGER record -- which is how LLVM writes the zero+ * indices of a getelementptr.+ */+static inline bool+air_const_uint(const struct air_value *v, uint64_t *out)+{+ const struct air_constant *c = air_value_as_constant(v);+ if (!c)+ return false;+ if (c->ckind == AIR_CONST_INT) {+ *out = c->u;+ return true;+ }+ if (c->ckind == AIR_CONST_NULL && v->type->kind == AIR_TYPE_INT) {+ *out = 0;+ return true;+ }+ return false;+}++static inline bool+air_type_is_float(const struct air_type *t)+{+ return t->kind == AIR_TYPE_HALF || t->kind == AIR_TYPE_BFLOAT ||+ t->kind == AIR_TYPE_FLOAT || t->kind == AIR_TYPE_DOUBLE;+}++/* the scalar of a vector, the type itself otherwise */+static inline const struct air_type *+air_type_scalar(const struct air_type *t)+{+ return t->kind == AIR_TYPE_VECTOR ? t->elem : t;+}++unsigned air_type_bit_size(const struct air_type *t); /* scalar bits: i1 -> 1, float -> 32, ptr -> 64 */+uint64_t air_type_alloc_size(const struct air_module *m, const struct air_type *t);+unsigned air_type_abi_align(const struct air_module *m, const struct air_type *t);+uint64_t air_struct_member_offset(const struct air_module *m, const struct air_type *t, unsigned i);++const struct air_function *air_module_find_function(const struct air_module *m, const char *name);+const char *air_md_string(const struct air_md *md); /* NUL-terminated copy, or NULL when not a string */++#ifdef __cplusplus+}+#endif++#endif /* AIR_MODULE_H */diff --git a/tools/mesa/air/air_print.c b/tools/mesa/air/air_print.cnew file mode 100644index 0000000..5654a10--- /dev/null+++ b/tools/mesa/air/air_print.c@@ -0,0 +1,898 @@+/*+ * Copyright © 2026 Darwin on redwood contributors+ * SPDX-License-Identifier: MIT+ */++/*+ * struct air_module -> LLVM assembly, in the syntax LLVM 22 reads (opaque+ * pointers). Attributes are not printed; everything else the reader keeps+ * is. The point is a test of the reader: llvm-as must accept the output,+ * and llvm-as | llvm-dis of it must equal llvm-dis of the original once+ * attributes are stripped from both (tools/air/reader-check.sh).+ */++#include "air_module.h"++#include <inttypes.h>+#include <string.h>++#include "util/hash_table.h"+#include "util/macros.h"+#include "util/ralloc.h"++struct printer {+ const struct air_module *m;+ FILE *fp;+ struct hash_table *md_numbers; /* air_md * -> number + 1 */+ unsigned num_md_numbers;+ struct air_md **md_order;+ unsigned cap_md_order;+ /* slots of the current function */+ struct hash_table *slots; /* air_value * or air_block * -> slot + 1 */+};++static void print_type(struct printer *p, const struct air_type *t);+static void print_value(struct printer *p, const struct air_value *v);++static bool+is_ident_char(char c)+{+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||+ c == '.' || c == '_' || c == '$' || c == '-';+}++static void+print_escaped(struct printer *p, const char *s, size_t len)+{+ for (size_t i = 0; i < len; i++) {+ unsigned char c = s[i];+ if (c >= 0x20 && c < 0x7f && c != '"' && c != '\\')+ fputc(c, p->fp);+ else+ fprintf(p->fp, "\\%02X", c);+ }+}++static void+print_name(struct printer *p, char sigil, const char *name)+{+ bool plain = name[0] != 0 && !(name[0] >= '0' && name[0] <= '9');+ for (const char *c = name; *c && plain; c++)+ plain = is_ident_char(*c);+ fputc(sigil, p->fp);+ if (plain) {+ fputs(name, p->fp);+ } else {+ fputc('"', p->fp);+ print_escaped(p, name, strlen(name));+ fputc('"', p->fp);+ }+}++static void+print_type(struct printer *p, const struct air_type *t)+{+ FILE *fp = p->fp;+ switch (t->kind) {+ case AIR_TYPE_VOID: fputs("void", fp); break;+ case AIR_TYPE_HALF: fputs("half", fp); break;+ case AIR_TYPE_BFLOAT: fputs("bfloat", fp); break;+ case AIR_TYPE_FLOAT: fputs("float", fp); break;+ case AIR_TYPE_DOUBLE: fputs("double", fp); break;+ case AIR_TYPE_LABEL: fputs("label", fp); break;+ case AIR_TYPE_METADATA: fputs("metadata", fp); break;+ case AIR_TYPE_TOKEN: fputs("token", fp); break;+ case AIR_TYPE_INT: fprintf(fp, "i%u", t->bits); break;+ case AIR_TYPE_POINTER:+ if (t->addrspace)+ fprintf(fp, "ptr addrspace(%u)", t->addrspace);+ else+ fputs("ptr", fp);+ break;+ case AIR_TYPE_ARRAY:+ fprintf(fp, "[%" PRIu64 " x ", t->count);+ print_type(p, t->elem);+ fputc(']', fp);+ break;+ case AIR_TYPE_VECTOR:+ fprintf(fp, "<%" PRIu64 " x ", t->count);+ print_type(p, t->elem);+ fputc('>', fp);+ break;+ case AIR_TYPE_STRUCT:+ if (t->name) {+ print_name(p, '%', t->name);+ break;+ }+ fputs(t->packed ? "<{ " : "{ ", fp);+ for (unsigned i = 0; i < t->num_members; i++) {+ if (i)+ fputs(", ", fp);+ print_type(p, t->members[i]);+ }+ fputs(t->num_members ? (t->packed ? " }>" : " }") : (t->packed ? "}>" : "}"), fp);+ break;+ case AIR_TYPE_FUNCTION:+ print_type(p, t->elem);+ fputs(" (", fp);+ for (unsigned i = 0; i < t->num_members; i++) {+ if (i)+ fputs(", ", fp);+ print_type(p, t->members[i]);+ }+ if (t->vararg)+ fputs(t->num_members ? ", ..." : "...", fp);+ fputc(')', fp);+ break;+ default:+ fputs("<unknown type>", fp);+ break;+ }+}++static void+print_float(struct printer *p, const struct air_type *t, uint64_t bits)+{+ switch (t->kind) {+ case AIR_TYPE_HALF:+ fprintf(p->fp, "0xH%04" PRIX64, bits & 0xffff);+ break;+ case AIR_TYPE_BFLOAT:+ fprintf(p->fp, "0xR%04" PRIX64, bits & 0xffff);+ break;+ case AIR_TYPE_FLOAT: {+ /* LLVM writes float constants as the double of the same value */+ uint32_t u = bits;+ float f;+ memcpy(&f, &u, 4);+ double d = f;+ uint64_t du;+ memcpy(&du, &d, 8);+ /* a NaN's payload must survive: shift it into the double's mantissa */+ if (f != f) {+ du = ((uint64_t)(u >> 31) << 63) | (0x7ffull << 52) | ((uint64_t)(u & 0x7fffff) << 29);+ }+ fprintf(p->fp, "0x%016" PRIX64, du);+ break;+ }+ default:+ fprintf(p->fp, "0x%016" PRIX64, bits);+ break;+ }+}++static void+print_int(struct printer *p, const struct air_type *t, uint64_t u)+{+ if (t->bits == 1) {+ fputs(u & 1 ? "true" : "false", p->fp);+ return;+ }+ int64_t s = t->bits >= 64 ? (int64_t)u : (int64_t)(u << (64 - t->bits)) >> (64 - t->bits);+ fprintf(p->fp, "%" PRId64, s);+}++static void print_constant(struct printer *p, const struct air_constant *c);++static void+print_typed(struct printer *p, const struct air_value *v)+{+ print_type(p, v->type);+ fputc(' ', p->fp);+ print_value(p, v);+}++static const struct air_type *+elem_type(const struct air_type *t, unsigned i)+{+ if (t->kind == AIR_TYPE_STRUCT)+ return t->members[i];+ return t->elem;+}++static void+print_constant(struct printer *p, const struct air_constant *c)+{+ FILE *fp = p->fp;+ const struct air_type *t = c->base.type;+ switch (c->ckind) {+ case AIR_CONST_INT:+ if (t->kind == AIR_TYPE_INT)+ print_int(p, t, c->u);+ else+ fputs("<int constant of a non-int type>", fp);+ break;+ case AIR_CONST_FLOAT:+ print_float(p, t, c->u);+ break;+ case AIR_CONST_NULL:+ /* a scalar zero prints as a zero of its type; only aggregates get+ * LLVM's zeroinitializer+ */+ if (t->kind == AIR_TYPE_POINTER)+ fputs("null", fp);+ else if (t->kind == AIR_TYPE_INT)+ print_int(p, t, 0);+ else if (air_type_is_float(t))+ print_float(p, t, 0);+ else+ fputs("zeroinitializer", fp);+ break;+ case AIR_CONST_UNDEF:+ fputs("undef", fp);+ break;+ case AIR_CONST_POISON:+ fputs("poison", fp);+ break;+ case AIR_CONST_AGGREGATE:+ case AIR_CONST_DATA: {+ const char *open = t->kind == AIR_TYPE_ARRAY ? "[" : t->kind == AIR_TYPE_VECTOR ? "<" :+ t->packed ? "<{ " : "{ ";+ const char *close = t->kind == AIR_TYPE_ARRAY ? "]" : t->kind == AIR_TYPE_VECTOR ? ">" :+ t->packed ? " }>" : " }";+ fputs(open, fp);+ for (unsigned i = 0; i < c->num_elems; i++) {+ if (i)+ fputs(", ", fp);+ if (c->ckind == AIR_CONST_AGGREGATE) {+ print_typed(p, c->elems[i]);+ } else {+ const struct air_type *et = elem_type(t, i);+ print_type(p, et);+ fputc(' ', fp);+ if (air_type_is_float(et))+ print_float(p, et, c->data[i]);+ else+ print_int(p, et, c->data[i]);+ }+ }+ fputs(close, fp);+ break;+ }+ case AIR_CONST_EXPR:+ switch (c->expr_op) {+ case AIR_OP_CAST: {+ static const char *names[] = {+ "trunc", "zext", "sext", "fptoui", "fptosi", "uitofp", "sitofp", "fptrunc",+ "fpext", "ptrtoint", "inttoptr", "bitcast", "addrspacecast",+ };+ const struct air_value *op = c->operands[0];+ /* with opaque pointers a pointer-to-pointer bitcast is nothing */+ if (c->expr_sub == AIR_CAST_BITCAST && t->kind == AIR_TYPE_POINTER &&+ op->type->kind == AIR_TYPE_POINTER && op->type->addrspace == t->addrspace) {+ print_value(p, op);+ break;+ }+ fprintf(fp, "%s (", c->expr_sub < ARRAY_SIZE(names) ? names[c->expr_sub] : "?cast");+ print_typed(p, op);+ fputs(" to ", fp);+ print_type(p, t);+ fputc(')', fp);+ break;+ }+ case AIR_OP_GEP:+ fprintf(fp, "getelementptr %s(", c->inbounds ? "inbounds " : "");+ print_type(p, c->src_type);+ for (unsigned i = 0; i < c->num_operands; i++) {+ fputs(", ", fp);+ print_typed(p, c->operands[i]);+ }+ fputc(')', fp);+ break;+ default:+ fprintf(fp, "<constant expression %u>", c->expr_op);+ break;+ }+ break;+ }+}++static void+print_value(struct printer *p, const struct air_value *v)+{+ switch (v->kind) {+ case AIR_VALUE_GLOBAL:+ case AIR_VALUE_FUNCTION:+ print_name(p, '@', v->name ? v->name : "?");+ return;+ case AIR_VALUE_CONSTANT:+ print_constant(p, (const struct air_constant *)v);+ return;+ case AIR_VALUE_METADATA:+ fputs("!{}", p->fp); /* not in AIR; kept printable */+ return;+ default: {+ if (v->name) {+ print_name(p, '%', v->name);+ return;+ }+ struct hash_entry *e = _mesa_hash_table_search(p->slots, v);+ if (e)+ fprintf(p->fp, "%%%u", (unsigned)((uintptr_t)e->data - 1));+ else+ fputs("%<no slot>", p->fp);+ return;+ }+ }+}++/* -- metadata ----------------------------------------------------------- */++static void+number_md(struct printer *p, struct air_md *md)+{+ if (!md || md->kind != AIR_MD_NODE)+ return;+ if (_mesa_hash_table_search(p->md_numbers, md))+ return;+ _mesa_hash_table_insert(p->md_numbers, md, (void *)(uintptr_t)(++p->num_md_numbers));+ if (p->num_md_numbers > p->cap_md_order) {+ p->cap_md_order = MAX2(64, p->cap_md_order * 2);+ p->md_order = reralloc(NULL, p->md_order, struct air_md *, p->cap_md_order);+ }+ p->md_order[p->num_md_numbers - 1] = md;+ for (unsigned i = 0; i < md->num_ops; i++)+ number_md(p, md->ops[i]);+}++static void+print_md_ref(struct printer *p, const struct air_md *md)+{+ if (!md) {+ fputs("null", p->fp);+ return;+ }+ switch (md->kind) {+ case AIR_MD_STRING:+ fputs("!\"", p->fp);+ print_escaped(p, md->str, md->len);+ fputc('"', p->fp);+ break;+ case AIR_MD_VALUE:+ print_typed(p, md->value);+ break;+ case AIR_MD_NODE: {+ struct hash_entry *e = _mesa_hash_table_search(p->md_numbers, md);+ fprintf(p->fp, "!%u", e ? (unsigned)((uintptr_t)e->data - 1) : ~0u);+ break;+ }+ default:+ fputs("!{}", p->fp);+ break;+ }+}++static void+print_md_node(struct printer *p, const struct air_md *md)+{+ fputs(md->distinct ? "distinct !{" : "!{", p->fp);+ for (unsigned i = 0; i < md->num_ops; i++) {+ if (i)+ fputs(", ", p->fp);+ print_md_ref(p, md->ops[i]);+ }+ fputc('}', p->fp);+}++/* -- instructions ------------------------------------------------------- */++static void+print_fmf(struct printer *p, unsigned f)+{+ if ((f & AIR_FMF_UNSAFE_ALGEBRA) ||+ (f & 0xfe) == 0xfe) {+ fputs("fast ", p->fp);+ return;+ }+ static const struct { unsigned bit; const char *name; } flags[] = {+ { AIR_FMF_REASSOC, "reassoc" }, { AIR_FMF_NNAN, "nnan" }, { AIR_FMF_NINF, "ninf" },+ { AIR_FMF_NSZ, "nsz" }, { AIR_FMF_ARCP, "arcp" }, { AIR_FMF_CONTRACT, "contract" },+ { AIR_FMF_AFN, "afn" },+ };+ for (unsigned i = 0; i < ARRAY_SIZE(flags); i++)+ if (f & flags[i].bit)+ fprintf(p->fp, "%s ", flags[i].name);+}++/* "label %x" after a branch, a bare "%x" inside a phi */+static void+print_block_ref_as(struct printer *p, const struct air_block *b, bool with_label)+{+ if (with_label)+ fputs("label ", p->fp);+ if (b->name) {+ print_name(p, '%', b->name);+ return;+ }+ struct hash_entry *e = _mesa_hash_table_search(p->slots, b);+ fprintf(p->fp, "%%%u", e ? (unsigned)((uintptr_t)e->data - 1) : ~0u);+}++static void+print_block_ref(struct printer *p, const struct air_block *b)+{+ print_block_ref_as(p, b, true);+}++static void+print_inst(struct printer *p, const struct air_inst *in)+{+ FILE *fp = p->fp;+ const struct air_type *t = in->base.type;+ fputs(" ", fp);+ if (t && t->kind != AIR_TYPE_VOID) {+ print_value(p, &in->base);+ fputs(" = ", fp);+ }++ switch (in->op) {+ case AIR_OP_BINOP: {+ static const char *iname[] = { "add", "sub", "mul", "udiv", "sdiv", "urem", "srem",+ "shl", "lshr", "ashr", "and", "or", "xor" };+ bool fp_op = air_type_is_float(air_type_scalar(t));+ const char *name = in->sub < ARRAY_SIZE(iname) ? iname[in->sub] : "?binop";+ if (fp_op) {+ static const char *fname[] = { "fadd", "fsub", "fmul", NULL, "fdiv", NULL, "frem" };+ name = in->sub < ARRAY_SIZE(fname) && fname[in->sub] ? fname[in->sub] : "?fbinop";+ }+ fprintf(fp, "%s ", name);+ if (fp_op) {+ print_fmf(p, in->flags);+ } else if (in->sub == AIR_BINOP_ADD || in->sub == AIR_BINOP_SUB ||+ in->sub == AIR_BINOP_MUL || in->sub == AIR_BINOP_SHL) {+ if (in->flags & AIR_FLAG_NUW)+ fputs("nuw ", fp);+ if (in->flags & AIR_FLAG_NSW)+ fputs("nsw ", fp);+ } else if (in->sub == AIR_BINOP_UDIV || in->sub == AIR_BINOP_SDIV ||+ in->sub == AIR_BINOP_LSHR || in->sub == AIR_BINOP_ASHR) {+ if (in->flags & AIR_FLAG_EXACT)+ fputs("exact ", fp);+ } else if (in->sub == AIR_BINOP_OR && (in->flags & 1)) {+ fputs("disjoint ", fp);+ }+ print_typed(p, in->operands[0]);+ fputs(", ", fp);+ print_value(p, in->operands[1]);+ break;+ }+ case AIR_OP_UNOP:+ fputs("fneg ", fp);+ print_fmf(p, in->flags);+ print_typed(p, in->operands[0]);+ break;+ case AIR_OP_CAST: {+ static const char *names[] = {+ "trunc", "zext", "sext", "fptoui", "fptosi", "uitofp", "sitofp", "fptrunc",+ "fpext", "ptrtoint", "inttoptr", "bitcast", "addrspacecast",+ };+ fprintf(fp, "%s ", in->sub < ARRAY_SIZE(names) ? names[in->sub] : "?cast");+ if (in->sub == AIR_CAST_ZEXT && (in->flags & 1))+ fputs("nneg ", fp);+ print_typed(p, in->operands[0]);+ fputs(" to ", fp);+ print_type(p, t);+ break;+ }+ case AIR_OP_GEP:+ fprintf(fp, "getelementptr %s", in->inbounds ? "inbounds " : "");+ print_type(p, in->aux_type);+ for (unsigned i = 0; i < in->num_operands; i++) {+ fputs(", ", fp);+ print_typed(p, in->operands[i]);+ }+ break;+ case AIR_OP_SELECT:+ fputs("select ", fp);+ print_fmf(p, in->flags);+ print_typed(p, in->operands[0]);+ fputs(", ", fp);+ print_typed(p, in->operands[1]);+ fputs(", ", fp);+ print_typed(p, in->operands[2]);+ break;+ case AIR_OP_EXTRACTELT:+ fputs("extractelement ", fp);+ print_typed(p, in->operands[0]);+ fputs(", ", fp);+ print_typed(p, in->operands[1]);+ break;+ case AIR_OP_INSERTELT:+ fputs("insertelement ", fp);+ for (unsigned i = 0; i < 3; i++) {+ if (i)+ fputs(", ", fp);+ print_typed(p, in->operands[i]);+ }+ break;+ case AIR_OP_SHUFFLEVEC:+ fputs("shufflevector ", fp);+ for (unsigned i = 0; i < 3; i++) {+ if (i)+ fputs(", ", fp);+ print_typed(p, in->operands[i]);+ }+ break;+ case AIR_OP_CMP: {+ static const char *fpred[] = { "false", "oeq", "ogt", "oge", "olt", "ole", "one", "ord",+ "uno", "ueq", "ugt", "uge", "ult", "ule", "une", "true" };+ static const char *ipred[] = { "eq", "ne", "ugt", "uge", "ult", "ule", "sgt", "sge",+ "slt", "sle" };+ if (in->sub < 16) {+ fprintf(fp, "fcmp ");+ print_fmf(p, in->flags);+ fprintf(fp, "%s ", fpred[in->sub]);+ } else if (in->sub >= 32 && in->sub < 42) {+ fprintf(fp, "icmp %s ", ipred[in->sub - 32]);+ } else {+ fprintf(fp, "?cmp%u ", in->sub);+ }+ print_typed(p, in->operands[0]);+ fputs(", ", fp);+ print_value(p, in->operands[1]);+ break;+ }+ case AIR_OP_PHI:+ fputs("phi ", fp);+ if (air_type_is_float(air_type_scalar(t)))+ print_fmf(p, in->flags);+ print_type(p, t);+ for (unsigned i = 0; i < in->num_operands; i++) {+ fputs(i ? ", [ " : " [ ", fp);+ print_value(p, in->operands[i]);+ fputs(", ", fp);+ print_block_ref_as(p, in->targets[i], false);+ fputs(" ]", fp);+ }+ break;+ case AIR_OP_ALLOCA: {+ fputs("alloca ", fp);+ print_type(p, in->aux_type);+ const struct air_constant *n = air_value_as_constant(in->operands[0]);+ if (!n || n->ckind != AIR_CONST_INT || n->u != 1) {+ fputs(", ", fp);+ print_typed(p, in->operands[0]);+ }+ if (in->align)+ fprintf(fp, ", align %u", in->align);+ if (t->addrspace)+ fprintf(fp, ", addrspace(%u)", t->addrspace);+ break;+ }+ case AIR_OP_LOAD:+ fprintf(fp, "load %s", in->is_volatile ? "volatile " : "");+ print_type(p, t);+ fputs(", ", fp);+ print_typed(p, in->operands[0]);+ if (in->align)+ fprintf(fp, ", align %u", in->align);+ break;+ case AIR_OP_STORE:+ fprintf(fp, "store %s", in->is_volatile ? "volatile " : "");+ print_typed(p, in->operands[0]);+ fputs(", ", fp);+ print_typed(p, in->operands[1]);+ if (in->align)+ fprintf(fp, ", align %u", in->align);+ break;+ case AIR_OP_CALL: {+ fputs(in->tail ? "tail call " : "call ", fp);+ print_fmf(p, in->flags);+ /* LLVM's CallingConv::ID, of which AIR uses only C and fastcc */+ if (in->cc == 8)+ fputs("fastcc ", fp);+ else if (in->cc)+ fprintf(fp, "cc%u ", in->cc);+ const struct air_type *fty = in->aux_type;+ if (fty->vararg)+ print_type(p, fty);+ else+ print_type(p, fty->elem);+ fputc(' ', fp);+ print_value(p, in->operands[0]);+ fputc('(', fp);+ for (unsigned i = 1; i < in->num_operands; i++) {+ if (i > 1)+ fputs(", ", fp);+ print_typed(p, in->operands[i]);+ }+ fputc(')', fp);+ break;+ }+ case AIR_OP_EXTRACTVAL:+ fputs("extractvalue ", fp);+ print_typed(p, in->operands[0]);+ for (unsigned i = 0; i < in->num_indices; i++)+ fprintf(fp, ", %u", in->indices[i]);+ break;+ case AIR_OP_INSERTVAL:+ fputs("insertvalue ", fp);+ print_typed(p, in->operands[0]);+ fputs(", ", fp);+ print_typed(p, in->operands[1]);+ for (unsigned i = 0; i < in->num_indices; i++)+ fprintf(fp, ", %u", in->indices[i]);+ break;+ case AIR_OP_FREEZE:+ fputs("freeze ", fp);+ print_typed(p, in->operands[0]);+ break;+ case AIR_OP_RET:+ if (in->num_operands) {+ fputs("ret ", fp);+ print_typed(p, in->operands[0]);+ } else {+ fputs("ret void", fp);+ }+ break;+ case AIR_OP_BR:+ fputs("br ", fp);+ if (in->num_targets == 1) {+ print_block_ref(p, in->targets[0]);+ } else {+ print_typed(p, in->operands[0]);+ fputs(", ", fp);+ print_block_ref(p, in->targets[0]);+ fputs(", ", fp);+ print_block_ref(p, in->targets[1]);+ }+ break;+ case AIR_OP_UNREACHABLE:+ fputs("unreachable", fp);+ break;+ default:+ fprintf(fp, "<opcode %u>", in->op);+ break;+ }++ for (unsigned i = 0; i < in->num_attachments; i++) {+ unsigned k = in->attachments[i].kind;+ const char *kind = k < p->m->num_md_kinds && p->m->md_kind_names[k] ? p->m->md_kind_names[k] : "?";+ fputs(", ", fp);+ print_name(p, '!', kind);+ fputc(' ', fp);+ print_md_ref(p, in->attachments[i].md);+ }+ fputc('\n', fp);+}++static const char *+linkage_name(unsigned l)+{+ switch (l) {+ case 0: case 5: case 6: case 15: return "";+ case 2: return "appending ";+ case 3: return "internal ";+ case 7: return "extern_weak ";+ case 8: return "common ";+ case 9: case 13: case 14: return "private ";+ case 12: return "available_externally ";+ case 1: case 16: return "weak ";+ case 10: case 17: return "weak_odr ";+ case 4: case 18: return "linkonce ";+ case 11: case 19: return "linkonce_odr ";+ default: return "?linkage ";+ }+}++static const char *+cc_name(unsigned cc)+{+ /* LLVM's CallingConv::ID; AIR uses only C (0) and fastcc (8) */+ switch (cc) {+ case 0: return "";+ case 8: return "fastcc ";+ case 9: return "coldcc ";+ default: return NULL;+ }+}++static const char *+unnamed_addr_name(unsigned u)+{+ return u == 1 ? "unnamed_addr " : u == 2 ? "local_unnamed_addr " : "";+}++static void+print_function(struct printer *p, const struct air_function *f)+{+ FILE *fp = p->fp;+ const struct air_type *fty = f->fn_type;++ if (f->is_declaration) {+ fprintf(fp, "declare %s", f->linkage == 7 ? "extern_weak " : "");+ if (cc_name(f->cc))+ fputs(cc_name(f->cc), fp);+ else+ fprintf(fp, "cc%u ", f->cc);+ print_type(p, fty->elem);+ fputc(' ', fp);+ print_name(p, '@', f->base.name);+ fputc('(', fp);+ for (unsigned i = 0; i < fty->num_members; i++) {+ if (i)+ fputs(", ", fp);+ print_type(p, fty->members[i]);+ }+ if (fty->vararg)+ fputs(fty->num_members ? ", ..." : "...", fp);+ fputc(')', fp);+ if (f->unnamed_addr)+ fprintf(fp, " %s", f->unnamed_addr == 1 ? "unnamed_addr" : "local_unnamed_addr");+ if (f->align)+ fprintf(fp, " align %u", f->align);+ fputs("\n\n", fp);+ return;+ }++ p->slots = _mesa_pointer_hash_table_create(NULL);+ unsigned slot = 0;+ for (unsigned i = 0; i < f->num_args; i++)+ if (!f->args[i].name)+ _mesa_hash_table_insert(p->slots, &f->args[i], (void *)(uintptr_t)(++slot));+ for (unsigned b = 0; b < f->num_blocks; b++) {+ const struct air_block *blk = &f->blocks[b];+ if (!blk->name)+ _mesa_hash_table_insert(p->slots, blk, (void *)(uintptr_t)(++slot));+ for (unsigned i = 0; i < blk->num_insts; i++) {+ const struct air_inst *in = blk->insts[i];+ if (in->base.type && in->base.type->kind != AIR_TYPE_VOID && !in->base.name)+ _mesa_hash_table_insert(p->slots, in, (void *)(uintptr_t)(++slot));+ }+ }++ fprintf(fp, "define %s", linkage_name(f->linkage));+ if (cc_name(f->cc))+ fputs(cc_name(f->cc), fp);+ else+ fprintf(fp, "cc%u ", f->cc);+ print_type(p, fty->elem);+ fputc(' ', fp);+ print_name(p, '@', f->base.name);+ fputc('(', fp);+ for (unsigned i = 0; i < f->num_args; i++) {+ if (i)+ fputs(", ", fp);+ print_typed(p, &f->args[i]);+ }+ fputc(')', fp);+ /* after the argument list, where the syntax puts it */+ if (f->unnamed_addr)+ fprintf(fp, " %s", f->unnamed_addr == 1 ? "unnamed_addr" : "local_unnamed_addr");+ if (f->align)+ fprintf(fp, " align %u", f->align);+ if (f->section) {+ fputs(" section \"", fp);+ print_escaped(p, f->section, strlen(f->section));+ fputc('"', fp);+ }+ fputs(" {\n", fp);+ for (unsigned b = 0; b < f->num_blocks; b++) {+ const struct air_block *blk = &f->blocks[b];+ if (b > 0 || blk->name) {+ if (b > 0)+ fputc('\n', fp);+ if (blk->name) {+ /* a label is a name without its sigil */+ print_name(p, '%', blk->name);+ fputs(":\n", fp);+ } else {+ struct hash_entry *e = _mesa_hash_table_search(p->slots, blk);+ fprintf(fp, "%u:\n", (unsigned)((uintptr_t)e->data - 1));+ }+ }+ for (unsigned i = 0; i < blk->num_insts; i++)+ print_inst(p, blk->insts[i]);+ }+ fputs("}\n\n", fp);+ _mesa_hash_table_destroy(p->slots, NULL);+ p->slots = NULL;+}++void+air_module_print(const struct air_module *m, FILE *fp)+{+ struct printer p = {+ .m = m,+ .fp = fp,+ .md_numbers = _mesa_pointer_hash_table_create(NULL),+ };++ if (m->source_filename) {+ fputs("source_filename = \"", fp);+ print_escaped(&p, m->source_filename, strlen(m->source_filename));+ fputs("\"\n", fp);+ }+ if (m->datalayout)+ fprintf(fp, "target datalayout = \"%s\"\n", m->datalayout);+ if (m->triple)+ fprintf(fp, "target triple = \"%s\"\n", m->triple);+ fputc('\n', fp);++ for (unsigned i = 0; i < m->num_types; i++) {+ const struct air_type *t = &m->types[i];+ if (t->kind != AIR_TYPE_STRUCT || !t->name)+ continue;+ print_name(&p, '%', t->name);+ fputs(" = type ", fp);+ if (t->opaque) {+ fputs("opaque\n", fp);+ continue;+ }+ struct air_type anon = *t;+ anon.name = NULL;+ print_type(&p, &anon);+ fputc('\n', fp);+ }+ fputc('\n', fp);++ /* metadata numbers: the module's first, then what instructions attach */+ for (unsigned i = 0; i < m->num_named_md; i++)+ for (unsigned k = 0; k < m->named_md[i].num_ops; k++)+ number_md(&p, m->named_md[i].ops[k]);+ for (unsigned i = 0; i < m->num_md; i++)+ number_md(&p, m->md[i]);+ for (unsigned f = 0; f < m->num_functions; f++) {+ const struct air_function *fn = m->functions[f];+ for (unsigned b = 0; b < fn->num_blocks; b++)+ for (unsigned i = 0; i < fn->blocks[b].num_insts; i++) {+ const struct air_inst *in = fn->blocks[b].insts[i];+ for (unsigned a = 0; a < in->num_attachments; a++)+ number_md(&p, in->attachments[a].md);+ }+ }++ for (unsigned i = 0; i < m->num_globals; i++) {+ const struct air_global *g = m->globals[i];+ print_name(&p, '@', g->base.name);+ fputs(" = ", fp);+ if (!g->init && (g->linkage == 0 || g->linkage == 5 || g->linkage == 6 || g->linkage == 15))+ fputs("external ", fp);+ else+ fputs(linkage_name(g->linkage), fp);+ fputs(unnamed_addr_name(g->unnamed_addr), fp);+ if (g->addrspace)+ fprintf(fp, "addrspace(%u) ", g->addrspace);+ if (g->externally_initialized)+ fputs("externally_initialized ", fp);+ fputs(g->is_const ? "constant " : "global ", fp);+ print_type(&p, g->value_type);+ if (g->init) {+ fputc(' ', fp);+ print_value(&p, g->init);+ }+ if (g->section) {+ fputs(", section \"", fp);+ print_escaped(&p, g->section, strlen(g->section));+ fputc('"', fp);+ }+ if (g->align)+ fprintf(fp, ", align %u", g->align);+ fputc('\n', fp);+ }+ fputc('\n', fp);++ for (unsigned i = 0; i < m->num_functions; i++)+ print_function(&p, m->functions[i]);++ for (unsigned i = 0; i < m->num_named_md; i++) {+ const struct air_named_md *n = &m->named_md[i];+ print_name(&p, '!', n->name);+ fputs(" = !{", fp);+ for (unsigned k = 0; k < n->num_ops; k++) {+ if (k)+ fputs(", ", fp);+ print_md_ref(&p, n->ops[k]);+ }+ fputs("}\n", fp);+ }+ fputc('\n', fp);+ for (unsigned i = 0; i < p.num_md_numbers; i++) {+ fprintf(fp, "!%u = ", i);+ print_md_node(&p, p.md_order[i]);+ fputc('\n', fp);+ }++ _mesa_hash_table_destroy(p.md_numbers, NULL);+ ralloc_free(p.md_order);+}diff --git a/tools/mesa/air/air_private.h b/tools/mesa/air/air_private.hnew file mode 100644index 0000000..a1bacbb--- /dev/null+++ b/tools/mesa/air/air_private.h@@ -0,0 +1,120 @@+/*+ * Copyright © 2026 Darwin on redwood contributors+ * SPDX-License-Identifier: MIT+ */++/* Shared between air_to_nir.c and air_intrinsics.c. */++#ifndef AIR_PRIVATE_H+#define AIR_PRIVATE_H++#include "air_module.h"+#include "nir_air.h"++#include "nir.h"+#include "nir_builder.h"++/* Where a pointer points. AIR's address spaces say which kind of memory;+ * which buffer, and the byte offset into it, the translator tracks itself+ * (docs/air.md section 3): no pointer in the corpus is ever stored to+ * memory or cast to an integer, so a pointer never has to become a number.+ */+enum air_ptr_class {+ AIR_PTR_NONE,+ AIR_PTR_UBO, /* a constant buffer: .binding is its index */+ AIR_PTR_SSBO, /* a device buffer */+ AIR_PTR_SHARED, /* threadgroup memory */+ AIR_PTR_SCRATCH, /* an alloca, or a program-scope variable */+ AIR_PTR_CONSTANT_DATA, /* a constant global: nir->constant_data */+ AIR_PTR_FUNCTION_CONSTANT, /* a function constant: .binding is its index */+ AIR_PTR_TEXTURE, /* a texture handle; offset unused */+ AIR_PTR_SAMPLER, /* a sampler handle */+};++struct air_ptr {+ enum air_ptr_class class;+ unsigned binding;+ nir_def *offset; /* bytes, 32-bit; NULL means zero */+ const struct air_type *pointee; /* for sizes, and for loads without a type */+};++enum air_val_kind {+ AIR_VAL_NONE,+ AIR_VAL_SSA, /* a scalar or vector */+ AIR_VAL_AGG, /* a struct or array, as a tree of values */+ AIR_VAL_PTR,+};++struct air_val {+ enum air_val_kind kind;+ nir_def *def;+ struct air_ptr ptr;+ unsigned num_elems;+ struct air_val **elems;+};++struct air_ctx {+ void *mem_ctx;+ const struct air_module *m;+ const struct air_function *fn;+ nir_shader *nir;+ nir_builder b;++ const struct air_to_nir_options *options;+ struct air_shader_info *info;++ /* translated values, keyed on const struct air_value * */+ struct hash_table *values;+ /* air_block * -> nir_block * */+ struct hash_table *blocks;+ /* a cursor in each block, before its terminator, where phi stores go */+ struct hash_table *phi_cursors;+ /* phi -> nir register decl */+ struct hash_table *phi_regs;++ /* what the entry point's parameters are */+ unsigned num_params;+ struct air_val **params;++ /* outputs, in the order of the returned struct's fields */+ unsigned num_outputs;+ struct {+ unsigned location; /* gl_varying_slot or gl_frag_result */+ unsigned index; /* dual-source index */+ nir_variable *var;+ } *outputs;++ unsigned scratch_size;+ unsigned shared_size;++ /* module-scope variables, by their air_global */+ struct hash_table *globals;++ char error[256];+};++bool air_error(struct air_ctx *c, const char *fmt, ...) PRINTFLIKE(2, 3);++/* value bookkeeping */+struct air_val *air_val_ssa(struct air_ctx *c, nir_def *def);+struct air_val *air_val_ptr(struct air_ctx *c, struct air_ptr ptr);+struct air_val *air_get(struct air_ctx *c, const struct air_value *v);+void air_set(struct air_ctx *c, const struct air_value *v, struct air_val *val);++/* an SSA value, with aggregates and pointers refused */+nir_def *air_get_ssa(struct air_ctx *c, const struct air_value *v);++/* the NIR type of an AIR type: bit size and components */+unsigned air_nir_bit_size(struct air_ctx *c, const struct air_type *t);+unsigned air_nir_components(const struct air_type *t);++/* memory, by the pointer's class */+nir_def *air_load_ptr(struct air_ctx *c, struct air_ptr ptr, const struct air_type *type,+ unsigned align);+bool air_store_ptr(struct air_ctx *c, struct air_ptr ptr, nir_def *value, unsigned align);+struct air_ptr air_ptr_add(struct air_ctx *c, struct air_ptr ptr, nir_def *bytes);++/* air.* and llvm.* calls; the result is set on the instruction by the callee */+bool air_translate_call(struct air_ctx *c, const struct air_inst *in, const char *name);++#endif /* AIR_PRIVATE_H */diff --git a/tools/mesa/air/air_to_nir.c b/tools/mesa/air/air_to_nir.cnew file mode 100644index 0000000..9af2156--- /dev/null+++ b/tools/mesa/air/air_to_nir.c@@ -0,0 +1,1722 @@+/*+ * Copyright © 2026 Darwin on redwood contributors+ * SPDX-License-Identifier: MIT+ */++/*+ * One AIR module -> one nir_shader. The mapping from AIR's named metadata to+ * NIR's variables, bindings and system values is the table in docs/air.md+ * section 3.1; this file is that table in code, and nothing here decides+ * anything the table does not state.+ */++#include "air_private.h"++#include <stdarg.h>+#include <stdio.h>+#include <string.h>++#include "util/hash_table.h"+#include "util/u_math.h"++bool+air_error(struct air_ctx *c, const char *fmt, ...)+{+ if (!c->error[0]) {+ va_list ap;+ va_start(ap, fmt);+ vsnprintf(c->error, sizeof(c->error), fmt, ap);+ va_end(ap);+ }+ return false;+}++/* -- values ------------------------------------------------------------- */++struct air_val *+air_val_ssa(struct air_ctx *c, nir_def *def)+{+ struct air_val *v = rzalloc(c->mem_ctx, struct air_val);+ v->kind = AIR_VAL_SSA;+ v->def = def;+ return v;+}++struct air_val *+air_val_ptr(struct air_ctx *c, struct air_ptr ptr)+{+ struct air_val *v = rzalloc(c->mem_ctx, struct air_val);+ v->kind = AIR_VAL_PTR;+ v->ptr = ptr;+ return v;+}++static struct air_val *+air_val_agg(struct air_ctx *c, unsigned n)+{+ struct air_val *v = rzalloc(c->mem_ctx, struct air_val);+ v->kind = AIR_VAL_AGG;+ v->num_elems = n;+ v->elems = rzalloc_array(c->mem_ctx, struct air_val *, MAX2(n, 1));+ return v;+}++void+air_set(struct air_ctx *c, const struct air_value *v, struct air_val *val)+{+ _mesa_hash_table_insert(c->values, v, val);+}++unsigned+air_nir_bit_size(struct air_ctx *c, const struct air_type *t)+{+ unsigned bits = air_type_bit_size(air_type_scalar(t));+ /* NIR has no i1 in SSA: booleans are 1-bit defs, which it does have */+ return bits;+}++unsigned+air_nir_components(const struct air_type *t)+{+ return t->kind == AIR_TYPE_VECTOR ? t->count : 1;+}++static struct air_val *air_constant_val(struct air_ctx *c, const struct air_constant *k);++struct air_val *+air_get(struct air_ctx *c, const struct air_value *v)+{+ struct hash_entry *e = _mesa_hash_table_search(c->values, v);+ if (e)+ return e->data;+ const struct air_constant *k = air_value_as_constant(v);+ if (k) {+ struct air_val *val = air_constant_val(c, k);+ if (val)+ air_set(c, v, val);+ return val;+ }+ air_error(c, "instruction: a %s value used before it is defined%s%s",+ v->kind == AIR_VALUE_GLOBAL ? "global" :+ v->kind == AIR_VALUE_FUNCTION ? "function" :+ v->kind == AIR_VALUE_ARGUMENT ? "argument" :+ v->kind == AIR_VALUE_INSTRUCTION ? "computed" : "metadata",+ v->name ? " " : "", v->name ? v->name : "");+ return NULL;+}++nir_def *+air_get_ssa(struct air_ctx *c, const struct air_value *v)+{+ struct air_val *val = air_get(c, v);+ if (!val)+ return NULL;+ if (val->kind != AIR_VAL_SSA) {+ air_error(c, "instruction: %s where a number belongs",+ val->kind == AIR_VAL_PTR ? "a pointer" : "an aggregate");+ return NULL;+ }+ return val->def;+}++/* -- constants ---------------------------------------------------------- */++static nir_def *+scalar_constant(struct air_ctx *c, const struct air_type *t, uint64_t bits)+{+ unsigned n = air_type_bit_size(t);+ if (t->kind == AIR_TYPE_INT && t->bits == 1)+ return nir_imm_bool(&c->b, bits & 1);+ if (air_type_is_float(t)) {+ switch (n) {+ case 16: return nir_imm_intN_t(&c->b, bits, 16);+ case 32: return nir_imm_int(&c->b, (uint32_t)bits);+ case 64: return nir_imm_int64(&c->b, bits);+ default: break;+ }+ }+ return nir_imm_intN_t(&c->b, bits, MAX2(n, 1));+}++/* The float bits of a constant have to come through unchanged: a float+ * constant is built as an integer of the same bits and reinterpreted, so+ * that no NaN payload or denormal is rewritten on the way.+ */+static nir_def *+reinterpret_float(struct air_ctx *c, const struct air_type *t, nir_def *bits)+{+ if (!air_type_is_float(t))+ return bits;+ return nir_mov(&c->b, bits); /* same bits, and NIR tracks the type by use */+}++static struct air_val *+air_constant_val(struct air_ctx *c, const struct air_constant *k)+{+ const struct air_type *t = k->base.type;++ switch (k->ckind) {+ case AIR_CONST_INT:+ case AIR_CONST_FLOAT:+ return air_val_ssa(c, reinterpret_float(c, t, scalar_constant(c, air_type_scalar(t), k->u)));++ case AIR_CONST_NULL:+ if (t->kind == AIR_TYPE_POINTER) {+ struct air_ptr p = { .class = AIR_PTR_NONE, .pointee = t->elem };+ return air_val_ptr(c, p);+ }+ if (t->kind == AIR_TYPE_STRUCT || t->kind == AIR_TYPE_ARRAY) {+ unsigned n = t->kind == AIR_TYPE_STRUCT ? t->num_members : t->count;+ struct air_val *v = air_val_agg(c, n);+ for (unsigned i = 0; i < n; i++) {+ const struct air_type *et = t->kind == AIR_TYPE_STRUCT ? t->members[i] : t->elem;+ struct air_constant z = { .base = { .kind = AIR_VALUE_CONSTANT, .type = et },+ .ckind = AIR_CONST_NULL };+ if (!(v->elems[i] = air_constant_val(c, &z)))+ return NULL;+ }+ return v;+ }+ return air_val_ssa(c, nir_imm_zero(&c->b, air_nir_components(t), air_nir_bit_size(c, t)));++ case AIR_CONST_UNDEF:+ case AIR_CONST_POISON:+ if (t->kind == AIR_TYPE_STRUCT || t->kind == AIR_TYPE_ARRAY) {+ unsigned n = t->kind == AIR_TYPE_STRUCT ? t->num_members : t->count;+ struct air_val *v = air_val_agg(c, n);+ /* fields stay NONE until insertvalue puts something there */+ return v;+ }+ if (t->kind == AIR_TYPE_POINTER) {+ struct air_ptr p = { .class = AIR_PTR_NONE, .pointee = t->elem };+ return air_val_ptr(c, p);+ }+ return air_val_ssa(c, nir_undef(&c->b, air_nir_components(t), air_nir_bit_size(c, t)));++ case AIR_CONST_AGGREGATE: {+ if (t->kind == AIR_TYPE_VECTOR) {+ nir_def *comps[NIR_MAX_VEC_COMPONENTS];+ if (k->num_elems > NIR_MAX_VEC_COMPONENTS)+ return air_error(c, "instruction: a vector constant of %u elements", k->num_elems), NULL;+ for (unsigned i = 0; i < k->num_elems; i++)+ if (!(comps[i] = air_get_ssa(c, k->elems[i])))+ return NULL;+ return air_val_ssa(c, nir_vec(&c->b, comps, k->num_elems));+ }+ struct air_val *v = air_val_agg(c, k->num_elems);+ for (unsigned i = 0; i < k->num_elems; i++)+ if (!(v->elems[i] = air_get(c, k->elems[i])))+ return NULL;+ return v;+ }++ case AIR_CONST_DATA: {+ const struct air_type *et = t->kind == AIR_TYPE_STRUCT ? NULL : t->elem;+ if (!et)+ return air_error(c, "instruction: a data constant of a struct type"), NULL;+ if (t->kind == AIR_TYPE_VECTOR) {+ nir_def *comps[NIR_MAX_VEC_COMPONENTS];+ if (k->num_elems > NIR_MAX_VEC_COMPONENTS)+ return air_error(c, "instruction: a vector constant of %u elements", k->num_elems), NULL;+ for (unsigned i = 0; i < k->num_elems; i++)+ comps[i] = reinterpret_float(c, et, scalar_constant(c, et, k->data[i]));+ return air_val_ssa(c, nir_vec(&c->b, comps, k->num_elems));+ }+ struct air_val *v = air_val_agg(c, k->num_elems);+ for (unsigned i = 0; i < k->num_elems; i++)+ v->elems[i] = air_val_ssa(c, reinterpret_float(c, et, scalar_constant(c, et, k->data[i])));+ return v;+ }++ case AIR_CONST_EXPR:+ /* with opaque pointers the only constant expression left in the corpus+ * is a pointer bitcast, which is the pointer itself+ */+ if (k->expr_op == AIR_OP_CAST && k->expr_sub == AIR_CAST_BITCAST &&+ k->base.type->kind == AIR_TYPE_POINTER)+ return air_get(c, k->operands[0]);+ return air_error(c, "instruction: constant expression %u", k->expr_op), NULL;+ }+ return air_error(c, "instruction: constant kind %u", k->ckind), NULL;+}++/* -- memory ------------------------------------------------------------- */++struct air_ptr+air_ptr_add(struct air_ctx *c, struct air_ptr ptr, nir_def *bytes)+{+ if (!bytes)+ return ptr;+ ptr.offset = ptr.offset ? nir_iadd(&c->b, ptr.offset, bytes) : bytes;+ return ptr;+}++static nir_def *+ptr_offset(struct air_ctx *c, struct air_ptr ptr)+{+ return ptr.offset ? ptr.offset : nir_imm_int(&c->b, 0);+}++nir_def *+air_load_ptr(struct air_ctx *c, struct air_ptr ptr, const struct air_type *type, unsigned align)+{+ unsigned comps = air_nir_components(type);+ unsigned bits = air_nir_bit_size(c, type);+ if (type->kind == AIR_TYPE_POINTER)+ return air_error(c, "instruction: a pointer loaded from memory (argument buffers)"), NULL;+ if (!align)+ align = MAX2(bits / 8, 1);++ /* a 1-bit load is a byte in memory */+ bool as_bool = bits == 1;+ if (as_bool)+ bits = 8;++ nir_def *off = ptr_offset(c, ptr);+ nir_def *res;+ switch (ptr.class) {+ case AIR_PTR_UBO:+ res = nir_load_ubo(&c->b, comps, bits, nir_imm_int(&c->b, ptr.binding), off,+ .align_mul = align, .align_offset = 0, .range_base = 0, .range = ~0);+ break;+ case AIR_PTR_SSBO:+ res = nir_load_ssbo(&c->b, comps, bits, nir_imm_int(&c->b, ptr.binding), off,+ .align_mul = align, .align_offset = 0);+ break;+ case AIR_PTR_SHARED:+ res = nir_load_shared(&c->b, comps, bits, off, .base = 0, .align_mul = align);+ break;+ case AIR_PTR_SCRATCH:+ res = nir_load_scratch(&c->b, comps, bits, off, .align_mul = align);+ break;+ case AIR_PTR_CONSTANT_DATA:+ res = nir_load_constant(&c->b, comps, bits, off, .base = 0, .range = c->nir->constant_data_size,+ .align_mul = align);+ break;+ case AIR_PTR_FUNCTION_CONSTANT: {+ /* its value is known at pipeline creation, so the load is that value */+ const struct air_constant_value *v = NULL;+ for (unsigned i = 0; c->options && i < c->options->num_constants; i++)+ if (c->options->constants[i].index == ptr.binding)+ v = &c->options->constants[i];+ if (!v)+ return air_error(c, "interface: function constant %u has no value", ptr.binding), NULL;+ if (comps != 1)+ return air_error(c, "interface: a function constant of %u components", comps), NULL;+ res = nir_imm_intN_t(&c->b, v->bits, as_bool ? 8 : bits);+ break;+ }+ default:+ return air_error(c, "instruction: a load through a %s pointer",+ ptr.class == AIR_PTR_NONE ? "null" : "texture or sampler"), NULL;+ }+ return as_bool ? nir_ine_imm(&c->b, res, 0) : res;+}++bool+air_store_ptr(struct air_ctx *c, struct air_ptr ptr, nir_def *value, unsigned align)+{+ unsigned comps = value->num_components;+ if (value->bit_size == 1) {+ value = nir_b2iN(&c->b, value, 8);+ }+ if (!align)+ align = MAX2(value->bit_size / 8, 1);++ nir_def *off = ptr_offset(c, ptr);+ switch (ptr.class) {+ case AIR_PTR_SSBO:+ nir_store_ssbo(&c->b, value, nir_imm_int(&c->b, ptr.binding), off,+ .write_mask = BITFIELD_MASK(comps), .align_mul = align);+ return true;+ case AIR_PTR_SHARED:+ nir_store_shared(&c->b, value, off, .base = 0, .write_mask = BITFIELD_MASK(comps),+ .align_mul = align);+ return true;+ case AIR_PTR_SCRATCH:+ nir_store_scratch(&c->b, value, off, .align_mul = align,+ .write_mask = BITFIELD_MASK(comps));+ return true;+ case AIR_PTR_UBO:+ case AIR_PTR_CONSTANT_DATA:+ return air_error(c, "instruction: a store into constant memory");+ default:+ return air_error(c, "instruction: a store through a %s pointer",+ ptr.class == AIR_PTR_NONE ? "null" : "texture or sampler");+ }+}++/* -- metadata helpers --------------------------------------------------- */++static const char *+md_str(const struct air_md *node, unsigned i)+{+ if (!node || i >= node->num_ops || !node->ops[i] || node->ops[i]->kind != AIR_MD_STRING)+ return NULL;+ return air_md_string(node->ops[i]);+}++static bool+md_int(const struct air_md *node, unsigned i, uint64_t *out)+{+ if (!node || i >= node->num_ops || !node->ops[i] || node->ops[i]->kind != AIR_MD_VALUE)+ return false;+ /* zero is written as a null constant, as everywhere else in the bitcode */+ return air_const_uint(node->ops[i]->value, out);+}++/* the index of the operand after the key, or -1 */+static int+md_key(const struct air_md *node, const char *key)+{+ for (unsigned i = 0; i < (node ? node->num_ops : 0); i++) {+ const char *s = md_str(node, i);+ if (s && !strcmp(s, key))+ return i;+ }+ return -1;+}++static bool+md_key_int(const struct air_md *node, const char *key, uint64_t *out)+{+ int i = md_key(node, key);+ return i >= 0 && md_int(node, i + 1, out);+}++static const char *+md_key_str(const struct air_md *node, const char *key)+{+ int i = md_key(node, key);+ return i >= 0 ? md_str(node, i + 1) : NULL;+}++static const struct air_named_md *+named_md(const struct air_module *m, const char *name)+{+ for (unsigned i = 0; i < m->num_named_md; i++)+ if (!strcmp(m->named_md[i].name, name))+ return &m->named_md[i];+ return NULL;+}++/* -- stage -------------------------------------------------------------- */++struct stage_md {+ gl_shader_stage stage;+ const char *md_name;+};++static const struct stage_md stages[] = {+ { MESA_SHADER_VERTEX, "air.vertex" },+ { MESA_SHADER_FRAGMENT, "air.fragment" },+ { MESA_SHADER_COMPUTE, "air.kernel" },+ { MESA_SHADER_NONE, "air.visible" },+};++static int+module_stage(const struct air_module *m, const struct air_md **entry)+{+ for (unsigned i = 0; i < ARRAY_SIZE(stages); i++) {+ const struct air_named_md *n = named_md(m, stages[i].md_name);+ if (n && n->num_ops >= 1 && n->ops[0] && n->ops[0]->kind == AIR_MD_NODE) {+ if (entry)+ *entry = n->ops[0];+ return stages[i].stage;+ }+ }+ return -2; /* no entry point at all */+}++int+air_module_stage(void *mem_ctx, const void *bitcode, size_t size, const char **calls,+ const char **error)+{+ void *ctx = ralloc_context(mem_ctx);+ struct air_module *m = air_module_read(ctx, bitcode, size, error);+ if (!m) {+ ralloc_free(ctx);+ return -1;+ }++ if (calls) {+ size_t len = 1;+ for (unsigned i = 0; i < m->num_functions; i++) {+ const char *n = m->functions[i]->base.name;+ if (m->functions[i]->is_declaration && n && !strncmp(n, "air.", 4))+ len += strlen(n) + 1;+ }+ char *buf = rzalloc_size(mem_ctx, len), *p = buf;+ for (unsigned i = 0; i < m->num_functions; i++) {+ const char *n = m->functions[i]->base.name;+ if (m->functions[i]->is_declaration && n && !strncmp(n, "air.", 4)) {+ memcpy(p, n, strlen(n) + 1);+ p += strlen(n) + 1;+ }+ }+ *calls = buf;+ }++ int stage = module_stage(m, NULL);+ ralloc_free(ctx);+ return stage;+}++unsigned+air_module_function_constants(void *mem_ctx, const void *bitcode, size_t size,+ struct air_constant_value **out)+{+ void *ctx = ralloc_context(mem_ctx);+ const char *err;+ struct air_module *m = air_module_read(ctx, bitcode, size, &err);+ *out = NULL;+ if (!m) {+ ralloc_free(ctx);+ return 0;+ }+ const struct air_named_md *n = named_md(m, "air.function_constants");+ unsigned num = 0;+ if (n && n->num_ops) {+ *out = rzalloc_array(mem_ctx, struct air_constant_value, n->num_ops);+ for (unsigned i = 0; i < n->num_ops; i++) {+ const struct air_md *node = n->ops[i];+ for (unsigned k = 1; k < (node ? node->num_ops : 0); k++) {+ uint64_t idx;+ if (md_int(node, k, &idx)) {+ (*out)[num++].index = idx;+ break;+ }+ }+ }+ }+ ralloc_free(ctx);+ return num;+}++/* -- the interface ------------------------------------------------------ */++/* AIR's names for what NIR calls system values */+enum air_sysval {+ AIR_SV_VERTEX_ID, AIR_SV_INSTANCE_ID, AIR_SV_BASE_VERTEX, AIR_SV_BASE_INSTANCE,+ AIR_SV_FRONT_FACING, AIR_SV_SAMPLE_ID, AIR_SV_SAMPLE_MASK_IN, AIR_SV_POINT_COORD,+ AIR_SV_THREAD_POS_GRID, AIR_SV_THREAD_POS_TG, AIR_SV_TG_POS_GRID,+ AIR_SV_THREADS_PER_TG, AIR_SV_TGS_PER_GRID, AIR_SV_THREAD_INDEX_TG,+ AIR_SV_THREADS_PER_GRID, AIR_SV_SIMD_LANE, AIR_SV_SIMD_INDEX, AIR_SV_SIMD_WIDTH,+};++static const struct { const char *key; enum air_sysval sv; } sysvals[] = {+ { "air.vertex_id", AIR_SV_VERTEX_ID },+ { "air.instance_id", AIR_SV_INSTANCE_ID },+ { "air.base_vertex", AIR_SV_BASE_VERTEX },+ { "air.base_instance", AIR_SV_BASE_INSTANCE },+ { "air.front_facing", AIR_SV_FRONT_FACING },+ { "air.sample_id", AIR_SV_SAMPLE_ID },+ { "air.sample_mask_in", AIR_SV_SAMPLE_MASK_IN },+ { "air.point_coord", AIR_SV_POINT_COORD },+ { "air.thread_position_in_grid", AIR_SV_THREAD_POS_GRID },+ { "air.thread_position_in_threadgroup", AIR_SV_THREAD_POS_TG },+ { "air.threadgroup_position_in_grid", AIR_SV_TG_POS_GRID },+ { "air.threads_per_threadgroup", AIR_SV_THREADS_PER_TG },+ { "air.threadgroups_per_grid", AIR_SV_TGS_PER_GRID },+ { "air.thread_index_in_threadgroup", AIR_SV_THREAD_INDEX_TG },+ { "air.threads_per_grid", AIR_SV_THREADS_PER_GRID },+ { "air.thread_index_in_simdgroup", AIR_SV_SIMD_LANE },+ { "air.simdgroup_index_in_threadgroup", AIR_SV_SIMD_INDEX },+ { "air.threads_per_simdgroup", AIR_SV_SIMD_WIDTH },+};++static nir_def *+load_sysval(struct air_ctx *c, enum air_sysval sv)+{+ switch (sv) {+ case AIR_SV_VERTEX_ID: return nir_load_vertex_id(&c->b);+ /* Metal's instance id counts from the base instance, GL's does not */+ case AIR_SV_INSTANCE_ID:+ return nir_iadd(&c->b, nir_load_instance_id(&c->b), nir_load_base_instance(&c->b));+ case AIR_SV_BASE_VERTEX: return nir_load_first_vertex(&c->b);+ case AIR_SV_BASE_INSTANCE: return nir_load_base_instance(&c->b);+ case AIR_SV_FRONT_FACING: return nir_load_front_face(&c->b, 1);+ case AIR_SV_SAMPLE_ID: return nir_load_sample_id(&c->b);+ case AIR_SV_SAMPLE_MASK_IN: return nir_load_sample_mask_in(&c->b);+ case AIR_SV_POINT_COORD: return nir_load_point_coord(&c->b);+ case AIR_SV_THREAD_POS_GRID: return nir_load_global_invocation_id(&c->b, 32);+ case AIR_SV_THREAD_POS_TG: return nir_load_local_invocation_id(&c->b);+ case AIR_SV_TG_POS_GRID: return nir_load_workgroup_id(&c->b);+ case AIR_SV_THREADS_PER_TG: return nir_load_workgroup_size(&c->b);+ case AIR_SV_TGS_PER_GRID: return nir_load_num_workgroups(&c->b);+ case AIR_SV_THREAD_INDEX_TG: return nir_load_local_invocation_index(&c->b);+ case AIR_SV_THREADS_PER_GRID:+ return nir_imul(&c->b, nir_load_num_workgroups(&c->b), nir_load_workgroup_size(&c->b));+ case AIR_SV_SIMD_LANE: return nir_load_subgroup_invocation(&c->b);+ case AIR_SV_SIMD_INDEX: return nir_load_subgroup_id(&c->b);+ case AIR_SV_SIMD_WIDTH: return nir_load_subgroup_size(&c->b);+ }+ return NULL;+}++/* a system value cut or widened to the type the shader declared */+static nir_def *+fit(struct air_ctx *c, nir_def *def, const struct air_type *t)+{+ unsigned want = air_nir_components(t);+ unsigned bits = air_nir_bit_size(c, t);+ if (def->num_components > want)+ def = nir_trim_vector(&c->b, def, want);+ else if (def->num_components < want)+ def = nir_pad_vector(&c->b, def, want);+ if (def->bit_size != bits)+ def = air_type_is_float(air_type_scalar(t))+ ? nir_u2fN(&c->b, def, bits)+ : nir_u2uN(&c->b, def, bits);+ return def;+}++static void+add_resource(struct air_ctx *c, enum air_resource_kind kind, unsigned index, unsigned size,+ bool read, bool write, unsigned param, const struct air_md *node)+{+ struct air_shader_info *info = c->info;+ info->resources = reralloc(c->mem_ctx, info->resources, struct air_resource,+ info->num_resources + 1);+ info->resources[info->num_resources++] = (struct air_resource) {+ .kind = kind, .index = index, .size = size, .read = read, .write = write,+ .param = param,+ .name = md_key_str(node, "air.arg_name"),+ .type_name = md_key_str(node, "air.arg_type_name"),+ };+}++static nir_variable *+make_io_var(struct air_ctx *c, nir_variable_mode mode, const struct air_type *t,+ unsigned location, const char *name)+{+ const struct glsl_type *gt;+ unsigned comps = air_nir_components(t);+ unsigned bits = air_nir_bit_size(c, t);+ if (air_type_is_float(air_type_scalar(t)))+ gt = bits == 16 ? glsl_f16vec_type(comps) : glsl_vec_type(comps);+ else+ gt = glsl_vector_type(bits == 16 ? GLSL_TYPE_INT16 : GLSL_TYPE_INT, comps);++ nir_variable *var = nir_variable_create(c->nir, mode, gt, name ? name : "io");+ var->data.location = location;+ return var;+}++/* fragment inputs and vertex outputs take the slots in the order they appear;+ * the runtime links the two sides by name (docs/air.md section 7.5)+ */+static void+add_varying(struct air_ctx *c, const char *name, unsigned slot, unsigned comps,+ const struct air_md *node)+{+ struct air_shader_info *info = c->info;+ info->varyings = reralloc(c->mem_ctx, info->varyings, struct air_varying,+ info->num_varyings + 1);+ info->varyings[info->num_varyings++] = (struct air_varying) {+ .name = name, .slot = slot, .components = comps,+ .flat = md_key(node, "air.flat") >= 0,+ .centroid = md_key(node, "air.centroid") >= 0,+ .sample = md_key(node, "air.sample") >= 0,+ .no_perspective = md_key(node, "air.no_perspective") >= 0,+ };+}++static bool+translate_input(struct air_ctx *c, const struct air_md *node, unsigned *next_varying)+{+ uint64_t param;+ if (!md_int(node, 0, ¶m))+ return air_error(c, "interface: an input without a parameter number");+ if (param >= c->fn->num_args)+ return air_error(c, "interface: input for parameter %u of %u", (unsigned)param,+ c->fn->num_args);+ const struct air_type *t = c->fn->args[param].type;++ /* resources */+ if (md_key(node, "air.buffer") >= 0) {+ uint64_t as = 0, index = 0, size = 0;+ md_key_int(node, "air.address_space", &as);+ md_key_int(node, "air.location_index", &index);+ md_key_int(node, "air.buffer_size", &size);+ bool read = md_key(node, "air.read") >= 0 || md_key(node, "air.read_write") >= 0;+ bool write = md_key(node, "air.write") >= 0 || md_key(node, "air.read_write") >= 0;++ struct air_ptr p = { .binding = index, .pointee = t->elem };+ enum air_resource_kind rk;+ switch (as) {+ case 1: p.class = AIR_PTR_SSBO; rk = AIR_RESOURCE_DEVICE_BUFFER; break;+ case 2: p.class = AIR_PTR_UBO; rk = AIR_RESOURCE_CONSTANT_BUFFER; break;+ case 3:+ p.class = AIR_PTR_SHARED;+ rk = AIR_RESOURCE_THREADGROUP_BUFFER;+ /* a threadgroup argument is sized at dispatch; its base is where the+ * previous ones end, which only the runtime knows. One is all the+ * corpus uses, so its base is zero and anything else is refused.+ */+ if (index != 0)+ return air_error(c, "interface: a second threadgroup buffer (index %u)",+ (unsigned)index);+ break;+ default:+ return air_error(c, "interface: a buffer in address space %u", (unsigned)as);+ }+ add_resource(c, rk, index, size, read, write, param, node);+ c->params[param] = air_val_ptr(c, p);+ return true;+ }++ if (md_key(node, "air.texture") >= 0) {+ uint64_t index = 0;+ md_key_int(node, "air.location_index", &index);+ bool sample = md_key(node, "air.sample") >= 0;+ bool read = md_key(node, "air.read") >= 0;+ bool write = md_key(node, "air.write") >= 0 || md_key(node, "air.read_write") >= 0;+ struct air_ptr p = {+ .class = (sample || (read && !write)) ? AIR_PTR_TEXTURE : AIR_PTR_TEXTURE,+ .binding = index,+ };+ add_resource(c, write ? AIR_RESOURCE_IMAGE : AIR_RESOURCE_TEXTURE, index, 0,+ sample || read, write, param, node);+ c->params[param] = air_val_ptr(c, p);+ return true;+ }++ if (md_key(node, "air.sampler") >= 0) {+ uint64_t index = 0;+ md_key_int(node, "air.location_index", &index);+ struct air_ptr p = { .class = AIR_PTR_SAMPLER, .binding = index };+ add_resource(c, AIR_RESOURCE_SAMPLER, index, 0, true, false, param, node);+ c->params[param] = air_val_ptr(c, p);+ return true;+ }++ /* system values */+ for (unsigned i = 0; i < ARRAY_SIZE(sysvals); i++) {+ if (md_key(node, sysvals[i].key) < 0)+ continue;+ nir_def *def = load_sysval(c, sysvals[i].sv);+ if (!def)+ return air_error(c, "interface: %s", sysvals[i].key);+ c->params[param] = air_val_ssa(c, fit(c, def, t));+ return true;+ }++ /* interpolated inputs of a fragment shader, and vertex attributes */+ if (md_key(node, "air.position") >= 0) {+ if (c->nir->info.stage == MESA_SHADER_FRAGMENT) {+ nir_def *pos = nir_load_frag_coord(&c->b);+ c->params[param] = air_val_ssa(c, fit(c, pos, t));+ c->nir->info.fs.origin_upper_left = true;+ c->nir->info.fs.pixel_center_integer = false;+ return true;+ }+ return air_error(c, "interface: air.position as an input of a %s shader",+ gl_shader_stage_name(c->nir->info.stage));+ }+ if (md_key(node, "air.fragment_input") >= 0 || md_key(node, "air.vertex_input") >= 0 ||+ md_key(node, "air.stage_in") >= 0) {+ unsigned slot;+ if (c->nir->info.stage == MESA_SHADER_VERTEX) {+ uint64_t index = 0;+ md_key_int(node, "air.location_index", &index);+ slot = VERT_ATTRIB_GENERIC0 + index;+ } else {+ slot = VARYING_SLOT_VAR0 + (*next_varying)++;+ }+ const char *name = md_key_str(node, "air.arg_name");+ nir_variable *var = make_io_var(c, nir_var_shader_in, t, slot, name);+ var->data.driver_location = c->nir->num_inputs++;+ if (md_key(node, "air.flat") >= 0)+ var->data.interpolation = INTERP_MODE_FLAT;+ else if (md_key(node, "air.no_perspective") >= 0)+ var->data.interpolation = INTERP_MODE_NOPERSPECTIVE;+ else+ var->data.interpolation = INTERP_MODE_SMOOTH;+ var->data.centroid = md_key(node, "air.centroid") >= 0;+ var->data.sample = md_key(node, "air.sample") >= 0;+ if (c->nir->info.stage == MESA_SHADER_FRAGMENT)+ add_varying(c, name, slot, air_nir_components(t), node);+ c->params[param] = air_val_ssa(c, nir_load_var(&c->b, var));+ return true;+ }++ /* the one thing left that is not an error: an argument nothing reads */+ if (md_key(node, "air.arg_unused") >= 0) {+ c->params[param] = air_val_ssa(c, nir_undef(&c->b, air_nir_components(t),+ air_nir_bit_size(c, t)));+ return true;+ }++ for (unsigned i = 0; i < node->num_ops; i++) {+ const char *s = md_str(node, i);+ if (s && !strncmp(s, "air.", 4) && strcmp(s, "air.arg_name") &&+ strcmp(s, "air.arg_type_name"))+ return air_error(c, "interface: input %s", s);+ }+ return air_error(c, "interface: an input with no key this translator knows");+}++static bool+translate_output(struct air_ctx *c, const struct air_md *node, unsigned field,+ const struct air_type *t, unsigned *next_varying)+{+ unsigned location = ~0u, index = 0;+ const char *name = md_key_str(node, "air.arg_name");++ int rt = md_key(node, "air.render_target");+ if (rt >= 0) {+ uint64_t n = 0, dual = 0;+ md_int(node, rt + 1, &n);+ md_int(node, rt + 2, &dual);+ location = FRAG_RESULT_DATA0 + n;+ index = dual;+ c->info->num_render_targets = MAX2(c->info->num_render_targets, n + 1);+ } else if (md_key(node, "air.depth") >= 0) {+ location = FRAG_RESULT_DEPTH;+ const char *q = md_key_str(node, "air.depth_qualifier");+ c->nir->info.fs.depth_layout =+ !q || !strcmp(q, "air.any") ? FRAG_DEPTH_LAYOUT_ANY :+ !strcmp(q, "air.greater") ? FRAG_DEPTH_LAYOUT_GREATER :+ !strcmp(q, "air.less") ? FRAG_DEPTH_LAYOUT_LESS : FRAG_DEPTH_LAYOUT_UNCHANGED;+ } else if (md_key(node, "air.sample_mask") >= 0) {+ location = FRAG_RESULT_SAMPLE_MASK;+ } else if (md_key(node, "air.stencil") >= 0) {+ location = FRAG_RESULT_STENCIL;+ } else if (md_key(node, "air.position") >= 0) {+ location = VARYING_SLOT_POS;+ } else if (md_key(node, "air.point_size") >= 0) {+ location = VARYING_SLOT_PSIZ;+ } else if (md_key(node, "air.clip_distance") >= 0) {+ location = VARYING_SLOT_CLIP_DIST0;+ } else if (md_key(node, "air.render_target_array_index") >= 0) {+ location = VARYING_SLOT_LAYER;+ } else if (md_key(node, "air.viewport_array_index") >= 0) {+ location = VARYING_SLOT_VIEWPORT;+ } else if (md_key(node, "air.vertex_output") >= 0) {+ location = VARYING_SLOT_VAR0 + (*next_varying)++;+ add_varying(c, md_str(node, md_key(node, "air.vertex_output") + 1), location,+ air_nir_components(t), node);+ } else {+ for (unsigned i = 0; i < node->num_ops; i++) {+ const char *s = md_str(node, i);+ if (s && !strncmp(s, "air.", 4) && strcmp(s, "air.arg_name") &&+ strcmp(s, "air.arg_type_name"))+ return air_error(c, "interface: output %s", s);+ }+ return air_error(c, "interface: an output with no key this translator knows");+ }++ nir_variable *var = make_io_var(c, nir_var_shader_out, t, location, name);+ var->data.index = index;+ var->data.driver_location = c->nir->num_outputs++;+ c->outputs[field].location = location;+ c->outputs[field].index = index;+ c->outputs[field].var = var;+ return true;+}++/* -- instructions ------------------------------------------------------- */++static bool+translate_gep(struct air_ctx *c, const struct air_inst *in)+{+ struct air_val *base = air_get(c, in->operands[0]);+ if (!base)+ return false;+ if (base->kind != AIR_VAL_PTR)+ return air_error(c, "instruction: getelementptr on something that is not a pointer");++ struct air_ptr p = base->ptr;+ const struct air_type *t = in->aux_type;++ /* index 0 steps over objects of the source type */+ uint64_t stride = air_type_alloc_size(c->m, t);+ uint64_t first_const;+ if (!air_const_uint(in->operands[1], &first_const) || first_const != 0) {+ nir_def *first = air_get_ssa(c, in->operands[1]);+ if (!first)+ return false;+ p = air_ptr_add(c, p, nir_imul_imm(&c->b, nir_u2u32(&c->b, first), stride));+ }++ for (unsigned i = 2; i < in->num_operands; i++) {+ nir_def *idx = air_get_ssa(c, in->operands[i]);+ if (!idx)+ return false;+ if (t->kind == AIR_TYPE_STRUCT) {+ uint64_t field;+ if (!air_const_uint(in->operands[i], &field))+ return air_error(c, "instruction: a struct field chosen at run time");+ unsigned n = field;+ if (n >= t->num_members)+ return air_error(c, "instruction: struct field %u of %u", n, t->num_members);+ uint64_t off = air_struct_member_offset(c->m, t, n);+ if (off)+ p = air_ptr_add(c, p, nir_imm_int(&c->b, off));+ t = t->members[n];+ } else if (t->kind == AIR_TYPE_ARRAY || t->kind == AIR_TYPE_VECTOR) {+ uint64_t es = t->kind == AIR_TYPE_ARRAY ? air_type_alloc_size(c->m, t->elem)+ : MAX2(air_type_bit_size(t->elem) / 8, 1);+ p = air_ptr_add(c, p, nir_imul_imm(&c->b, nir_u2u32(&c->b, idx), es));+ t = t->elem;+ } else {+ return air_error(c, "instruction: getelementptr into a scalar");+ }+ }+ p.pointee = t;+ air_set(c, &in->base, air_val_ptr(c, p));+ return true;+}++static bool+translate_binop(struct air_ctx *c, const struct air_inst *in)+{+ nir_def *x = air_get_ssa(c, in->operands[0]);+ nir_def *y = air_get_ssa(c, in->operands[1]);+ if (!x || !y)+ return false;+ bool is_float = air_type_is_float(air_type_scalar(in->base.type));+ nir_def *res;++ /* Metal compiles with fast math on, and the modules say so per+ * instruction. Without the flags the arithmetic must not be reassociated,+ * so the builder is told to keep it exact.+ */+ bool was_exact = c->b.exact;+ if (is_float)+ c->b.exact = !(in->flags & (AIR_FMF_UNSAFE_ALGEBRA | AIR_FMF_REASSOC));++ switch (in->sub) {+ case AIR_BINOP_ADD: res = is_float ? nir_fadd(&c->b, x, y) : nir_iadd(&c->b, x, y); break;+ case AIR_BINOP_SUB: res = is_float ? nir_fsub(&c->b, x, y) : nir_isub(&c->b, x, y); break;+ case AIR_BINOP_MUL: res = is_float ? nir_fmul(&c->b, x, y) : nir_imul(&c->b, x, y); break;+ case AIR_BINOP_UDIV: res = is_float ? nir_fdiv(&c->b, x, y) : nir_udiv(&c->b, x, y); break;+ case AIR_BINOP_SDIV: res = is_float ? nir_fdiv(&c->b, x, y) : nir_idiv(&c->b, x, y); break;+ case AIR_BINOP_UREM: res = is_float ? nir_frem(&c->b, x, y) : nir_umod(&c->b, x, y); break;+ case AIR_BINOP_SREM: res = is_float ? nir_frem(&c->b, x, y) : nir_irem(&c->b, x, y); break;+ case AIR_BINOP_SHL: res = nir_ishl(&c->b, x, nir_u2u32(&c->b, y)); break;+ case AIR_BINOP_LSHR: res = nir_ushr(&c->b, x, nir_u2u32(&c->b, y)); break;+ case AIR_BINOP_ASHR: res = nir_ishr(&c->b, x, nir_u2u32(&c->b, y)); break;+ case AIR_BINOP_AND: res = nir_iand(&c->b, x, y); break;+ case AIR_BINOP_OR: res = nir_ior(&c->b, x, y); break;+ case AIR_BINOP_XOR: res = nir_ixor(&c->b, x, y); break;+ default:+ c->b.exact = was_exact;+ return air_error(c, "instruction: binary operator %u", in->sub);+ }+ c->b.exact = was_exact;+ air_set(c, &in->base, air_val_ssa(c, res));+ return true;+}++static bool+translate_cast(struct air_ctx *c, const struct air_inst *in)+{+ const struct air_type *dt = in->base.type;+ const struct air_type *st = in->operands[0]->type;++ if (in->sub == AIR_CAST_BITCAST && dt->kind == AIR_TYPE_POINTER) {+ struct air_val *v = air_get(c, in->operands[0]);+ if (!v || v->kind != AIR_VAL_PTR)+ return air_error(c, "instruction: a bitcast of something that is not a pointer");+ struct air_ptr p = v->ptr;+ p.pointee = dt->elem;+ air_set(c, &in->base, air_val_ptr(c, p));+ return true;+ }++ nir_def *x = air_get_ssa(c, in->operands[0]);+ if (!x)+ return false;+ unsigned bits = air_nir_bit_size(c, dt);+ nir_def *res;+ switch (in->sub) {+ case AIR_CAST_TRUNC:+ res = bits == 1 ? nir_i2b(&c->b, nir_iand_imm(&c->b, x, 1)) : nir_u2uN(&c->b, x, bits);+ break;+ case AIR_CAST_ZEXT:+ res = x->bit_size == 1 ? nir_b2iN(&c->b, x, bits) : nir_u2uN(&c->b, x, bits);+ break;+ case AIR_CAST_SEXT:+ res = x->bit_size == 1 ? nir_ineg(&c->b, nir_b2iN(&c->b, x, bits))+ : nir_i2iN(&c->b, x, bits);+ break;+ case AIR_CAST_FPTOUI: res = nir_f2uN(&c->b, x, bits); break;+ case AIR_CAST_FPTOSI: res = nir_f2iN(&c->b, x, bits); break;+ case AIR_CAST_UITOFP:+ res = x->bit_size == 1 ? nir_b2fN(&c->b, x, bits) : nir_u2fN(&c->b, x, bits);+ break;+ case AIR_CAST_SITOFP:+ res = x->bit_size == 1 ? nir_fneg(&c->b, nir_b2fN(&c->b, x, bits))+ : nir_i2fN(&c->b, x, bits);+ break;+ case AIR_CAST_FPTRUNC: res = nir_f2fN(&c->b, x, bits); break;+ case AIR_CAST_FPEXT: res = nir_f2fN(&c->b, x, bits); break;+ case AIR_CAST_BITCAST:+ if (air_nir_components(dt) != air_nir_components(st) ||+ air_nir_bit_size(c, dt) != air_nir_bit_size(c, st))+ return air_error(c, "instruction: a bitcast that changes the shape of its value");+ res = nir_mov(&c->b, x);+ break;+ default:+ return air_error(c, "instruction: cast %u", in->sub);+ }+ air_set(c, &in->base, air_val_ssa(c, res));+ return true;+}++static bool+translate_cmp(struct air_ctx *c, const struct air_inst *in)+{+ nir_def *x = air_get_ssa(c, in->operands[0]);+ nir_def *y = air_get_ssa(c, in->operands[1]);+ if (!x || !y)+ return false;+ nir_def *res;+ switch (in->sub) {+ /* NaN never appears in these shaders (nnan is set on every one), so the+ * ordered and unordered forms of a comparison are the same comparison;+ * what differs is only the answer when an operand is NaN.+ */+ case AIR_FCMP_OEQ: case AIR_FCMP_UEQ: res = nir_feq(&c->b, x, y); break;+ case AIR_FCMP_ONE: case AIR_FCMP_UNE: res = nir_fneu(&c->b, x, y); break;+ case AIR_FCMP_OGT: case AIR_FCMP_UGT: res = nir_flt(&c->b, y, x); break;+ case AIR_FCMP_OGE: case AIR_FCMP_UGE: res = nir_fge(&c->b, x, y); break;+ case AIR_FCMP_OLT: case AIR_FCMP_ULT: res = nir_flt(&c->b, x, y); break;+ case AIR_FCMP_OLE: case AIR_FCMP_ULE: res = nir_fge(&c->b, y, x); break;+ case AIR_FCMP_ORD: res = nir_iand(&c->b, nir_feq(&c->b, x, x), nir_feq(&c->b, y, y)); break;+ case AIR_FCMP_UNO: res = nir_ior(&c->b, nir_fneu(&c->b, x, x), nir_fneu(&c->b, y, y)); break;+ case AIR_FCMP_FALSE: res = nir_imm_false(&c->b); break;+ case AIR_FCMP_TRUE: res = nir_imm_true(&c->b); break;+ case AIR_ICMP_EQ: res = nir_ieq(&c->b, x, y); break;+ case AIR_ICMP_NE: res = nir_ine(&c->b, x, y); break;+ case AIR_ICMP_UGT: res = nir_ult(&c->b, y, x); break;+ case AIR_ICMP_UGE: res = nir_uge(&c->b, x, y); break;+ case AIR_ICMP_ULT: res = nir_ult(&c->b, x, y); break;+ case AIR_ICMP_ULE: res = nir_uge(&c->b, y, x); break;+ case AIR_ICMP_SGT: res = nir_ilt(&c->b, y, x); break;+ case AIR_ICMP_SGE: res = nir_ige(&c->b, x, y); break;+ case AIR_ICMP_SLT: res = nir_ilt(&c->b, x, y); break;+ case AIR_ICMP_SLE: res = nir_ige(&c->b, y, x); break;+ default:+ return air_error(c, "instruction: comparison %u", in->sub);+ }+ air_set(c, &in->base, air_val_ssa(c, res));+ return true;+}++/* an aggregate value's field, by the index path of extract/insertvalue */+static struct air_val **+agg_slot(struct air_ctx *c, struct air_val *agg, const uint32_t *idx, unsigned n)+{+ struct air_val **slot = &agg;+ for (unsigned i = 0; i < n; i++) {+ if (!*slot || (*slot)->kind != AIR_VAL_AGG || idx[i] >= (*slot)->num_elems) {+ air_error(c, "instruction: an aggregate index out of its value");+ return NULL;+ }+ slot = &(*slot)->elems[idx[i]];+ }+ return slot;+}++static struct air_val *+clone_val(struct air_ctx *c, const struct air_val *v)+{+ if (!v)+ return NULL;+ struct air_val *n = rzalloc(c->mem_ctx, struct air_val);+ *n = *v;+ if (v->kind == AIR_VAL_AGG) {+ n->elems = rzalloc_array(c->mem_ctx, struct air_val *, MAX2(v->num_elems, 1));+ for (unsigned i = 0; i < v->num_elems; i++)+ n->elems[i] = clone_val(c, v->elems[i]);+ }+ return n;+}++static bool+translate_instruction(struct air_ctx *c, const struct air_inst *in)+{+ switch (in->op) {+ case AIR_OP_BINOP:+ return translate_binop(c, in);+ case AIR_OP_UNOP: {+ nir_def *x = air_get_ssa(c, in->operands[0]);+ if (!x)+ return false;+ air_set(c, &in->base, air_val_ssa(c, nir_fneg(&c->b, x)));+ return true;+ }+ case AIR_OP_CAST:+ return translate_cast(c, in);+ case AIR_OP_CMP:+ return translate_cmp(c, in);+ case AIR_OP_GEP:+ return translate_gep(c, in);+ case AIR_OP_SELECT: {+ nir_def *cond = air_get_ssa(c, in->operands[0]);+ nir_def *x = air_get_ssa(c, in->operands[1]);+ nir_def *y = air_get_ssa(c, in->operands[2]);+ if (!cond || !x || !y)+ return false;+ if (cond->num_components > 1 && cond->num_components != x->num_components)+ return air_error(c, "instruction: a select whose condition does not match its values");+ air_set(c, &in->base, air_val_ssa(c, nir_bcsel(&c->b, cond, x, y)));+ return true;+ }+ case AIR_OP_EXTRACTELT: {+ nir_def *v = air_get_ssa(c, in->operands[0]);+ nir_def *i = air_get_ssa(c, in->operands[1]);+ if (!v || !i)+ return false;+ air_set(c, &in->base, air_val_ssa(c, nir_vector_extract(&c->b, v, nir_u2u32(&c->b, i))));+ return true;+ }+ case AIR_OP_INSERTELT: {+ nir_def *v = air_get_ssa(c, in->operands[0]);+ nir_def *x = air_get_ssa(c, in->operands[1]);+ nir_def *i = air_get_ssa(c, in->operands[2]);+ if (!v || !x || !i)+ return false;+ if (!nir_src_is_const(nir_src_for_ssa(i)))+ return air_error(c, "instruction: insertelement at a run-time index");+ air_set(c, &in->base,+ air_val_ssa(c, nir_vector_insert_imm(&c->b, v, x,+ nir_src_as_uint(nir_src_for_ssa(i)))));+ return true;+ }+ case AIR_OP_SHUFFLEVEC: {+ nir_def *x = air_get_ssa(c, in->operands[0]);+ nir_def *y = air_get_ssa(c, in->operands[1]);+ struct air_val *mv = air_get(c, in->operands[2]);+ if (!x || !y || !mv)+ return false;+ unsigned n = air_nir_components(in->base.type);+ nir_def *comps[NIR_MAX_VEC_COMPONENTS];+ if (n > NIR_MAX_VEC_COMPONENTS)+ return air_error(c, "instruction: a shuffle of %u components", n);+ /* the mask is a constant vector, or zeroinitializer, or undef */+ const struct air_constant *mk = air_value_as_constant(in->operands[2]);+ for (unsigned i = 0; i < n; i++) {+ int64_t sel = 0;+ bool undef = false;+ if (mk && mk->ckind == AIR_CONST_DATA && i < mk->num_elems) {+ sel = (int32_t)mk->data[i];+ } else if (mk && mk->ckind == AIR_CONST_AGGREGATE && i < mk->num_elems) {+ const struct air_constant *e = air_value_as_constant(mk->elems[i]);+ if (!e || (e->ckind != AIR_CONST_INT && e->ckind != AIR_CONST_UNDEF &&+ e->ckind != AIR_CONST_POISON))+ return air_error(c, "instruction: a shuffle mask that is not constant");+ undef = e->ckind != AIR_CONST_INT;+ sel = undef ? 0 : (int32_t)e->u;+ } else if (mk && (mk->ckind == AIR_CONST_NULL)) {+ sel = 0;+ } else if (mk && (mk->ckind == AIR_CONST_UNDEF || mk->ckind == AIR_CONST_POISON)) {+ undef = true;+ } else {+ return air_error(c, "instruction: a shuffle mask that is not constant");+ }+ if (undef) {+ comps[i] = nir_undef(&c->b, 1, x->bit_size);+ } else if (sel < x->num_components) {+ comps[i] = nir_channel(&c->b, x, sel);+ } else if (sel - x->num_components < y->num_components) {+ comps[i] = nir_channel(&c->b, y, sel - x->num_components);+ } else {+ return air_error(c, "instruction: a shuffle index past its inputs");+ }+ }+ air_set(c, &in->base, air_val_ssa(c, nir_vec(&c->b, comps, n)));+ return true;+ }+ case AIR_OP_EXTRACTVAL: {+ struct air_val *agg = air_get(c, in->operands[0]);+ if (!agg)+ return false;+ struct air_val **slot = agg_slot(c, agg, in->indices, in->num_indices);+ if (!slot)+ return false;+ if (!*slot) {+ /* a field of an undef aggregate */+ air_set(c, &in->base,+ air_val_ssa(c, nir_undef(&c->b, air_nir_components(in->base.type),+ air_nir_bit_size(c, in->base.type))));+ return true;+ }+ air_set(c, &in->base, *slot);+ return true;+ }+ case AIR_OP_INSERTVAL: {+ struct air_val *agg = air_get(c, in->operands[0]);+ struct air_val *val = air_get(c, in->operands[1]);+ if (!agg || !val)+ return false;+ struct air_val *copy = clone_val(c, agg);+ struct air_val **slot = agg_slot(c, copy, in->indices, in->num_indices);+ if (!slot)+ return false;+ *slot = val;+ air_set(c, &in->base, copy);+ return true;+ }+ case AIR_OP_FREEZE:+ air_set(c, &in->base, air_get(c, in->operands[0]));+ return c->error[0] == 0;+ case AIR_OP_ALLOCA: {+ uint64_t count;+ if (!air_const_uint(in->operands[0], &count))+ return air_error(c, "instruction: an alloca of a run-time size");+ uint64_t size = air_type_alloc_size(c->m, in->aux_type) * count;+ unsigned align = MAX2(in->align, air_type_abi_align(c->m, in->aux_type));+ c->scratch_size = ALIGN_POT(c->scratch_size, MAX2(align, 1));+ struct air_ptr p = {+ .class = AIR_PTR_SCRATCH,+ .offset = nir_imm_int(&c->b, c->scratch_size),+ .pointee = in->aux_type,+ };+ c->scratch_size += size;+ air_set(c, &in->base, air_val_ptr(c, p));+ return true;+ }+ case AIR_OP_LOAD: {+ struct air_val *p = air_get(c, in->operands[0]);+ if (!p)+ return false;+ if (p->kind != AIR_VAL_PTR)+ return air_error(c, "instruction: a load from something that is not a pointer");+ nir_def *res = air_load_ptr(c, p->ptr, in->base.type, in->align);+ if (!res)+ return false;+ air_set(c, &in->base, air_val_ssa(c, res));+ return true;+ }+ case AIR_OP_STORE: {+ struct air_val *p = air_get(c, in->operands[1]);+ nir_def *v = air_get_ssa(c, in->operands[0]);+ if (!p || !v)+ return false;+ if (p->kind != AIR_VAL_PTR)+ return air_error(c, "instruction: a store to something that is not a pointer");+ return air_store_ptr(c, p->ptr, v, in->align);+ }+ case AIR_OP_CALL: {+ const struct air_value *callee = in->operands[0];+ if (callee->kind != AIR_VALUE_FUNCTION || !callee->name)+ return air_error(c, "instruction: a call through a pointer");+ return air_translate_call(c, in, callee->name);+ }+ case AIR_OP_RET:+ case AIR_OP_BR:+ case AIR_OP_UNREACHABLE:+ case AIR_OP_PHI:+ return true; /* handled by the CFG walk */+ default:+ return air_error(c, "instruction: opcode %u", in->op);+ }+}++/* -- the CFG ------------------------------------------------------------ */++static nir_block *+nir_block_of(struct air_ctx *c, const struct air_block *b)+{+ struct hash_entry *e = _mesa_hash_table_search(c->blocks, b);+ if (e)+ return e->data;+ nir_block *n = nir_block_create(c->nir);+ exec_list_push_tail(&c->b.impl->body, &n->cf_node.node);+ n->cf_node.parent = &c->b.impl->cf_node;+ _mesa_hash_table_insert(c->blocks, b, n);+ return n;+}++static bool+emit_return(struct air_ctx *c, const struct air_inst *in)+{+ if (in->num_operands == 0)+ return true;+ struct air_val *v = air_get(c, in->operands[0]);+ if (!v)+ return false;++ const struct air_type *rt = in->operands[0]->type;+ if (rt->kind == AIR_TYPE_STRUCT) {+ if (v->kind != AIR_VAL_AGG || v->num_elems != rt->num_members)+ return air_error(c, "instruction: a returned struct that was never built");+ for (unsigned i = 0; i < v->num_elems; i++) {+ if (!c->outputs[i].var)+ return air_error(c, "interface: field %u of the result has no output", i);+ if (!v->elems[i] || v->elems[i]->kind != AIR_VAL_SSA)+ continue; /* a field left undef is a target nothing writes */+ nir_store_var(&c->b, c->outputs[i].var, v->elems[i]->def,+ BITFIELD_MASK(v->elems[i]->def->num_components));+ }+ return true;+ }+ if (v->kind != AIR_VAL_SSA)+ return air_error(c, "instruction: a returned value that is not a number");+ if (!c->num_outputs || !c->outputs[0].var)+ return air_error(c, "interface: a returned value with no output");+ nir_store_var(&c->b, c->outputs[0].var, v->def, BITFIELD_MASK(v->def->num_components));+ return true;+}++/* The blocks in reverse post-order, so that every value is translated before+ * it is used: LLVM lays blocks out in its own order, and a block whose only+ * predecessor comes after it in that order is ordinary (a loop's exit, say).+ * Reverse post-order respects dominance, which is exactly the guarantee the+ * translation needs. Blocks the entry cannot reach are left out, and the phi+ * pass below ignores edges from them.+ */+static unsigned+reverse_post_order(struct air_ctx *c, const struct air_function *f, unsigned *order)+{+ unsigned n = f->num_blocks;+ uint8_t *state = rzalloc_array(c->mem_ctx, uint8_t, MAX2(n, 1)); /* 0 new, 1 open, 2 done */+ unsigned *stack = rzalloc_array(c->mem_ctx, unsigned, MAX2(n, 1));+ unsigned *next_succ = rzalloc_array(c->mem_ctx, unsigned, MAX2(n, 1));+ unsigned sp = 0, num_post = 0;++ stack[sp++] = 0;+ state[0] = 1;+ while (sp) {+ unsigned bi = stack[sp - 1];+ const struct air_block *blk = &f->blocks[bi];+ const struct air_inst *term = blk->insts[blk->num_insts - 1];+ if (next_succ[bi] < term->num_targets) {+ unsigned to = term->targets[next_succ[bi]++]->index;+ if (state[to] == 0) {+ state[to] = 1;+ next_succ[to] = 0;+ stack[sp++] = to;+ }+ continue;+ }+ state[bi] = 2;+ order[num_post++] = bi; /* post-order */+ sp--;+ }+ /* reverse it in place */+ for (unsigned i = 0; i < num_post / 2; i++) {+ unsigned t = order[i];+ order[i] = order[num_post - 1 - i];+ order[num_post - 1 - i] = t;+ }+ return num_post;+}++static bool+translate_body(struct air_ctx *c)+{+ const struct air_function *f = c->fn;++ /* phis first: each becomes a register, loaded where the phi is and stored+ * at the end of every predecessor (docs/air.md: NIR's own+ * nir_lower_goto_ifs does the same to make an unstructured CFG safe)+ */+ nir_builder entry = nir_builder_at(nir_before_impl(c->b.impl));+ for (unsigned bi = 0; bi < f->num_blocks; bi++) {+ const struct air_block *blk = &f->blocks[bi];+ for (unsigned i = 0; i < blk->num_insts; i++) {+ const struct air_inst *in = blk->insts[i];+ if (in->op != AIR_OP_PHI)+ continue;+ nir_def *reg = nir_decl_reg(&entry, air_nir_components(in->base.type),+ air_nir_bit_size(c, in->base.type), 0);+ _mesa_hash_table_insert(c->phi_regs, in, reg);+ }+ }++ /* NIR's first block is the function's first; the rest are made as they+ * are reached, and nir_lower_goto_ifs puts them in order afterwards+ */+ _mesa_hash_table_insert(c->blocks, &f->blocks[0], nir_start_block(c->b.impl));++ unsigned *order = rzalloc_array(c->mem_ctx, unsigned, MAX2(f->num_blocks, 1));+ unsigned num_order = reverse_post_order(c, f, order);++ for (unsigned oi = 0; oi < num_order; oi++) {+ unsigned bi = order[oi];+ const struct air_block *blk = &f->blocks[bi];+ nir_block *nb = nir_block_of(c, blk);+ c->b.cursor = nir_after_block(nb);++ /* the phis of this block are its first instructions */+ for (unsigned i = 0; i < blk->num_insts; i++) {+ const struct air_inst *in = blk->insts[i];+ if (in->op != AIR_OP_PHI)+ continue;+ struct hash_entry *e = _mesa_hash_table_search(c->phi_regs, in);+ air_set(c, &in->base,+ air_val_ssa(c, nir_load_reg(&c->b, e->data)));+ }++ for (unsigned i = 0; i < blk->num_insts; i++) {+ const struct air_inst *in = blk->insts[i];+ if (in->op == AIR_OP_PHI)+ continue;+ if (!translate_instruction(c, in)) {+ /* say where, so the corpus report points at a line of the module */+ char where[64];+ snprintf(where, sizeof(where), " (block %u, instruction %u, opcode %u)",+ bi, i, in->op);+ if (strlen(c->error) + strlen(where) < sizeof(c->error))+ strcat(c->error, where);+ return false;+ }+ }++ /* where the phi stores of this block's successors go */+ _mesa_hash_table_insert(c->phi_cursors, blk,+ ralloc_memdup(c->mem_ctx, &c->b.cursor, sizeof(c->b.cursor)));++ const struct air_inst *term = blk->insts[blk->num_insts - 1];+ switch (term->op) {+ case AIR_OP_RET:+ if (!emit_return(c, term))+ return false;+ nir_goto(&c->b, c->b.impl->end_block);+ break;+ case AIR_OP_BR:+ if (term->num_targets == 1) {+ nir_goto(&c->b, nir_block_of(c, term->targets[0]));+ } else {+ nir_def *cond = air_get_ssa(c, term->operands[0]);+ if (!cond)+ return false;+ if (term->targets[0] == term->targets[1])+ nir_goto(&c->b, nir_block_of(c, term->targets[0]));+ else+ nir_goto_if(&c->b, nir_block_of(c, term->targets[0]), cond,+ nir_block_of(c, term->targets[1]));+ }+ break;+ case AIR_OP_UNREACHABLE:+ nir_goto(&c->b, c->b.impl->end_block);+ break;+ default:+ return air_error(c, "instruction: block %u ends with opcode %u", bi, term->op);+ }+ }++ /* the phi stores, now that every value exists */+ for (unsigned bi = 0; bi < f->num_blocks; bi++) {+ const struct air_block *blk = &f->blocks[bi];+ for (unsigned i = 0; i < blk->num_insts; i++) {+ const struct air_inst *in = blk->insts[i];+ if (in->op != AIR_OP_PHI)+ continue;+ struct hash_entry *re = _mesa_hash_table_search(c->phi_regs, in);+ if (!re)+ continue; /* a phi in an unreachable block */+ for (unsigned k = 0; k < in->num_operands; k++) {+ struct hash_entry *ce = _mesa_hash_table_search(c->phi_cursors, in->targets[k]);+ if (!ce)+ continue; /* an edge from a block the entry cannot reach */+ c->b.cursor = *(nir_cursor *)ce->data;+ nir_def *val = air_get_ssa(c, in->operands[k]);+ if (!val)+ return false;+ nir_store_reg(&c->b, val, re->data);+ /* later stores into the same block go after this one */+ *(nir_cursor *)ce->data = c->b.cursor;+ }+ }+ }+ return true;+}++/* -- module-scope variables --------------------------------------------- */++/* the index !air.function_constants gives this global, or -1 */+static int+function_constant_index(struct air_ctx *c, const struct air_global *g)+{+ const struct air_named_md *n = named_md(c->m, "air.function_constants");+ for (unsigned i = 0; i < (n ? n->num_ops : 0); i++) {+ const struct air_md *node = n->ops[i];+ if (!node || node->kind != AIR_MD_NODE || !node->num_ops)+ continue;+ if (!node->ops[0] || node->ops[0]->kind != AIR_MD_VALUE ||+ node->ops[0]->value != &g->base)+ continue;+ /* !{ptr @g, !"uint", !"name", i32 index, i1 true} */+ for (unsigned k = 1; k < node->num_ops; k++) {+ uint64_t idx;+ if (md_int(node, k, &idx))+ return (int)idx;+ }+ return -1;+ }+ return -1;+}++static void+translate_globals(struct air_ctx *c)+{+ for (unsigned i = 0; i < c->m->num_globals; i++) {+ const struct air_global *g = c->m->globals[i];+ const char *name = g->base.name ? g->base.name : "";++ /* llvm.compiler.used and llvm.global_ctors are lists for the linker,+ * not memory the shader reads+ */+ if (!strncmp(name, "llvm.", 5))+ continue;++ struct air_ptr p = { .pointee = g->value_type };++ if (g->externally_initialized) {+ int idx = function_constant_index(c, g);+ if (idx < 0) {+ air_error(c, "interface: an externally initialized variable that is not a "+ "function constant");+ return;+ }+ p.class = AIR_PTR_FUNCTION_CONSTANT;+ p.binding = idx;+ } else if (!strncmp(name, "__air_sampler_state", 19)) {+ /* an inline sampler; its state word is g->init (docs/air.md 7.7) */+ p.class = AIR_PTR_SAMPLER;+ p.binding = ~0u;+ } else if (g->addrspace == 3) {+ /* a static threadgroup array */+ unsigned align = MAX2(g->align, air_type_abi_align(c->m, g->value_type));+ c->shared_size = ALIGN_POT(c->shared_size, MAX2(align, 1));+ p.class = AIR_PTR_SHARED;+ p.offset = nir_imm_int(&c->b, c->shared_size);+ c->shared_size += air_type_alloc_size(c->m, g->value_type);+ } else {+ /* a program-scope variable: private to the invocation, written by+ * the static initializers below+ */+ unsigned align = MAX2(g->align, air_type_abi_align(c->m, g->value_type));+ c->scratch_size = ALIGN_POT(c->scratch_size, MAX2(align, 1));+ p.class = AIR_PTR_SCRATCH;+ p.offset = nir_imm_int(&c->b, c->scratch_size);+ c->scratch_size += air_type_alloc_size(c->m, g->value_type);+ }+ air_set(c, &g->base, air_val_ptr(c, p));+ }+}++/* The functions of @llvm.global_ctors, inlined at the top of the entry point:+ * this is where a function constant turns into the program-scope variable the+ * body reads (AV1SW computes kPixelShift from kBitDepth that way).+ */+static void+run_static_initializers(struct air_ctx *c)+{+ for (unsigned i = 0; i < c->m->num_functions; i++) {+ const struct air_function *f = c->m->functions[i];+ if (f->is_declaration || !f->section || strcmp(f->section, "air.static_init"))+ continue;+ if (f->num_args || f->num_blocks != 1) {+ air_error(c, "interface: a static initializer with arguments or branches");+ return;+ }+ /* its instructions, in place, without its ret */+ const struct air_block *blk = &f->blocks[0];+ for (unsigned k = 0; k < blk->num_insts; k++) {+ const struct air_inst *in = blk->insts[k];+ if (in->op == AIR_OP_RET)+ continue;+ if (!translate_instruction(c, in))+ return;+ }+ }+}++/* -- the entry point ---------------------------------------------------- */++nir_shader *+air_to_nir(void *mem_ctx, const void *bitcode, size_t size, const char *entry_point,+ const struct air_to_nir_options *options,+ const nir_shader_compiler_options *nir_options,+ struct air_shader_info *info, const char **error)+{+ void *ctx = ralloc_context(mem_ctx);+ struct air_shader_info local_info = { 0 };+ struct air_ctx c = {+ .mem_ctx = ctx,+ .options = options,+ .info = info ? info : &local_info,+ };+ memset(c.info, 0, sizeof(*c.info));++ const char *read_error = NULL;+ c.m = air_module_read(ctx, bitcode, size, &read_error);+ if (!c.m) {+ if (error)+ *error = ralloc_asprintf(mem_ctx, "reader: %s", read_error);+ ralloc_free(ctx);+ return NULL;+ }++ const struct air_md *entry = NULL;+ int stage = module_stage(c.m, &entry);+ if (stage == -2) {+ if (error)+ *error = ralloc_strdup(mem_ctx, "stage: no entry point metadata");+ ralloc_free(ctx);+ return NULL;+ }+ if (stage == MESA_SHADER_NONE) {+ /* air.visible: a library function, linked into its caller at pipeline+ * time (docs/air.md section 7.5). Not an entry point, so not a shader.+ */+ if (error)+ *error = ralloc_strdup(mem_ctx, "stage: air.visible, a library function (not yet)");+ ralloc_free(ctx);+ return NULL;+ }++ if (!entry->num_ops || !entry->ops[0] || entry->ops[0]->kind != AIR_MD_VALUE ||+ entry->ops[0]->value->kind != AIR_VALUE_FUNCTION) {+ if (error)+ *error = ralloc_strdup(mem_ctx, "stage: entry point metadata without a function");+ ralloc_free(ctx);+ return NULL;+ }+ const struct air_function *fn = (const struct air_function *)entry->ops[0]->value;+ if (entry_point && strcmp(entry_point, fn->base.name ? fn->base.name : "")) {+ if (error)+ *error = ralloc_asprintf(mem_ctx, "stage: this module's entry point is %s",+ fn->base.name);+ ralloc_free(ctx);+ return NULL;+ }+ if (fn->is_declaration) {+ if (error)+ *error = ralloc_strdup(mem_ctx, "stage: the entry point has no body");+ ralloc_free(ctx);+ return NULL;+ }+ c.fn = fn;++ c.nir = nir_shader_create(mem_ctx, stage, nir_options, NULL);+ c.nir->info.name = ralloc_strdup(c.nir, fn->base.name ? fn->base.name : "air");+ c.nir->info.internal = false;+ nir_function *main = nir_function_create(c.nir, "main");+ main->is_entrypoint = true;+ c.b = nir_builder_at(nir_before_impl(nir_function_impl_create(main)));+ c.b.impl->structured = false;++ c.values = _mesa_pointer_hash_table_create(ctx);+ c.globals = _mesa_pointer_hash_table_create(ctx);+ c.blocks = _mesa_pointer_hash_table_create(ctx);+ c.phi_cursors = _mesa_pointer_hash_table_create(ctx);+ c.phi_regs = _mesa_pointer_hash_table_create(ctx);+ c.num_params = fn->num_args;+ c.params = rzalloc_array(ctx, struct air_val *, MAX2(c.num_params, 1));++ c.info->stage = stage;+ c.info->entry_point = fn->base.name;++ /* the outputs: fields of the returned struct, in order */+ const struct air_md *out_node = entry->num_ops > 1 ? entry->ops[1] : NULL;+ const struct air_type *rt = fn->fn_type->elem;+ unsigned num_fields = rt->kind == AIR_TYPE_STRUCT ? rt->num_members :+ rt->kind == AIR_TYPE_VOID ? 0 : 1;+ c.num_outputs = num_fields;+ c.outputs = rzalloc_array(ctx, __typeof__(*c.outputs), MAX2(num_fields, 1));++ unsigned next_out_varying = 0, next_in_varying = 0;+ if (out_node && out_node->num_ops != num_fields && num_fields) {+ air_error(&c, "interface: %u outputs for %u result fields", out_node->num_ops,+ num_fields);+ } else {+ for (unsigned i = 0; i < num_fields && !c.error[0]; i++) {+ const struct air_type *ft = rt->kind == AIR_TYPE_STRUCT ? rt->members[i] : rt;+ if (!out_node || i >= out_node->num_ops || !out_node->ops[i]) {+ air_error(&c, "interface: result field %u has no metadata", i);+ break;+ }+ translate_output(&c, out_node->ops[i], i, ft, &next_out_varying);+ }+ }++ /* the inputs */+ const struct air_md *in_node = entry->num_ops > 2 ? entry->ops[2] : NULL;+ for (unsigned i = 0; i < (in_node ? in_node->num_ops : 0) && !c.error[0]; i++)+ translate_input(&c, in_node->ops[i], &next_in_varying);++ /* the entry point's parameters, as the body will read them */+ for (unsigned i = 0; i < c.num_params && !c.error[0]; i++) {+ if (c.params[i])+ air_set(&c, &fn->args[i], c.params[i]);+ else+ air_error(&c, "interface: parameter %u has no metadata", i);+ }++ if (!c.error[0])+ translate_globals(&c);+ if (!c.error[0])+ run_static_initializers(&c);++ if (!c.error[0])+ translate_body(&c);++ if (c.error[0]) {+ if (error)+ *error = ralloc_strdup(mem_ctx, c.error);+ ralloc_free(c.nir);+ ralloc_free(ctx);+ return NULL;+ }++ /* What the shader expects to be bound, as NIR counts it: Metal's indices+ * are the binding numbers, so a shader using [[buffer(14)]] alone still+ * declares fifteen UBOs. ir3 and NIR's own passes read these.+ */+ for (unsigned i = 0; i < c.info->num_resources; i++) {+ const struct air_resource *r = &c.info->resources[i];+ switch (r->kind) {+ case AIR_RESOURCE_CONSTANT_BUFFER:+ c.nir->info.num_ubos = MAX2(c.nir->info.num_ubos, r->index + 1);+ break;+ case AIR_RESOURCE_DEVICE_BUFFER:+ c.nir->info.num_ssbos = MAX2(c.nir->info.num_ssbos, r->index + 1);+ break;+ case AIR_RESOURCE_TEXTURE:+ c.nir->info.num_textures = MAX2(c.nir->info.num_textures, r->index + 1);+ BITSET_SET(c.nir->info.textures_used, r->index);+ break;+ case AIR_RESOURCE_IMAGE:+ c.nir->info.num_images = MAX2(c.nir->info.num_images, r->index + 1);+ BITSET_SET(c.nir->info.images_used, r->index);+ break;+ default:+ break;+ }+ }++ c.nir->scratch_size = c.scratch_size;+ c.nir->info.shared_size = c.shared_size;+ c.info->threadgroup_bytes = c.shared_size;+ c.nir->info.io_lowered = false;+ if (stage == MESA_SHADER_COMPUTE) {+ /* the threadgroup size is a dispatch argument, not a shader constant */+ c.nir->info.workgroup_size_variable = true;+ }++ nir_lower_goto_ifs(c.nir);+ nir_index_ssa_defs(nir_shader_get_entrypoint(c.nir));++ if (info) {+ /* the info's arrays live under mem_ctx, not under the scratch context */+ if (info->num_resources)+ info->resources = ralloc_memdup(mem_ctx, info->resources,+ info->num_resources * sizeof(*info->resources));+ if (info->num_varyings)+ info->varyings = ralloc_memdup(mem_ctx, info->varyings,+ info->num_varyings * sizeof(*info->varyings));+ info->entry_point = ralloc_strdup(mem_ctx, info->entry_point);+ }+ ralloc_free(ctx);+ if (error)+ *error = NULL;+ return c.nir;+}diff --git a/tools/mesa/air/meson.build b/tools/mesa/air/meson.buildnew file mode 100644index 0000000..4a6bff3--- /dev/null+++ b/tools/mesa/air/meson.build@@ -0,0 +1,45 @@+# Copyright © 2026 Darwin on redwood contributors+# SPDX-License-Identifier: MIT++# The AIR (Metal) frontend. In the Darwin on redwood repository this+# directory is tools/mesa/air, copied to src/compiler/air by the build+# scripts; tools/mesa/air.patch adds the subdir() that reaches it.++files_libair = files(+ 'air_bitcode.c',+ 'air_bitcode.h',+ 'air_layout.c',+ 'air_metallib.c',+ 'air_module.c',+ 'air_module.h',+ 'air_print.c',+ 'air_private.h',+ 'air_to_nir.c',+ 'air_intrinsics.c',+ 'nir_air.h',+)++libair = static_library(+ 'air',+ files_libair,+ include_directories : [inc_include, inc_src],+ c_args : [no_override_init_args],+ gnu_symbol_visibility : 'hidden',+ dependencies : [idep_nir, idep_mesautil],+ build_by_default : false,+)++idep_air = declare_dependency(+ dependencies : [idep_nir, idep_mesautil],+ link_with : libair,+ include_directories : include_directories('.'),+)++air2nir = executable(+ 'air2nir',+ files('air2nir.c'),+ dependencies : [dep_m, idep_air],+ include_directories : [inc_include, inc_src],+ build_by_default : false,+ install : false,+)diff --git a/tools/mesa/air/nir_air.h b/tools/mesa/air/nir_air.hnew file mode 100644index 0000000..c42a8b5--- /dev/null+++ b/tools/mesa/air/nir_air.h@@ -0,0 +1,135 @@+/*+ * Copyright © 2026 Darwin on redwood contributors+ * SPDX-License-Identifier: MIT+ */++/*+ * AIR -> NIR: Metal shaders (the LLVM bitcode inside a .metallib) into NIR.+ * See docs/air.md of Darwin on redwood for the design and the mapping+ * tables this follows.+ */++#ifndef NIR_AIR_H+#define NIR_AIR_H++#include <stdbool.h>+#include <stddef.h>+#include <stdint.h>++#include "compiler/shader_enums.h"++#ifdef __cplusplus+extern "C" {+#endif++typedef struct nir_shader nir_shader;+typedef struct nir_shader_compiler_options nir_shader_compiler_options;++/* -- the .metallib container ---------------------------------------------- */++struct air_metallib_function {+ const char *name;+ int type; /* the container's TYPE tag, see air_metallib_type_name() */+ const void *bitcode; /* the module, still in its 0x0B17C0DE wrapper */+ size_t bitcode_size;+};++struct air_metallib {+ unsigned version_major, version_minor;+ unsigned num_functions;+ struct air_metallib_function *functions;+};++bool air_metallib_parse(void *mem_ctx, const void *data, size_t size,+ struct air_metallib *lib, const char **error);+const char *air_metallib_type_name(int type);++/* -- what the translated shader expects of the runtime ---------------------- */++enum air_resource_kind {+ AIR_RESOURCE_CONSTANT_BUFFER, /* UBO at .index */+ AIR_RESOURCE_DEVICE_BUFFER, /* SSBO at .index */+ AIR_RESOURCE_THREADGROUP_BUFFER, /* sized at dispatch */+ AIR_RESOURCE_TEXTURE, /* sampler view at .index */+ AIR_RESOURCE_IMAGE, /* storage image at .index */+ AIR_RESOURCE_SAMPLER, /* sampler state at .index */+};++struct air_resource {+ enum air_resource_kind kind;+ unsigned index; /* Metal's [[buffer(n)]], [[texture(n)]], [[sampler(n)]] */+ unsigned size; /* air.buffer_size when given, else 0 */+ bool read, write;+ unsigned param; /* the entry point's parameter */+ const char *name; /* air.arg_name */+ const char *type_name;+};++struct air_varying {+ const char *name; /* the AIR name that links vertex to fragment */+ unsigned slot; /* gl_varying_slot assigned by the translator */+ unsigned components;+ bool flat, centroid, sample, no_perspective;+};++struct air_shader_info {+ gl_shader_stage stage; /* MESA_SHADER_NONE for an air.visible function */+ const char *entry_point;+ unsigned num_resources;+ struct air_resource *resources;+ unsigned num_varyings; /* vertex outputs or fragment inputs */+ struct air_varying *varyings;+ unsigned num_render_targets;+ unsigned threadgroup_bytes; /* static threadgroup memory */+};++/* -- the translator --------------------------------------------------------- */++struct air_constant_value {+ unsigned index; /* the function constant's index */+ uint64_t bits; /* its value, as the bits of its type */+};++struct air_to_nir_options {+ const struct air_constant_value *constants;+ unsigned num_constants;+};++/* Translates one AIR module (one function of a .metallib). entry_point may+ * be NULL: the module's own entry point is taken. On failure returns NULL+ * and sets *error (allocated under mem_ctx) to "<category>: <what>", where+ * the category is one of+ *+ * reader the bitcode could not be read+ * stage no entry point, or not one this translator knows+ * interface an entry-point metadata key not handled yet+ * instruction an LLVM instruction or form not handled yet+ * intrinsic an air.* (or llvm.*) function not handled yet+ *+ * so the corpus report can count them. *info, when non-NULL, describes what+ * the shader expects to be bound (allocated under mem_ctx).+ */+nir_shader *air_to_nir(void *mem_ctx, const void *bitcode, size_t size,+ const char *entry_point,+ const struct air_to_nir_options *options,+ const nir_shader_compiler_options *nir_options,+ struct air_shader_info *info, const char **error);++/* The function constants the module declares, with .bits zero: a caller+ * fills in the values it will specialize with. Returns how many there are.+ */+unsigned air_module_function_constants(void *mem_ctx, const void *bitcode, size_t size,+ struct air_constant_value **out);++/* What the module is, without translating it: the stage from its metadata+ * (MESA_SHADER_NONE for visible functions, -1 when unknown) and the air.*+ * functions it calls, NUL-separated in *calls.+ */+int air_module_stage(void *mem_ctx, const void *bitcode, size_t size, const char **calls,+ const char **error);++#ifdef __cplusplus+}+#endif++#endif /* NIR_AIR_H */diff --git a/tools/metallib.py b/tools/metallib.pyindex e9c2257..b96706e 100755--- a/tools/metallib.py+++ b/tools/metallib.py@@ -13,7 +13,11 @@ import osimport structimport sys-TYPES = {0: 'vertex', 1: 'fragment', 2: 'kernel', 3: 'visible', 4: 'intersection', 5: 'none'}+# The TYPE tag. Corrected against the metadata of all 456 modules: 4 is what+# the 135 stitchable functions of PortraitFilters carry, and every one of them+# says !air.visible, so 4 is "visible" and 3 is not.+TYPES = {0: 'vertex', 1: 'fragment', 2: 'kernel', 3: 'unqualified', 4: 'visible',+ 5: 'extern', 6: 'intersection'}def parse(path):