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: run the operations as well as fold them, and three more fixes
vcvkk6109798515f9
diff --git a/docs/air.md b/docs/air.mdindex 7a347a2..5c4293e 100644--- a/docs/air.md+++ b/docs/air.md@@ -30,8 +30,9 @@ And of the 119 distinct `air.*` operations those modules call (`tools/air/intrin| | of 119 || --- | --- || checked numerically, one operation at a time, against a reference outside this tree | 78 |-| of those, exactly defined and agreeing on every case (44 028 cases) | 71 |+| of those, exactly defined and agreeing on every case (45 607 cases) | 71 || of those, approximate, so measured against libm and nothing concluded | 7 |+| of those, also *run* by a Gallium driver rather than folded (softpipe, 2 586 cases) | 47 || textures, atomics, barriers, derivatives and simd: no reference here | 41 |313 of 456 is 313 of 321 entry points — 97.5% — because 135 modules are `air.visible` library@@ -39,18 +40,22 @@ functions and not entry points at all.**What those numbers are not**, because they will be quoted without this paragraph otherwise:-- **The arithmetic operations are now checked; the reference is not the Adreno.** 71 of the- corpus's declarations agree with C's own functions on every one of 44 028 cases, which is a real- answer to what used to be the largest hole here (section 4, item 4). But what is folded is NIR's- constant expression for each opcode, on this machine — so an opcode whose Adreno instruction- differs from what `nir_opt_constant_folding` computes would be invisible to all 44 028 of them.- Nothing in this table's bottom row calls an `air.*` function: **no operation has been run on the- GPU.**+- **The arithmetic operations are now checked; nothing checked them against the Adreno.** 71 of+ the corpus's declarations agree with C's own functions on every one of 45 607 cases, and 47 of+ them agree again when *executed* by softpipe instead of folded — which is a real answer to what+ used to be the largest hole here (section 4, item 4), and found three bugs getting there. But+ both engines are on an x86 host. An opcode whose Adreno instruction differs from what+ `nir_opt_constant_folding` and TGSI compute is invisible to all 48 193 of those cases, and the+ 24 narrow-type declarations softpipe cannot run at all are exactly the ones where ir3 differs+ most from it. None of the seven shaders that have run on the phone calls an `air.*` function:+ **no operation has been run on the GPU.**- **Still unverified by anything: the atomics, the barrier, the derivatives and the simdreductions** — 41 declarations with no reference in `intrincheck.py`, because what they meandepends on more than one thread or on neighbouring fragments and a folded constant cannot sayit. The texture operations among them are covered differently and partly, by the six shaders- that returned the exact texel on the Adreno.+ that returned the exact texel on the Adreno. One thing *is* now settled about the atomics+ without running any: every one in the corpus asks for `memory_order_relaxed`, and the lowering+ refuses any other order by name instead of ignoring the argument, which it used to do.- **Nothing here tests Metal's own filtering or addressing.** The six texture shaders that drew onthe Adreno took their sampler from the API, which this harness chose: nearest, clamped, sampledat a texel centre. That is evidence about binding, descriptors and ir3's texture instructions —@@ -433,7 +438,7 @@ Three references, each independent of the translator:--eval`. The reference is the C library's own `roundf`, `floorf`, `fmaxf`, `ldexpf` and theIEEE definitions, evaluated at the operation's own precision.- **71 exactly defined operations agree on every one of 44 028 cases; none differ.** Seven are+ **71 exactly defined operations agree on every one of 45 607 cases; none differ.** Seven areapproximate (`fast_sin`, `fast_cos`, `fast_exp`, `fast_pow`, `fast_atan2`) and are reportedwith their worst distance from libm and counted as nothing — see below.@@ -473,10 +478,16 @@ Three references, each independent of the translator:`dst = ldexpf(src0, src1); /* flush denormals to zero. */ if (!isnormal(dst)) dst =copysignf(0.0f, src0);` — and `!isnormal` is true of an infinity as well as of a denormal, so`ldexp(0.5, 32767)` folds to `0` where Metal, OpenCL and C all say `+inf`. The comment names- denormals; the condition catches more than it means to. Found in Mesa 25.0.7, which is what- this port pins. **Not checked against Mesa main** — freedesktop's GitLab is behind bot- protection from here, so neither the file nor the 2020 merge request that looks like its- origin could be read. Worth reporting upstream by someone who can open the page; not worked+ denormals; the condition catches more than it means to. Present in Mesa 26.2.5, the newest+ release at the time of writing, byte for byte — checked by extracting that one file from+ `archive.mesa3d.org`, which is a plain file server, because freedesktop's GitLab is behind+ bot protection and the GitHub mirror paths 404. The merge request that looks like its origin+ is freedesktop 3982, "nir: Flush to zero with OOB low exponents in ldexp", whose title says+ both what it was for and what it missed: out-of-bounds *low* exponents, the high end never+ considered. The MR itself could not be read, so treat the origin as likely and the state of+ the current release as established. A one-line fix would be `isfinite(dst) && !isnormal(dst)`.+ Worth reporting upstream by someone who can open the page; it is a bug for every Mesa+ frontend whose language keeps IEEE overflow, which is OpenCL and Metal at least. Not workedaround here, because the frontend's `nir_ldexp` is the right opcode.**The check can fail,** which is the first thing to establish about any check in this@@ -487,6 +498,49 @@ Three references, each independent of the translator:of a vector argument is given a *different* value, because with the same value in all of them alowering that swizzled or dropped a component returns the right answer for the wrong reason.+ **Folded is not run, and the difference is not a matter of degree.** `--eval` asks NIR's+ constant folder; `intrincheck.py --run` builds the same operations into shaders that *load+ their arguments from a buffer* and hands them to `air_run`, which draws with them through a+ real driver's compilation and execution. The buffer is the whole point: ir3 folds too, so a+ shader calling `air.fast_round(0.5)` on an immediate is answered by the compiler and the+ hardware never sees the instruction — a GPU test built that way passes with the GPU switched+ off. A value loaded from a buffer cannot be folded, and `air_run` puts bytes the harness chose+ there (`AIR_RUN_BUFFER`, added for this).++ **47 of the 78 declarations agree on every one of 2 586 cases, run by softpipe rather than+ folded; none differ.** Seven more are the approximate ones. The remaining 24 touch a type+ narrower than 32 bits (`i1`, `i8`, `i16`, `f16`) and TGSI's registers are 32-bit, so softpipe+ cannot answer for them: `nir_to_tgsi` asserts for the integers, which is loud and fine, and+ for a half it computes at 32 bits instead — it answered `32767` where a half rounds to+ `32768`, which is a verdict about softpipe and not about this frontend. `--check` reads the+ screen out of `air_run`'s own first line and sets those aside by name. ir3 has real 16-bit+ registers, so they are a question for the phone and are open.++ Running them found two things the folding check could not, and could never have:++ - **`air.sign(-0)` gave `+0`.** Metal's `sign` is OpenCL's, where `sign(-0)` is `-0` and+ `sign(NaN)` is `+0`. `nir_fsign` does not promise either; its own documentation says that+ for a zero source "there is a preference for the result to have the same sign, but this is+ not required (it is required by OpenCL)". So a backend is licensed to lose it, NIR's+ *constant folder* happens not to, and softpipe does — which is exactly why folding the+ shader could not show it. Same shape as the atan2 bug: an opcode whose contract is weaker+ than Metal's requirement. `air_intrinsics.c` now builds `sign` from comparisons, which+ promise what Metal needs, rather than asking for a preference.+ - **The 16-bit gap above, which is softpipe's and not ours** — but it took a wrong answer+ (`32767` for a half that rounds to `32768`) to notice, not an assertion, and a check that+ had trusted the number would have recorded a frontend bug that does not exist.++ **It has not run on the phone.** `--emit DIR` writes the modules, the bytes for their input+ buffer, a `manifest.json` of what each should return, and a `run.sh` that uses only `for`,+ `echo` and shell parameter expansion — no `sed`, no `paste` — because what runs it is a Darwin+ userland and not this machine's shell. `--check DIR LOG` then judges the log wherever it was+ produced, so the arithmetic reference never leaves the host and the device needs nothing but+ `air_run`. `--cases 4` cuts it to 211 modules and 1.7 MB, which is carryable. What is missing+ is only the carrying: getting that directory into the boot image is the flash-root machinery of+ subsystem (2), which this work is not supposed to touch, and the phone was held by another+ session all night. **So every number above is from an x86 host, and the bottom row of the+ table at the top of this document still reads 7.**+Where a shader has a known GLSL equivalent (AppleMetalGLRenderer's shaders *are* the GLpipeline's fixed functions), rendering both through the port's GLES and comparing images is afourth check; it is not built yet.@@ -810,7 +864,10 @@ build/mesa-host/build/src/gallium/drivers/freedreno/ir3_compiler \--chip-id 0x007506030500 FILE[.metallib] [FUNCTION] # Adreno codetools/air/cpuref.py --compare FILE[.metallib] [FUNCTION] # ours against LLVM's own answertools/air/cpuref.py --all --draw FILE.metallib # every function: LLVM, folded, drawn-tools/air/intrincheck.py [-v] [OP ...] # one air.* operation at a time+tools/air/intrincheck.py [-v] [OP ...] # one air.* operation at a time, folded+tools/air/intrincheck.py --run --few [OP ...] # the same, drawn by a real driver+tools/air/intrincheck.py --emit DIR --few # modules + inputs + run.sh, to carry+tools/air/intrincheck.py --check DIR RUN.LOG # judge what the runner printedbuild/mesa-host/build/src/gallium/drivers/freedreno/air_run \FILE[.metallib] [FUNCTION] # draw with it, print the pixeltools/air/texcheck.sh [FILE.metallib ...] # every texture shader, the texel it returns@@ -820,11 +877,18 @@ tools/air/texcheck.sh [FILE.metallib ...] # every texture shadeit checks only those, which is how it is used while changing a lowering:`tools/air/intrincheck.py atan2`.+`--run` is the same operations *executed* instead of folded, and it is a different check, not a+slower one — section 4 item 4 says what each can see that the other cannot. `--emit` writes the+modules, the bytes for their input buffer, a `manifest.json` of what each should return and a+`run.sh` that uses only `for`, `echo` and parameter expansion, because what runs it may be the+phone's Darwin userland and not this machine's shell. `--check` then judges the log wherever it+was produced: the arithmetic reference never leaves the host.+`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 about four minutes, most of it the per-operation check, so it runs before every commit that touches+GitHub). `check.sh` is the CI; it takes about five minutes, most of it the two per-operation checks, so it runs before every commit that touchesthe frontend, and the report it writes is committed as `docs/air-report.md` with the numbers ofthat commit.diff --git a/tools/air/check.sh b/tools/air/check.shindex 22301f8..53621bf 100755--- a/tools/air/check.sh+++ b/tools/air/check.sh@@ -78,4 +78,18 @@ echo "== the air.* operations, one at a time"python3 "$ROOT/tools/air/intrincheck.py" 2>&1 | tail -8intrin_rc=${PIPESTATUS[0]}-exit $((reader_rc | cpu_rc | intrin_rc))+echo+echo "== the same operations run, not folded"+# A different check and not a slower one: folding asks NIR's constant+# expression, this builds the arguments into a buffer so nothing can be folded+# and hands the shader to a driver that compiles and executes it. That is how+# air.sign(-0) was caught -- NIR's folder keeps the sign of a zero, softpipe+# does not, and nir_fsign promises neither.+#+# --cases 4 and not the whole pool: 612 cases in 79 seconds against 2586 in+# 300, and it still catches that bug, which is how the subset was chosen rather+# than guessed. The full run is `intrincheck.py --run --few`.+python3 "$ROOT/tools/air/intrincheck.py" --run --cases 4 2>&1 | tail -6+run_rc=${PIPESTATUS[0]}++exit $((reader_rc | cpu_rc | intrin_rc | run_rc))diff --git a/tools/air/intrincheck.py b/tools/air/intrincheck.pyindex 2d80367..feb2669 100755--- a/tools/air/intrincheck.py+++ b/tools/air/intrincheck.py@@ -42,9 +42,13 @@ What this does NOT prove, and no amount of it will:- Denormals. Apple compiles with air.compile.denorms_disable, so thehardware may flush where this check does not. Inputs are kept normal.-usage: intrincheck.py [-v] [--decls FILE] [OP ...]+usage: intrincheck.py [-v] [--decls FILE] [OP ...] fold it, exhaustively+ intrincheck.py --run [--few] [--cases N] [OP ...] run it through a real driver+ intrincheck.py --emit DIR [--few] [--cases N] write it out to carry somewhere+ intrincheck.py --check DIR RUN.LOG judge what the runner printed"""+import jsonimport mathimport osimport re@@ -230,6 +234,57 @@ def _powr(x, y):return math.pow(x, y)+# Python raises where C returns a value. Metal's math functions are OpenCL's,+# which keep the IEEE results at the edge of the domain, so raising here would+# silently drop the cases that matter most -- it had already dropped every case+# of air.fast_sqrt.v4f32, whose rotated components always include a negative.+def _sqrt(x):+ if math.isnan(x):+ return x+ return float("nan") if x < 0 else math.sqrt(x) # sqrt(-0) is -0+++def _log(f, zero):+ def g(x):+ if math.isnan(x):+ return x+ if x == 0.0:+ return zero+ return float("nan") if x < 0 else f(x)+ return g+++def _rsqrt(x):+ if math.isnan(x):+ return x+ if x == 0.0:+ return math.copysign(float("inf"), x)+ return float("nan") if x < 0 else 1.0 / math.sqrt(x)+++def _fmod(x, y):+ if y == 0.0 or math.isnan(x) or math.isnan(y) or math.isinf(x):+ return float("nan")+ return math.fmod(x, y)+++def _pow(x, y):+ # C: pow(+-0, y) for a negative odd integer y is +-inf, keeping the zero's+ # sign; for any other negative y it is +inf. Python raises for both, and+ # the fallback that guessed +inf made the shader's correct -inf for+ # pow(-0, -1) look like an infinite-ulp disagreement.+ if x == 0.0 and y < 0:+ odd = y == int(y) and int(y) % 2 != 0+ return math.copysign(float("inf"), x) if odd else float("inf")+ try:+ return math.pow(x, y)+ except ValueError:+ return float("nan") # x < 0 with a fractional y+ except OverflowError:+ return math.copysign(float("inf"), x if x < 0 and y == int(y)+ and int(y) % 2 != 0 else 1.0)++def _ldexp(x, n):try:return math.ldexp(x, n)@@ -252,10 +307,10 @@ OPS = {"fmax": (2, _fmax, True),"clamp": (3, _clamp_f, True),"mix": (3, _mix, True),- "fmod": (2, math.fmod, True),- "mod": (2, math.fmod, True),+ "fmod": (2, _fmod, True),+ "mod": (2, _fmod, True),"divide": (2, lambda a, b: a / b if b else math.copysign(float("inf"), a) if a else float("nan"), True),- "sqrt": (1, math.sqrt, True), # IEEE: exactly rounded+ "sqrt": (1, _sqrt, True), # IEEE: exactly rounded"fma": (3, lambda a, b, c: math.fma(a, b, c), True),"ldexp": (2, _ldexp, True),# approximate: the reference is libm, the shader is allowed to differ@@ -266,12 +321,12 @@ OPS = {"exp": (1, math.exp, False),"exp2": (1, lambda x: math.pow(2.0, x), False),"exp10": (1, lambda x: math.pow(10.0, x), False),- "log": (1, math.log, False),- "log2": (1, math.log2, False),- "log10": (1, math.log10, False),- "pow": (2, math.pow, False),+ "log": (1, _log(math.log, float("-inf")), False),+ "log2": (1, _log(math.log2, float("-inf")), False),+ "log10": (1, _log(math.log10, float("-inf")), False),+ "pow": (2, _pow, False),"powr": (2, _powr, False),- "rsqrt": (1, lambda x: 1.0 / math.sqrt(x), False),+ "rsqrt": (1, _rsqrt, False),}# integer operations, by (base name, signed)@@ -451,6 +506,142 @@ define <{ <4 x %(outty)s> }> @ic() local_unnamed_addr {!6 = !{}"""+# The same shader with its arguments read from a constant buffer instead of+# written in as immediates. That is the only form worth running on a GPU: ir3+# folds, so air.fast_round(0.5) written as a constant is answered by the+# compiler and the hardware never sees the instruction -- the test would pass+# with the GPU switched off. A value loaded from a buffer cannot be folded, and+# air_run puts bytes we choose there (AIR_RUN_BUFFER).+BUF_SKELETON = """source_filename = "ic"+target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32"+target triple = "air64-apple-ios16.5.0"++%(decl)s++define <{ <4 x %(outty)s> }> @ic(ptr addrspace(2) %%in) local_unnamed_addr {+%(body)s+ %%r = insertvalue <{ <4 x %(outty)s> }> undef, <4 x %(outty)s> %%v3, 0+ ret <{ <4 x %(outty)s> }> %%r+}++!llvm.module.flags = !{!0}+!air.version = !{!1}+!air.language_version = !{!2}+!air.fragment = !{!3}++!0 = !{i32 1, !"wchar_size", i32 4}+!1 = !{i32 2, i32 5, i32 0}+!2 = !{!"Metal", i32 3, i32 0, i32 0}+!3 = !{ptr @ic, !4, !6}+!4 = !{!5}+!5 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"%(outname)s", !"air.arg_name", !"out"}+!6 = !{!7}+!7 = !{i32 0, !"air.buffer", !"air.buffer_size", i32 4096, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"float", !"air.arg_name", !"in"}+"""++# One case's arguments occupy MAXARG * 4 four-byte slots of that buffer, so a+# component's address is arithmetic on its indices and nothing has to be packed+# tightly.+MAXARG = 3+SLOTS_PER_ARG = 4+SLOTS_PER_CASE = MAXARG * SLOTS_PER_ARG+++def slot_bytes(bty, v):+ """One four-byte slot holding `v` as type `bty`, little-endian.++ A narrow type is written into the low bytes of its slot, which is where a+ little-endian load of that width at a four-byte-aligned address reads it.+ """+ if bty == "float":+ return struct.pack("<f", f32(v))+ if bty == "half":+ h = f16(v)+ b = (struct.pack("<H", 0x7C00 if h > 0 else 0xFC00) if math.isinf(h)+ else struct.pack("<e", h))+ return b + b"\0\0"+ if bty == "double":+ return struct.pack("<d", v)[:4]+ w = int(bty[1:])+ if w == 1:+ return struct.pack("<B", 1 if v else 0) + b"\0\0\0"+ return struct.pack("<i", wrap(v, 32, True) if w >= 32+ else wrap(v, w, True) & ((1 << w) - 1))+++def emit_buffered(decl, name, argtys, retty, cases, signed):+ """The .ll of a shader that loads its arguments, and the bytes to load.++ Returns (source, input bytes). The caller assembles the source and gives+ the bytes to air_run.+ """+ rty, rn = parse_type(retty)+ outty = "float" if rty in ("float", "half", "double") else "i32"+ outname = "float4" if outty == "float" else "int4"++ data = bytearray()+ lines = []+ slots = []+ for i, args in enumerate(cases):+ while len(data) < (i + 1) * SLOTS_PER_CASE * 4:+ data += b"\0\0\0\0"+ argvals = []+ for j, (ty, v) in enumerate(zip(argtys, args)):+ bty, bn = parse_type(ty)+ comps = []+ for c in range(bn):+ slot = i * SLOTS_PER_CASE + j * SLOTS_PER_ARG + c+ data[slot * 4:slot * 4 + 4] = slot_bytes(bty, v[c])+ nm = "%%l%d_%d_%d" % (i, j, c)+ lines.append(" %sp = getelementptr inbounds i8, "+ "ptr addrspace(2) %%in, i64 %d" % (nm, slot * 4))+ lines.append(" %s = load %s, ptr addrspace(2) %sp, align 4"+ % (nm, bty, nm))+ comps.append(nm)+ if bn == 1:+ argvals.append("%s %s" % (bty, comps[0]))+ else:+ prev = "undef"+ for c, nm in enumerate(comps):+ vv = "%%g%d_%d_%d" % (i, j, c)+ lines.append(" %s = insertelement <%d x %s> %s, %s %s, i32 %d"+ % (vv, bn, bty, prev, bty, nm, c))+ prev = vv+ argvals.append("<%d x %s> %s" % (bn, bty, prev))++ lines.append(" %%c%d = call %s @%s(%s)"+ % (i, retty, name, ", ".join(argvals)))+ for k in range(rn):+ s_ = "%%c%d" % i+ if rn > 1:+ s_ = "%%e%d_%d" % (i, k)+ lines.append(" %s = extractelement %s %%c%d, i32 %d"+ % (s_, retty, i, k))+ if rty == "half":+ lines.append(" %%f%d_%d = fpext half %s to float" % (i, k, s_))+ s_ = "%%f%d_%d" % (i, k)+ elif rty in ("i1", "i8", "i16") and outty == "i32":+ lines.append(" %%f%d_%d = %s %s %s to i32"+ % (i, k, "sext" if signed else "zext", rty, s_))+ s_ = "%%f%d_%d" % (i, k)+ elif rty == "i64" and outty == "i32":+ lines.append(" %%f%d_%d = trunc i64 %s to i32" % (i, k, s_))+ s_ = "%%f%d_%d" % (i, k)+ slots.append(s_)++ pad = "0.0" if outty == "float" else "0"+ packed = (slots + [pad] * 4)[:4]+ prev = "undef"+ for i, s_ in enumerate(packed):+ lines.append(" %%v%d = insertelement <4 x %s> %s, %s %s, i32 %d"+ % (i, outty, prev, outty, s_, i))+ prev = "%%v%d" % i++ return (BUF_SKELETON % dict(decl=decl, outty=outty, outname=outname,+ body="\n".join(lines)),+ bytes(data))++def fconst(ty, x):"""A float constant LLVM will read back bit-for-bit."""@@ -576,7 +767,36 @@ def base_and_sign(name):DOT_FLOATS = [0.0, 1.0, -1.0, 2.0, 3.0, -4.0, 0.5, -0.25, 8.0, -16.0]-def pool_for(ty, family):+# A short pool, for the run on real hardware: 300 ms a module here and more on+# the phone, so the full cross product is 12 031 modules and an hour. What the+# GPU run has to establish is that each operation *executes* correctly, not the+# input coverage -- the folding check above already does the grid exhaustively.+# So these are the values that have actually broken something: both zeros, the+# half-way cases that separate round from rint, the largest float below a half,+# and the integer extremes.+FEW_FLOATS = [0.0, -0.0, 0.5, -0.5,+ struct.unpack("<f", struct.pack("<I", 0x3EFFFFFF))[0],+ 2.5, -2.5, 3.7]+FEW_FLOATS2 = [1.0, -1.0, 0.0, 0.25]+FEW_INTS = [0, 1, -1, 7, -32768, 32767, 2147483647, -2147483648]+FEW_INTS2 = [1, -1, 0, 7]+FEW_DOT = [0.0, 1.0, -1.0, 2.0, -4.0, 0.5, -0.25, 8.0]+++def pool_for(ty, family, few=False, nth=0):+ if few:+ bty, _ = parse_type(ty)+ if bty == "i1":+ return [0, 1]+ if bty.startswith("i"):+ return FEW_INTS if nth == 0 else FEW_INTS2+ if family == "dot":+ return FEW_DOT+ return FEW_FLOATS if nth == 0 else FEW_FLOATS2+ return pool_for_full(ty, family)+++def pool_for_full(ty, family):bty, _ = parse_type(ty)if bty == "i1":return [0, 1]@@ -585,7 +805,7 @@ def pool_for(ty, family):return DOT_FLOATS if family == "dot" else FLOATS-def inputs_for(argtys, family):+def inputs_for(argtys, family, few=False, cases=0):"""The cases to try: one list per argument, holding its components.Every component of a vector argument gets a different value. With the same@@ -593,14 +813,20 @@ def inputs_for(argtys, family):one, or swizzled, would return the right answer for the wrong reason --which is the mistake this port has already made four times with textures."""- pools = [pool_for(t, family) for t in argtys]+ pools = [pool_for(t, family, few, n) for n, t in enumerate(argtys)]widths = [parse_type(t)[1] for t in argtys]# the whole pool for the first argument, less of it for the others, or a# three-argument operation is tens of thousands of shader builds- limits = [len(pools[0])]- limits += [min(12, len(p)) for p in pools[1:2]]- limits += [min(6, len(p)) for p in pools[2:]]+ # --cases N takes the first N of the first argument's pool and narrows the+ # others with it: that is how a suite small enough to carry to the phone is+ # cut, and the values are still in the order of how dangerous they are+ first = min(cases, len(pools[0])) if cases else len(pools[0])+ limits = [first]+ limits += [min(max(1, first // 2) if cases else (4 if few else 12), len(p))+ for p in pools[1:2]]+ limits += [min(max(1, first // 4) if cases else (2 if few else 6), len(p))+ for p in pools[2:]]grid = [()]for lim in limits:@@ -643,10 +869,272 @@ def ulps(a, b):return abs(ia - ib)+# ---------------------------------------------------------------------------+# the same operations, run rather than folded+#+# --emit writes a directory of modules whose arguments come from a buffer, the+# bytes for that buffer, and a runner that needs only `for`, `echo` and+# parameter expansion -- the phone's userland is not this machine's. --check+# reads what the runner printed, wherever it ran, and compares it with the+# expectations in the manifest. --run does both here, through softpipe, which+# is already a second engine: softpipe executes TGSI, so a disagreement between+# it and air2nir --eval is NIR's constant folder against nir_to_tgsi and the+# answer is not pre-decided by either.++RUNNER = """#!/bin/sh+# Run every generated module and print its whole output after a marker line.+# Parsing happens on the host (intrincheck.py --check); this stays dumb on+# purpose, because what is here may be a Darwin userland with no sed or paste.+D=`dirname "$0"`+AIR_RUN=${AIR_RUN:-$D/air_run}+for bc in "$D"/*.bc; do+ id=${bc##*/}+ id=${id%.bc}+ echo "=== $id"+ AIR_RUN_BUFFER="$D/$id.bin" "$AIR_RUN" "$bc" 2>&1+done+"""+++def emit_suite(arith, outdir, want, verbose, few=False, cases=0):+ """Write the modules, their inputs, the manifest and the runner."""+ os.makedirs(outdir, exist_ok=True)+ manifest = []+ n = 0+ for d, name, retty, argtys, op, plain, sign, family in arith:+ if want and not any(w in name for w in want):+ continue+ rn = parse_type(retty)[1]+ per_shader = max(1, 4 // rn)+ cases_l = inputs_for(argtys, family, few, cases)+ for k in range(0, len(cases_l), per_shader):+ batch = cases_l[k:k + per_shader]+ expect = []+ keep = []+ for args in batch:+ try:+ expect.append(reference(family, plain, name, args, argtys,+ retty, True if sign is None else sign))+ keep.append(args)+ except (ValueError, OverflowError, ZeroDivisionError):+ pass+ if not keep:+ continue+ src, data = emit_buffered(d, name, argtys, retty, keep, sign)+ ident = "%04d" % n+ ll = os.path.join(outdir, ident + ".ll")+ with open(ll, "w") as f:+ f.write(src)+ q = subprocess.run(["llvm-as", "-o", os.path.join(outdir, ident + ".bc"), ll],+ capture_output=True)+ if q.returncode:+ print("REFUSED %-34s llvm-as: %s"+ % (name, q.stderr.decode().strip().splitlines()[0]))+ continue+ os.remove(ll)+ with open(os.path.join(outdir, ident + ".bin"), "wb") as f:+ f.write(data)+ manifest.append(dict(id=ident, name=name, retty=retty, rn=rn,+ exact=bool(OPS[plain][2] if plain in OPS else True),+ op=plain, signed=True if sign is None else bool(sign),+ cases=[[list(a) for a in c] for c in keep],+ expect=expect))+ n += 1++ with open(os.path.join(outdir, "manifest.json"), "w") as f:+ json.dump(manifest, f)+ run = os.path.join(outdir, "run.sh")+ with open(run, "w") as f:+ f.write(RUNNER)+ os.chmod(run, 0o755)+ print("intrincheck: %d modules in %s, %d declarations, with run.sh and manifest.json"+ % (len(manifest), outdir, len(set(m["name"] for m in manifest))))+ return 0+++NARROW = {"i1", "i8", "i16", "f16", "half"}+++def is_narrow(name, retty):+ """Does this declaration touch a type narrower than 32 bits?++ Read off the mangled name, which carries every operand's type, not only+ the result's: air.convert.f.v2f32.s.v2i16 returns floats and takes i16.+ """+ for part in name.split(".") + [parse_type(retty)[0]]:+ if re.sub(r"^v\d+", "", part) in NARROW:+ return True+ return False+++def parse_runner_log(path):+ """({id: result}, screen) from whatever the runner printed.++ The screen matters: air_run says which one it opened, and softpipe has no+ 16-bit types -- nir_to_tgsi asserts on most of them and silently computes+ the rest at 32 bits, which answered 32767 where a half rounds to 32768.+ That is the engine's limit and not the frontend's, so a half operation+ judged on softpipe would be a verdict about nothing.+ """+ out = {}+ screen = None+ ident = None+ block = []+ def finish():+ if ident is None:+ return+ text = "\n".join(block)+ i = text.find("came back as")+ if i < 0:+ why = ""+ for line in block:+ if any(w in line for w in ("this harness", "Assertion", "error",+ "no gallium", "stores nothing", "no function")):+ why = line.strip()+ break+ out[ident] = ("refused", why or (block[-1].strip() if block else "no output"))+ return+ vals = []+ for line in text[i:].splitlines()[1:]:+ t = line.strip()+ if not t or not re.match(r"^-?[0-9.]|^-?(inf|nan)", t):+ break+ vals.append(t)+ out[ident] = ("ok", vals)++ for line in open(path, errors="replace"):+ if screen is None and " on " in line and line.startswith("air_run: "):+ screen = "softpipe" if "softpipe" in line else line.split(" on ")[-1].strip()+ if line.startswith("=== "):+ finish()+ ident = line[4:].strip()+ block = []+ else:+ block.append(line.rstrip("\n"))+ finish()+ return out, screen+++def check_log(outdir, logpath, verbose):+ """Compare a runner log against the manifest. Where it ran is not our+ business; what it computed is."""+ with open(os.path.join(outdir, "manifest.json")) as f:+ manifest = json.load(f)+ got, screen = parse_runner_log(logpath)+ # TGSI's registers are 32-bit, so softpipe cannot run an operation on a+ # narrow type: nir_to_tgsi asserts for i1, i8 and i16, and for a half it+ # computes at 32 bits instead and answers 32767 where a half rounds to+ # 32768. Either way the verdict would be about softpipe. ir3 has real+ # 16-bit registers, so these are a question for the phone and stay open.+ narrow_here = screen == "softpipe"++ per_decl = {}+ narrow_skipped = set()+ missing = 0+ refused = {}+ total = 0+ for m in manifest:+ if narrow_here and is_narrow(m["name"], m["retty"]):+ narrow_skipped.add(m["name"])+ continue+ r = got.get(m["id"])+ if r is None:+ missing += 1+ continue+ if r[0] == "refused":+ refused.setdefault(m["name"], r[1])+ continue+ vals = r[1]+ isf = parse_type(m["retty"])[0] in ("float", "half", "double")+ flat = []+ for v in vals:+ try:+ flat.append(float(v) if isf else int(float(v)))+ except ValueError:+ flat.append(float("nan"))+ if not isf and m["signed"]:+ flat = [wrap(v, 32, True) for v in flat]+ st = per_decl.setdefault(m["name"], dict(exact=m["exact"], n=0, bad=[],+ worst=0, worst_case=None))+ for i, args in enumerate(m["cases"]):+ for c, exp in enumerate(m["expect"][i]):+ idx = i * m["rn"] + c+ if idx >= len(flat):+ continue+ if (isinstance(exp, float)+ and (math.isinf(exp)+ or (exp != 0.0 and abs(exp) < 1.17549435e-38))):+ continue+ st["n"] += 1+ total += 1+ g = flat[idx]+ if st["exact"]:+ if isinstance(exp, int):+ same = g == exp+ else:+ same = (to_f32_bits(f32(g)) == to_f32_bits(f32(exp))+ or (math.isnan(g) and math.isnan(exp)))+ if not same:+ st["bad"].append((args, c, g, exp))+ else:+ u = ulps(g, exp)+ if u > st["worst"]:+ st["worst"], st["worst_case"] = u, (args, c, g, exp)++ ok = bad = approx = 0+ for name in sorted(per_decl):+ st = per_decl[name]+ if not st["n"]:+ continue+ if st["exact"]:+ if st["bad"]:+ bad += 1+ print("WRONG %-34s %d of %d cases differ" % (name, len(st["bad"]), st["n"]))+ for args, c, g, exp in st["bad"][:4]:+ fmt = (lambda v: "%.9g" % v) if isinstance(g, float) else str+ print(" %-34s [%d] got %-16s want %s"+ % (showargs(args), c, fmt(g), fmt(exp)))+ else:+ ok += 1+ if verbose:+ print("exact %-34s %d cases" % (name, st["n"]))+ else:+ approx += 1+ where = ""+ if st["worst_case"] and st["worst"] > 64:+ args, c, g, exp = st["worst_case"]+ where = " at %s [%d]: %.9g against %.9g" % (showargs(args), c, g, exp)+ print("approx %-34s %d cases, worst %s ulp from libm%s"+ % (name, st["n"], st["worst"], where))++ for name in sorted(refused):+ print("refused %-34s %s" % (name, refused[name][:80]))+ print()+ print("intrincheck: %d exactly defined operations agree on every case, %d differ"+ % (ok, bad))+ print("intrincheck: %d are approximate, compared with this machine's libm and not counted"+ % approx)+ if refused:+ print("intrincheck: %d declarations were refused by the harness" % len(refused))+ if missing:+ print("intrincheck: %d modules are in the manifest and not in the log" % missing)+ if narrow_skipped:+ print("intrincheck: %d declarations left out: a narrow type (i1, i8, i16, f16) "+ "and this ran on softpipe, whose registers are 32-bit" % len(narrow_skipped))+ print("intrincheck: %d cases in all, as RUN on %s and not as folded"+ % (total, screen or "an unnamed screen"))+ return 1 if (bad or missing) else 0++def main(argv):verbose = Falsewant = []decls_file = None+ emit_dir = None+ check_pair = None+ run_here = False+ few = False+ ncases = 0i = 0while i < len(argv):if argv[i] == "-v":@@ -654,10 +1142,26 @@ def main(argv):elif argv[i] == "--decls":i += 1decls_file = argv[i]+ elif argv[i] == "--emit":+ i += 1+ emit_dir = argv[i]+ elif argv[i] == "--check":+ check_pair = (argv[i + 1], argv[i + 2])+ i += 2+ elif argv[i] == "--run":+ run_here = True+ elif argv[i] == "--few":+ few = True+ elif argv[i] == "--cases":+ i += 1+ ncases = int(argv[i])else:want.append(argv[i])i += 1+ if check_pair:+ return check_log(check_pair[0], check_pair[1], verbose)+if not os.path.exists(AIR2NIR):print("intrincheck: run tools/air/mk-host.sh first", file=sys.stderr)return 1@@ -699,6 +1203,29 @@ def main(argv):continuearith.append((d, name, retty, argtys, op, plain, sign, family))+ if emit_dir:+ return emit_suite(arith, emit_dir, want, verbose, few, ncases)++ if run_here:+ # the same modules, drawn by whatever screen air_run opens -- softpipe+ # here, the Adreno on the phone+ d = tempfile.mkdtemp(prefix="intrincheck.run.")+ if emit_suite(arith, d, want, verbose, few, ncases):+ return 1+ log = os.path.join(d, "run.log")+ air_run = os.environ.get("AIR_RUN", os.path.join(+ ROOT, "build/mesa-host/build/src/gallium/drivers/freedreno/air_run"))+ if not os.path.exists(air_run):+ print("intrincheck: no air_run at %s" % air_run, file=sys.stderr)+ return 1+ with open(log, "w") as f:+ q = subprocess.run(["sh", os.path.join(d, "run.sh")],+ env=dict(os.environ, AIR_RUN=air_run),+ stdout=f, stderr=subprocess.STDOUT)+ if q.returncode:+ print("intrincheck: run.sh exited %d" % q.returncode, file=sys.stderr)+ return check_log(d, log, verbose)+tmp = tempfile.mkdtemp(prefix="intrincheck.")exact_ok = exact_bad = approx = refused = denorm = notnormal = 0total_cases = 0diff --git a/tools/mesa/air/air_intrinsics.c b/tools/mesa/air/air_intrinsics.cindex e2b7d38..aba70df 100644--- a/tools/mesa/air/air_intrinsics.c+++ b/tools/mesa/air/air_intrinsics.c@@ -186,8 +186,27 @@ math_op(struct air_ctx *c, const struct air_inst *in, const struct air_name *n,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") && is_float) {+ /* Metal's sign is OpenCL's: sign(-0) is -0, sign(+0) is +0, sign(NaN)+ * is +0. nir_fsign will not promise that -- its own documentation says+ * that for a zero source "there is a preference for the result to have+ * the same sign, but this is not required (it is required by OpenCL)",+ * and likewise for NaN. A backend is therefore licensed to lose it, and+ * softpipe does: it answered +0 for -0 where NIR's own constant folder+ * answered -0, so folding the shader could never have shown this.+ *+ * Built from comparisons instead, which promise what Metal needs:+ * +1 where positive, -1 where negative, 0 for NaN because neither+ * comparison holds, and a zero handed back as it came so it keeps its+ * sign. No immediate is replicated, so this is the same for a vector.+ */+ nir_def *x = a[0];+ nir_def *pos = nir_b2fN(&c->b, nir_fgt_imm(&c->b, x, 0.0), x->bit_size);+ nir_def *neg = nir_b2fN(&c->b, nir_flt_imm(&c->b, x, 0.0), x->bit_size);+ r = nir_bcsel(&c->b, nir_feq_imm(&c->b, x, 0.0), x,+ nir_fsub(&c->b, pos, neg));} else if (!strcmp(op, "sign")) {- r = is_float ? nir_fsign(&c->b, a[0]) : nir_isign(&c->b, a[0]);+ r = nir_isign(&c->b, a[0]); /* the float case is above */} 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],@@ -321,6 +340,27 @@ atomic_op(struct air_ctx *c, const struct air_inst *in, const struct air_name *nnir_def *off = p.offset ? p.offset : nir_imm_int(&c->b, 0);+ /* The memory order, which this lowering is right for exactly one value of.+ * That argument is Metal's memory_order, and every atomic in the corpus+ * passes 0 -- memory_order_relaxed. A relaxed load or store of an aligned+ * 32-bit word is a plain load or store, which is what happens below, and a+ * relaxed read-modify-write needs no barrier either. A stronger order would+ * need one that is not emitted, so rather than ignore the argument and be+ * quietly wrong on a shader that asks for more, refuse it by name. Read+ * through air_const_uint because a zero arrives as CST_CODE_NULL about as+ * often as as an integer.+ */+ unsigned iorder = !strcmp(op, "load") ? 2 : 3;+ uint64_t order;+ if (in->num_operands <= iorder ||+ !air_const_uint(in->operands[iorder], &order))+ return air_error(c, "intrinsic: air.atomic.%s.%s with a memory order that is "+ "not a constant", where, op);+ if (order != 0)+ return air_error(c, "intrinsic: air.atomic.%s.%s with memory_order %u; only "+ "relaxed (0) is translated, and a stronger one needs a "+ "barrier this does not emit", where, op, (unsigned)order);+if (!strcmp(op, "load")) {nir_def *r = air_load_ptr(c, p, in->base.type, 0);if (!r)diff --git a/tools/mesa/air/air_run.c b/tools/mesa/air/air_run.cindex ba9a5fa..be885c0 100644--- a/tools/mesa/air/air_run.c+++ b/tools/mesa/air/air_run.c@@ -22,6 +22,7 @@*/#include <stdio.h>+#include <errno.h>#include <stdlib.h>#include <string.h>@@ -160,6 +161,40 @@ pattern_byte(unsigned i)return (i * 7 + 13) & 0xff;}+/* Fill a buffer the shader is about to read.+ *+ * AIR_RUN_BUFFER=FILE puts that file's bytes there instead of the pattern,+ * which is what lets a test choose the arguments an operation is called on.+ * The reason it has to be a buffer and not a constant in the shader: ir3+ * folds, so a shader that computes air.fast_round(0.5) from an immediate is+ * answered by the compiler and the Adreno never runs the instruction -- the+ * test would pass without the hardware having been asked. A value loaded from+ * a buffer cannot be folded, and the harness knows what it put there.+ *+ * Returns how many bytes came from the file, so the caller can say so rather+ * than claim a fill it did not do. A file shorter than the buffer leaves the+ * rest as the pattern.+ */+static unsigned+fill_buffer(uint8_t *bits, unsigned bytes)+{+ for (unsigned k = 0; k < bytes; k++)+ bits[k] = pattern_byte(k);++ const char *path = getenv("AIR_RUN_BUFFER");+ if (!path || !*path)+ return 0;++ FILE *f = fopen(path, "rb");+ if (!f) {+ fprintf(stderr, "air_run: AIR_RUN_BUFFER=%s: %s\n", path, strerror(errno));+ return 0;+ }+ size_t got = fread(bits, 1, bytes, f);+ fclose(f);+ return got;+}+/* A vertex shader for the quad: it takes the position as attribute 0 and* passes it through. Written here rather than translated, because what is* under test is the fragment shader; when the .metallib has a vertex shader of@@ -284,8 +319,10 @@ dispatch_kernel(struct pipe_screen *screen, const struct air_shader_info *info,if (r->index >= ARRAY_SIZE(bufs))continue;uint8_t *bits = calloc(1, bytes);- for (unsigned k = 0; k < bytes; k++)- bits[k] = pattern_byte(k);+ unsigned from_file = fill_buffer(bits, bytes);+ if (from_file)+ printf("air_run: buffer at index %u, %u bytes, %u of them from "+ "AIR_RUN_BUFFER\n", r->index, bytes, from_file);if (r->kind == AIR_RESOURCE_CONSTANT_BUFFER) {struct pipe_resource *b = pipe_buffer_create(screen, PIPE_BIND_CONSTANT_BUFFER,@@ -638,8 +675,7 @@ main(int argc, char **argv)continue;unsigned bytes = r->size ? r->size : 256;uint8_t *bits = malloc(bytes);- for (unsigned k = 0; k < bytes; k++)- bits[k] = pattern_byte(k);+ unsigned from_file = fill_buffer(bits, bytes);struct pipe_resource *buf = pipe_buffer_create(screen, PIPE_BIND_CONSTANT_BUFFER,PIPE_USAGE_DEFAULT, bytes);pipe_buffer_write(pipe, buf, 0, bytes, bits);@@ -647,9 +683,15 @@ main(int argc, char **argv)&(struct pipe_constant_buffer){.buffer = buf, .buffer_size = bytes,});- printf("air_run: %s buffer at index %u, %u bytes of (i * 7 + 13) & 0xff\n",- r->kind == AIR_RESOURCE_CONSTANT_BUFFER ? "constant" : "device",- r->index, bytes);+ if (from_file)+ printf("air_run: %s buffer at index %u, %u bytes, %u of them from "+ "AIR_RUN_BUFFER\n",+ r->kind == AIR_RESOURCE_CONSTANT_BUFFER ? "constant" : "device",+ r->index, bytes, from_file);+ else+ printf("air_run: %s buffer at index %u, %u bytes of (i * 7 + 13) & 0xff\n",+ r->kind == AIR_RESOURCE_CONSTANT_BUFFER ? "constant" : "device",+ r->index, bytes);free(bits);}