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
air: read both of LLVM's spellings of zero, so every entry point translates
vcvkk1253deb1bf53
diff --git a/README.md b/README.mdindex bd8c3d7..1e2fea8 100644--- a/README.md+++ b/README.md@@ -539,14 +539,15 @@ P3 поверхности кадров копировались, и этого| что | сколько из 456 || --- | --- || читает наш собственный читатель битового кода, побайтово как `llvm-dis` | 456 |-| транслируется в NIR и проходит `nir_validate` | 318 |-| компилируется ir3 в машинный код Adreno | 318 |+| транслируется в NIR и проходит `nir_validate` | 321 |+| компилируется ir3 в машинный код Adreno | 321 || совпадает с LLVM численно и **рисуется** (softpipe) | 255 || запущено на самом GPU телефона (Adreno 7c+ Gen 3, через `msm` в ядре): 7 отрисовкой, 44 диспатчем | **51** |-Из 321 точки входа (135 модулей — библиотечные функции `air.visible`, не точки входа) транслируется-318, то есть 99,1 %. Смысл каждой операции `air.*` взят из словаря самого компилятора Apple-(`AGXCompilerCore`, 137 строк-суффиксов), а не угадан — так нашлась и одна ошибка в наших догадках.+Это **все 321 точки входа** корпуса (остальные 135 модулей — библиотечные функции `air.visible`,+не точки входа): 271 фрагментный шейдер, 47 вычислительных ядер и 3 вершинных. Смысл каждой+операции `air.*` взят из словаря самого компилятора Apple (`AGXCompilerCore`, 137 строк-суффиксов),+а не угадан — так нашлась и одна ошибка в наших догадках.Операции проверены численно — на хосте: из 119 разных `air.*`, что встречаются в корпусе, 78 прогнаныпо одной против эталона вне этого дерева, 71 из них совпадает с функциями C на каждом из 45 697 случаев,@@ -645,7 +646,8 @@ P3 поверхности кадров копировались, и этогокоторая её и сдвинула.Чего нет: 64-битное слово состояния семплера (`constexpr sampler`) не разобрано;-из 47 вычислительных ядер Apple три отказаны передним концом (маска шаффла не константа);+из 47 вычислительных ядер Apple 44 отправлены на Adreno, а три стали транслироваться позже+измерения и прогона ещё не видели;`air.fast_pow` на Adreno даёт NaN при отрицательном основании, где softpipe даёт точное значение — постандарту это разрешено (`fast::` в Metal, как `native_` в OpenCL, вне своей области определения неопределены), но всякий шейдер корпуса, у которого основание может уйти ниже нуля, поведёт себя наdiff --git a/docs/air-report.md b/docs/air-report.mdindex e3c2100..69edb51 100644--- a/docs/air-report.md+++ b/docs/air-report.md@@ -11,15 +11,15 @@ correct**: correctness needs the CPU reference and a run on the GPU.| --- | --- | --- || container | 456 | 100% || reader | 456 | 100% |-| translate | 318 | 70% |-| ir3 | 318 | 70% |+| translate | 321 | 70% |+| ir3 | 321 | 70% |## By stage of the shader| what the module is | modules | translate | ir3 || --- | --- | --- | --- || fragment | 271 | 271 | 271 |-| kernel | 47 | 44 | 44 |+| kernel | 47 | 47 | 47 || vertex | 3 | 3 | 3 || visible | 135 | 0 | 0 |@@ -30,9 +30,9 @@ The container's TYPE tag agrees with the module's own metadata on 456 of 456; 0| library | modules | translate | ir3 || --- | --- | --- | --- || AppleMetalGLRenderer.bundle/default.metallib | 274 | 274 | 274 |-| PortraitFilters.cifilter/default.metallib | 36 | 35 | 35 |+| PortraitFilters.cifilter/default.metallib | 36 | 36 | 36 || PortraitFilters.cifilter/portrait_filters.metallib | 135 | 0 | 0 |-| VideoDecoders/AV1SW.metallib | 11 | 9 | 9 |+| VideoDecoders/AV1SW.metallib | 11 | 11 | 11 |## Modules that call no `air.*` at all@@ -43,7 +43,6 @@ The container's TYPE tag agrees with the module's own metadata on 456 of 456; 0| modules | where it stops || --- | --- || 135 | stage: air.visible, a library function (not yet) |-| 3 | instruction: a shuffle mask that is not constant |## The `air.*` functions the corpus callsdiff --git a/docs/air.md b/docs/air.mdindex d4ec465..8290b75 100644--- a/docs/air.md+++ b/docs/air.md@@ -20,8 +20,8 @@ Of the 456 modules of the device's system `.metallib` files (`tools/air/check.sh| | of 456 || --- | --- || read by our own bitcode reader, byte for byte as `llvm-dis` reads them | 456 |-| translated to NIR, passing `nir_validate` | 318 |-| compiled by ir3 into Adreno machine code | 318 |+| translated to NIR, passing `nir_validate` | 321 |+| compiled by ir3 into Adreno machine code | 321 || numerically identical to LLVM's own execution, and drawn | 255 || **run on the phone's GPU** — 7 drawn, 44 dispatched | **51** |@@ -313,10 +313,10 @@ functions and not entry points at all.they are evidence about is binding, descriptors and ir3's texture instructions — exactly whatthey were built to be — and silence about everything Metal's sampler state decides. Two modulesof the corpus declare a `constexpr sampler`; everywhere else the API supplies it.-- **A function of the module that takes a texture: done, and the diagnosis was the work.** Three- of the four such entry points now translate; the fourth stops on the non-constant shuffle mask- it would have stopped on anyway. The fix is a split of `translate_globals`, and arriving at it- took two reverts and three failed guesses, which is the part worth keeping.+- **A function of the module that takes a texture: done, and the diagnosis was the work.** All+ four such entry points translate — three with this fix, the fourth once the shuffle mask it also+ stopped on was decoded. The fix is a split of `translate_globals`, and arriving at it took two+ reverts and three failed guesses, which is the part worth keeping.A texture is not a value in this frontend: it is resolved at translation time into a binding,and `tex_handle` wants an `AIR_VAL_PTR` rather than an SSA def. So a pointer-class argument is@@ -349,22 +349,45 @@ functions and not entry points at all.| | on softpipe | **on the Adreno** || --- | --- | --- |- | dispatched and read back | 6 | **44** |- | softpipe's `nir_to_tgsi`: scratch and intrinsics it lacks | 38 | — |- | a shuffle mask that is not constant (a frontend limit) | 3 | 3 |+ | dispatched and read back | 6 | **44**, with 3 not yet run |+ | softpipe's `nir_to_tgsi`: scratch and intrinsics it lacks | 41 | — |+ | a shuffle mask our reader would not decode (ours, now fixed) | 0 | 0 || **crashed `air_run`** (a defect here, not a limit) | 0 | **0** |- **The deferred question is answered: ir3 runs them.** 38 kernels stopped at a software- rasteriser that has no scratch memory and lacks compute intrinsics; on the hardware 44 of the 47- dispatch and read their results back, and every one of the 23 that bind an image is among them.- The phone replaced softpipe and the column that was never ours emptied. The corpus report's- kernel row reads 44 of 47 through ir3 as well, stopping on the same three, so the compile and- the dispatch agree about which kernels are out of reach.+ The three in the last-but-one row were refused when the Adreno column was measured, so that+ column says 44 of 47 and not 47 of 47: they translate and ir3 compiles them now, and whether+ they dispatch is a question for the next run rather than a figure to carry forward. Two of the+ three read and write textures, which is the shape that crashed before the sampler fix, so the+ run is worth more than a tick.++ **The deferred question is answered: ir3 runs them.** 41 kernels stop at a software rasteriser+ that has no scratch memory and lacks compute intrinsics; on the hardware 44 of the 47 dispatch+ and read their results back, and every one of the 23 that bind an image is among them. The phone+ replaced softpipe and the column that was never ours emptied. **All 47 now translate and compile+ through ir3** — so does every other entry point of the corpus — and the only column with a gap+ left in it is the one the phone fills.What the rows do **not** say is right. There is no executed reference for these kernels- anywhere: softpipe refuses 38 of them, which is why they came here, so a number out of the+ anywhere: softpipe refuses 41 of them, which is why they came here, so a number out of theAdreno has nothing on this machine to disagree with. 44 have been shown to *run*.+ **The last row was blaming the shader for our own gap.** "A shuffle mask that is not constant"+ was impossible as written: LLVM requires a `shufflevector` mask to be constant, so the message+ was describing something that cannot occur. What the three kernels actually carry is a mask like+ `<i32 0, i32 poison, i32 1, i32 poison>` — the shape a Metal `half2`-to-`half4` widening+ compiles to — and in it the zero is written `CST_CODE_NULL`, not `CST_CODE_INTEGER 0`, because+ that is how LLVM stores every zero of a scalar type. A mask is stored as an aggregate of+ element constants rather than as plain data exactly when one lane is poison, so those two+ encodings meet only in this case, and our reader accepted only the second. We refused on a zero+ we could read perfectly well, and recorded it as a limit of the shader.++ The fix is not three cases but one: `air_const_as_uint` (`air_module.h`) reads either spelling,+ and the three other places that took an integer constant off a record — `llvm.memcpy` and+ `llvm.memset` lengths, `air.wg.barrier` flags — now go through it. None of those three was+ reachable in this corpus, so this is not a correction of any number; it closes a class. Two+ spellings of zero is a property of the format, and a format detail belongs in one decoder+ rather than in every reader of it.+The four that used to crash now dispatch, and the crash was this harness's:void *csampler = NULL;@@ -416,7 +439,8 @@ functions and not entry points at all.which arrives feeling like diligence and is rarely re-checked against the same evidence.The row for a call of a module-local function was 5 until those calls were translated; it is now- gone, its five having moved to softpipe (four) and the shuffle mask (one). Twice in a row the+ gone, its five having moved to softpipe (four) and the shuffle mask (one) — and that last one+ moved again when the mask was decoded, so all five are softpipe's. Twice in a row thedispatched count on softpipe stayed at 6 while a column stopped being ours, and the run above iswhere that finally paid: those same kernels dispatch on the hardware. Until 20 October, 24 of these wererefused by `air_run` itself — it bound textures and images for a draw and not for a dispatch —diff --git a/tools/mesa/air/air_intrinsics.c b/tools/mesa/air/air_intrinsics.cindex 4676444..107acac 100644--- a/tools/mesa/air/air_intrinsics.c+++ b/tools/mesa/air/air_intrinsics.c@@ -412,8 +412,7 @@ barrier_op(struct air_ctx *c, const struct air_inst *in)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;+ air_const_as_uint(k, &flags); /* leaves flags alone when it is not readable */nir_variable_mode modes = 0;if (flags & 1)@@ -447,14 +446,15 @@ llvm_op(struct air_ctx *c, const struct air_inst *in, const char *name)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)+ uint64_t bytes;+ if (!air_const_as_uint(len, &bytes))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) {+ if (bytes % 4)+ return air_error(c, "intrinsic: memcpy of %u bytes", (unsigned)bytes);+ for (uint64_t off = 0; off < bytes; 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 };@@ -472,13 +472,14 @@ llvm_op(struct air_ctx *c, const struct air_inst *in, const char *name)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)+ uint64_t bytes;+ if (!air_const_as_uint(len, &bytes) || bytes % 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) {+ for (uint64_t off = 0; off < bytes; 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;diff --git a/tools/mesa/air/air_module.h b/tools/mesa/air/air_module.hindex 7ea7c95..e791e6f 100644--- a/tools/mesa/air/air_module.h+++ b/tools/mesa/air/air_module.h@@ -316,6 +316,32 @@ air_value_as_constant(const struct air_value *v)return v && v->kind == AIR_VALUE_CONSTANT ? (const struct air_constant *)v : NULL;}+/* An integer constant's value, whichever way the writer spelled it.+ *+ * LLVM has two encodings for a zero of a scalar type: CST_CODE_INTEGER with a+ * value of 0, and CST_CODE_NULL. Which one a module uses is not free -- a zero+ * that appears inside an aggregate constant is always NULL -- so anything that+ * reads an integer constant has to accept both. Taking only INTEGER is why+ * three of Apple's kernels stopped on a shuffle mask whose first lane was 0,+ * and the same trap sits under every other reader of a constant integer.+ */+static inline bool+air_const_as_uint(const struct air_constant *c, uint64_t *out)+{+ if (!c)+ return false;+ if (c->ckind == AIR_CONST_INT) {+ *out = c->u;+ return true;+ }+ if (c->ckind == AIR_CONST_NULL && c->base.type &&+ c->base.type->kind == AIR_TYPE_INT) {+ *out = 0;+ return true;+ }+ return false;+}+static inline const struct air_inst *air_value_as_inst(const struct air_value *v){diff --git a/tools/mesa/air/air_to_nir.c b/tools/mesa/air/air_to_nir.cindex 9011bcf..61cbc0e 100644--- a/tools/mesa/air/air_to_nir.c+++ b/tools/mesa/air/air_to_nir.c@@ -1040,6 +1040,40 @@ clone_val(struct air_ctx *c, const struct air_val *v)return n;}+/* What a value turned out to be, for a message that has to be read without the+ * module in hand. A refusal that only says "not constant" sends the reader to+ * llvm-dis to find out which of six things it was, and the three kernels that+ * stopped on a shuffle mask cost exactly that detour.+ */+static const char *+air_value_kind_name(const struct air_value *v)+{+ if (!v)+ return "nothing";+ const struct air_constant *c = air_value_as_constant(v);+ if (!c) {+ switch (v->kind) {+ case AIR_VALUE_GLOBAL: return "a global";+ case AIR_VALUE_FUNCTION: return "a function";+ case AIR_VALUE_ARGUMENT: return "a function argument";+ case AIR_VALUE_INSTRUCTION: return "an instruction";+ case AIR_VALUE_METADATA: return "metadata";+ default: return "a value of an unknown kind";+ }+ }+ switch (c->ckind) {+ case AIR_CONST_INT: return "an integer";+ case AIR_CONST_FLOAT: return "a float";+ case AIR_CONST_NULL: return "zeroinitializer";+ case AIR_CONST_UNDEF: return "undef";+ case AIR_CONST_POISON: return "poison";+ case AIR_CONST_AGGREGATE: return "an aggregate of constants";+ case AIR_CONST_DATA: return "a vector of plain integers";+ case AIR_CONST_EXPR: return "a constant expression";+ }+ return "a constant of an unknown kind";+}+static booltranslate_instruction(struct air_ctx *c, const struct air_inst *in){@@ -1110,17 +1144,28 @@ translate_instruction(struct air_ctx *c, const struct air_inst *in)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 &&+ /* The mask is an aggregate rather than plain data whenever a lane+ * is poison, so <i32 0, i32 poison, ...> -- what a Metal+ * half2-to-half4 widening compiles to -- mixes LLVM's two+ * spellings of a constant integer. air_const_as_uint reads both.+ */+ uint64_t lane = 0;+ bool have = e && air_const_as_uint(e, &lane);+ if (!e || (!have && 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;+ return air_error(c, "instruction: element %u of a shuffle mask is %s",+ i, air_value_kind_name(mk->elems[i]));+ undef = !have;+ sel = have ? (int32_t)lane : 0;} 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");+ return air_error(c, "instruction: a shuffle mask that is %s, with %u of the "+ "%u elements it needs",+ air_value_kind_name(in->operands[2]),+ mk ? mk->num_elems : 0, n);}if (undef) {comps[i] = nir_undef(&c->b, 1, x->bit_size);