upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/tools
diff options
context:
space:
mode:
authorNotRexed <therealnothingfn@gmail.com>2026-12-01 07:52:21 -0500
committerNotRexed <therealnothingfn@gmail.com>2026-12-01 07:52:21 -0500
commitdd4829ecfc259eebc0e42e3f72d2d61911ee010e (patch)
tree607dabec0efef7e5fe71297e2c5f0b512b0859eb /tools
parente12f7f9f9a82288ee0424be753d383eb3eb7843f (diff)
parent1723dec94510d0aa3d99e795f0a656970c1f00e9 (diff)
Merge remote-tracking branch 'origin/main' into push/main-1130
# Conflicts: # d3d12/docs/switches.md
Diffstat (limited to 'tools')
-rw-r--r--tools/amd_swizzle.py16
-rw-r--r--tools/awc_opus.py63
-rw-r--r--tools/chain_check.py776
-rw-r--r--tools/fmisc_diff.py61
-rw-r--r--tools/lod_bias_probe.py128
-rw-r--r--tools/mc_command.py14
-rw-r--r--tools/picture_metrics.py583
-rw-r--r--tools/rdna2_decode.py16
-rw-r--r--tools/rdna2spirv.py262
-rw-r--r--tools/rpf9dump/Program.cs12
-rw-r--r--tools/rpf9dump/Segments.cs5
-rw-r--r--tools/shader_disasm.py2
-rw-r--r--tools/vk_fuzz_run.py17
-rw-r--r--tools/vk_lod_bias.py351
-rw-r--r--tools/vk_subgroup_info.py26
-rw-r--r--tools/wave64_emulate_opt.py8
16 files changed, 2280 insertions, 60 deletions
diff --git a/tools/amd_swizzle.py b/tools/amd_swizzle.py
index 5f0cd42f0..9096049b5 100644
--- a/tools/amd_swizzle.py
+++ b/tools/amd_swizzle.py
@@ -16,7 +16,20 @@ import os
16import re 16import re
17import sys 17import sys
18 18
19import numpy as np 19# numpy is imported late on purpose: argument and header validation must report their own errors on a machine where
20# numpy is missing or hidden, and only the computation needs it.
21try:
22 import numpy as np
23except ModuleNotFoundError as exc:
24 if exc.name != "numpy":
25 raise
26 np = None
27
28
29def _require_numpy():
30 """Exits with the actionable message when the computation needs numpy and it is not importable."""
31 if np is None:
32 raise SystemExit("ERROR: amd_swizzle.py needs numpy (python -m pip install numpy)")
20 33
21HEADER = os.environ.get("AMD_SWIZZLE_HEADER", r"<ref>\mesa-addrlib\gfx10SwizzlePattern.h") 34HEADER = os.environ.get("AMD_SWIZZLE_HEADER", r"<ref>\mesa-addrlib\gfx10SwizzlePattern.h")
22BPE_INDEX = {1: 0, 2: 1, 4: 2, 8: 3, 16: 4} 35BPE_INDEX = {1: 0, 2: 1, 4: 2, 8: 3, 16: 4}
@@ -241,6 +254,7 @@ def main(argv=None):
241 except (AttributeError, ValueError) as e: 254 except (AttributeError, ValueError) as e:
242 print(f"ERROR: {HEADER!r} does not look like addrlib's gfx10SwizzlePattern.h ({e})", file=sys.stderr) 255 print(f"ERROR: {HEADER!r} does not look like addrlib's gfx10SwizzlePattern.h ({e})", file=sys.stderr)
243 return 2 256 return 2
257 _require_numpy() # every check above must report its own error without numpy
244 # BC formats cover 4x4 pixels per element; uncompressed 1/2/4 bpe formats have one pixel per element. 258 # BC formats cover 4x4 pixels per element; uncompressed 1/2/4 bpe formats have one pixel per element.
245 block = 4 if a.bpe in (8, 16) else 1 259 block = 4 if a.bpe in (8, 16) else 1
246 wb = (a.width + block - 1) // block 260 wb = (a.width + block - 1) // block
diff --git a/tools/awc_opus.py b/tools/awc_opus.py
index be3cd9aaf..9907566f4 100644
--- a/tools/awc_opus.py
+++ b/tools/awc_opus.py
@@ -105,6 +105,22 @@ def opus_samples(packet: bytes | memoryview) -> int:
105OPUS_PRE_SKIP = 312 105OPUS_PRE_SKIP = 312
106 106
107 107
108def ogg_last_granule(path: str):
109 """The granule of the last Ogg page in `path`, or None when the file has no complete page header.
110
111 `--skip-existing` keeps an Ogg written by an earlier run, so that file's own EOS granule is the authority for
112 the cue-sheet limit: recomputing the limit from this run's packets would describe a file that was not written."""
113 try:
114 with open(path, "rb") as f:
115 data = f.read()
116 except OSError:
117 return None
118 at = data.rfind(b"OggS")
119 if at < 0 or at + 14 > len(data):
120 return None
121 return struct.unpack_from("<q", data, at + 6)[0]
122
123
108def write_ogg_opus(path: str, packets: list, channels: int, serial: int, length: int = 0, 124def write_ogg_opus(path: str, packets: list, channels: int, serial: int, length: int = 0,
109 pre_skip: int = OPUS_PRE_SKIP) -> int: 125 pre_skip: int = OPUS_PRE_SKIP) -> int:
110 """length: the stream's declared per-channel sample count at 48 kHz; the EOS page's granule position is 126 """length: the stream's declared per-channel sample count at 48 kHz; the EOS page's granule position is
@@ -469,10 +485,11 @@ def write_cue_sheet(sheet, rows):
469 write_file(sheet, (json.dumps(payload, indent=2) + "\n").encode("utf-8")) 485 write_file(sheet, (json.dumps(payload, indent=2) + "\n").encode("utf-8"))
470 486
471 487
472def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP, cue_sheet: bool = False): 488def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP, cue_sheet: bool = False,
489 skip_existing: bool = False):
473 od = bank_output_dir(path, out_dir) 490 od = bank_output_dir(path, out_dir)
474 if cue_sheet: 491 sheet = os.path.join(od, "cue_regions.json")
475 sheet = os.path.join(od, "cue_regions.json") 492 if cue_sheet and not skip_existing:
476 if os.path.exists(sheet): 493 if os.path.exists(sheet):
477 # A skipped bank or interrupted channel write must not leave last run's regions current. 494 # A skipped bank or interrupted channel write must not leave last run's regions current.
478 write_cue_sheet(sheet, []) 495 write_cue_sheet(sheet, [])
@@ -491,8 +508,21 @@ def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP, cue_shee
491 if cue_sheet: 508 if cue_sheet:
492 channel_counts[cid] += 1 509 channel_counts[cid] += 1
493 if pk: 510 if pk:
511 # The write below uses the de-duplicated stem, so the skip has to look at the same name: a bank
512 # whose streams share an id exports XXXXXXXX.ogg and XXXXXXXX~2.ogg, and only the first would have
513 # been seen under the raw id.
514 target = os.path.join(od, stem + ".ogg")
515 # Kept from an earlier run: its own EOS granule is the only authority for the cue-sheet
516 # limit. Recomputing it from this run's packets would describe a file that was not written.
517 if skip_existing and os.path.exists(target):
518 counts["music"] += 1
519 if cue_sheet and rate == 48000 and samples > 0:
520 kept = ogg_last_granule(target)
521 if kept is not None:
522 frame_limits[cid] = min(samples, max(0, kept - pre_skip))
523 continue
494 n48 = samples * 48000 // rate if rate else 0 524 n48 = samples * 48000 // rate if rate else 0
495 granule = write_ogg_opus(os.path.join(od, stem + ".ogg"), pk, packet_channels, cid, n48, 525 granule = write_ogg_opus(target, pk, packet_channels, cid, n48,
496 pre_skip=pre_skip) 526 pre_skip=pre_skip)
497 if cue_sheet and rate == 48000 and samples > 0: 527 if cue_sheet and rate == 48000 and samples > 0:
498 frame_limits[cid] = min(samples, max(0, granule - pre_skip)) 528 frame_limits[cid] = min(samples, max(0, granule - pre_skip))
@@ -500,6 +530,10 @@ def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP, cue_shee
500 for s, stem in zip(streams, export_stems([s["id"] for s in streams])): 530 for s, stem in zip(streams, export_stems([s["id"] for s in streams])):
501 at, size = s["data"] 531 at, size = s["data"]
502 if s["codec"] == 0x0B and size % 2048 == 0 and s["channels"] in (1, 2): 532 if s["codec"] == 0x0B and size % 2048 == 0 and s["channels"] in (1, 2):
533 ogg = os.path.join(od, stem + ".ogg")
534 if skip_existing and os.path.exists(ogg):
535 counts["opus"] += 1
536 continue
503 pk = opus_packets(d, at, size) 537 pk = opus_packets(d, at, size)
504 if pk: 538 if pk:
505 # +0x0C is the per-channel Opus frame count: equal to the +0 count for mono and 539 # +0x0C is the per-channel Opus frame count: equal to the +0 count for mono and
@@ -509,17 +543,25 @@ def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP, cue_shee
509 frames = s["frames"] 543 frames = s["frames"]
510 if not frames or frames * s["channels"] != s["samples"]: 544 if not frames or frames * s["channels"] != s["samples"]:
511 frames = s["samples"] // max(1, s["channels"]) 545 frames = s["samples"] // max(1, s["channels"])
512 write_ogg_opus(os.path.join(od, stem + ".ogg"), pk, s["channels"], s["id"], frames, 546 write_ogg_opus(ogg, pk, s["channels"], s["id"], frames,
513 pre_skip=pre_skip) 547 pre_skip=pre_skip)
514 counts["opus"] += 1 548 counts["opus"] += 1
515 continue 549 continue
516 if s["codec"] == 2 and s["channels"] in (1, 2) and size == s["samples"] * s["channels"] * 4: 550 if s["codec"] == 2 and s["channels"] in (1, 2) and size == s["samples"] * s["channels"] * 4:
517 # codec 2: 32-bit float PCM (4 bytes per sample; values can exceed +-1, e.g. impulse responses) 551 # codec 2: 32-bit float PCM (4 bytes per sample; values can exceed +-1, e.g. impulse responses)
518 write_wav(os.path.join(od, stem + ".wav"), memoryview(d)[at:at + size], s["rate"], s["channels"], True) 552 wav = os.path.join(od, stem + ".wav")
553 if skip_existing and os.path.exists(wav):
554 counts["pcm"] += 1
555 continue
556 write_wav(wav, memoryview(d)[at:at + size], s["rate"], s["channels"], True)
519 counts["pcm"] += 1 557 counts["pcm"] += 1
520 continue 558 continue
521 if s["codec"] == 0 and s["channels"] in (1, 2) and size == s["samples"] * s["channels"] * 2: 559 if s["codec"] == 0 and s["channels"] in (1, 2) and size == s["samples"] * s["channels"] * 2:
522 write_wav(os.path.join(od, stem + ".wav"), memoryview(d)[at:at + size], s["rate"], s["channels"]) 560 wav = os.path.join(od, stem + ".wav")
561 if skip_existing and os.path.exists(wav):
562 counts["pcm"] += 1
563 continue
564 write_wav(wav, memoryview(d)[at:at + size], s["rate"], s["channels"])
523 counts["pcm"] += 1 565 counts["pcm"] += 1
524 continue 566 continue
525 counts["other"] += 1 567 counts["other"] += 1
@@ -538,6 +580,9 @@ def main(argv=None) -> int:
538 ap.add_argument("src") 580 ap.add_argument("src")
539 ap.add_argument("out") 581 ap.add_argument("out")
540 ap.add_argument("--cue-sheet", action="store_true", help="write paired music cues beside their Ogg files") 582 ap.add_argument("--cue-sheet", action="store_true", help="write paired music cues beside their Ogg files")
583 ap.add_argument("--skip-existing", action="store_true",
584 help="leave outputs that already exist alone, so a stopped export resumes instead of "
585 "rewriting every file")
541 ap.add_argument("--limit", type=int, help="maximum number of banks to export (default: all)") 586 ap.add_argument("--limit", type=int, help="maximum number of banks to export (default: all)")
542 ap.add_argument("--jobs", type=int, default=max(1, (os.cpu_count() or 2) // 2), 587 ap.add_argument("--jobs", type=int, default=max(1, (os.cpu_count() or 2) // 2),
543 help="banks to export at once (default: half the CPU count)") 588 help="banks to export at once (default: half the CPU count)")
@@ -601,7 +646,7 @@ def main(argv=None) -> int:
601 if jobs == 1: 646 if jobs == 1:
602 for i, (b, output_parent) in enumerate(banks): 647 for i, (b, output_parent) in enumerate(banks):
603 try: 648 try:
604 add(export_bank(b, output_parent, a.pre_skip, a.cue_sheet)) 649 add(export_bank(b, output_parent, a.pre_skip, a.cue_sheet, a.skip_existing))
605 except (ValueError, struct.error, IndexError, OSError) as e: 650 except (ValueError, struct.error, IndexError, OSError) as e:
606 skipped(b, e) 651 skipped(b, e)
607 continue 652 continue
@@ -609,7 +654,7 @@ def main(argv=None) -> int:
609 print(f" {i + 1}/{len(banks)} banks: {tot}", flush=True) 654 print(f" {i + 1}/{len(banks)} banks: {tot}", flush=True)
610 else: 655 else:
611 with ProcessPoolExecutor(max_workers=process_workers(jobs)) as ex: 656 with ProcessPoolExecutor(max_workers=process_workers(jobs)) as ex:
612 futures = {ex.submit(export_bank, b, output_parent, a.pre_skip, a.cue_sheet): b for b, output_parent in banks} 657 futures = {ex.submit(export_bank, b, output_parent, a.pre_skip, a.cue_sheet, a.skip_existing): b for b, output_parent in banks}
613 for i, fut in enumerate(as_completed(futures), 1): 658 for i, fut in enumerate(as_completed(futures), 1):
614 b = futures[fut] 659 b = futures[fut]
615 try: 660 try:
diff --git a/tools/chain_check.py b/tools/chain_check.py
new file mode 100644
index 000000000..5405e8f50
--- /dev/null
+++ b/tools/chain_check.py
@@ -0,0 +1,776 @@
1"""One page of counts for the whole shader chain of a work folder: tools, disassembly and translation per family, the
2contract with the runtime and, from a run's log, what the runtime made of it. One block per link, each with a verdict
3(OK / WARN / FAIL) and its most likely cause, then the weakest link.
4
5 python -I tools/chain_check.py <work folder> [--log RUN.log] [--no-probe] [--json] [--strict] [--show-paths]
6
7The links fail quietly one by one: an llvm-mc whose gfx1013 decoder rejects words leaves programs untranslated
8without a warning (#1923), a translation made by older translator sources keeps loading after main changed the
9contract (#2098, "descriptor_table": "tagged"), and the runtime's slot-67 refusals and failed CreatePipelineState
10calls sit in a log of a million lines. This page puts the counts side by side.
11
12Reads, in the work folder (make_game.py's layout):
13
14* shaders/<family>/index.json (and dxbc/fssm_index.json): what was unpacked, with `invalid_words` where the
15 unpacker records them; shaders/<family>/disasm/*.s: the listings;
16* shaders/spirv[/<family>]/index.json and the .spv beside it: what was translated, with each module's
17 `descriptor_table`; translation_sources.sha256 and <family>_build.json: the llvm-mc and the translator sources
18 the translation was made with; shaders/dxbc/disasm.done: the llvm-mc of the game's disassembly;
19* logs/shaders.log: the translator's own refusal reasons of the latest run per family (optional);
20* --log: a gta6rt stderr log (scripts/windows-boot/boot.ps1's <Name>.log), with <Name>.stdout.log and
21 <Name>.digest.txt beside it when they are there.
22
23Verdicts (also in --help):
24
25* tools: FAIL with no llvm-mc record or one without the AMDGPU (amdgcn) target; WARN for an llvm-mc older than
26 GOOD_LLVM_MAJOR (23, the version #1923 measured reading the library), for families made with different llvm-mc
27 versions or with another one than LLVM_MC names now, for a translation made by other translator sources than this
28 checkout's (make_game.py's translation_sources_digest()), and for no spirv-val on PATH.
29* a family: OK when every unpacked program has a module; WARN when at most FAIL_FRACTION (1 %) of them have none
30 (99 of 100 is WARN, 197 of 200 is FAIL) or when there are more modules than programs; FAIL above that, with no
31 readable index, or with no translated index (named "in progress or interrupted" when shard files are there); n/a
32 when the work folder does not hold that family. An index entry whose .spv is missing does not count as translated.
33* contract: WARN for mixed tagged and plain modules, for only plain modules when the translator's default is tagged
34 (#2098), and for no fspx_compute/ while library programs are untranslated.
35* runtime: FAIL for a device loss or fault, a failed device slot call, no translated-shaders line or a non-zero exit
36 code; WARN for "device-fault: submitted dispatch" lines alone (a stall prints them too), for failed or unsupported
37 D3D12 calls and for a loaded module count other than the work folder's. The log may be UTF-8 or UTF-16 with or
38 without a BOM (detected from its zero bytes).
39
40The weakest link is the first block, in chain order, with the worst verdict. The exit code is 0 whatever the
41verdicts (this is a report); --strict exits 1 when a block is FAIL. Bad arguments exit 2.
42
43It prints counts, verdicts, versions, short digests and the translator's and runtime's own fixed words, never a
44program name, a path or a log line (AGENTS.md, "No game data"). Each free-text field is closed against the sources:
45a refusal reason is printed only when it matches one of the messages rdna2spirv.py raises (read from its source),
46each variable part kept only when it is an instruction of rdna2_isa_tables.py (encoding suffix _dpp, _sdwa, _e32 or
47_e64 removed) or a built-in exception name and printed as "#" otherwise, and the whole reason is "other" when it
48matches no message; a D3D12 trace method is printed only when it is a string literal of runtime/shims or
49runtime/src (or Interface::Method built from them), else "(other)"; boot.ps1's ending only in its three forms, else
50"other". The work folder and log paths appear only with --show-paths.
51Standard library only. It runs nothing heavy: with probing on (the default) it asks llvm-mc and spirv-val for
52--version, and git for the current commit; --no-probe runs nothing. A partial or empty work folder gives n/a blocks.
53"""
54from __future__ import annotations
55
56import argparse
57import ast
58import builtins
59import functools
60import hashlib
61import json
62import os
63import re
64import shutil
65import subprocess
66import sys
67from collections import Counter
68
69HERE = os.path.dirname(os.path.abspath(__file__))
70ROOT = os.path.dirname(HERE)
71
72OK, WARN, FAIL, NA = "OK", "WARN", "FAIL", "n/a"
73RANK = {NA: -1, OK: 0, WARN: 1, FAIL: 2}
74# The llvm-mc major whose gfx1013 decoder reads the pipeline library (#1923 measured 21.1.8 against 23.1.5).
75GOOD_LLVM_MAJOR = 23
76# A family with untranslated programs is WARN up to this fraction of its programs, FAIL above it.
77FAIL_FRACTION = 0.01
78VERDICTS = (f"Verdicts: a family is OK when every program has a module, WARN up to {FAIL_FRACTION:.0%} untranslated, "
79 f"FAIL above; tools are WARN for llvm-mc older than {GOOD_LLVM_MAJOR} or a stale translator digest, FAIL "
80 "with no llvm-mc record or no AMDGPU target; the runtime is FAIL for a failed device slot call, a device "
81 "loss or a non-zero exit. Exit code 0 (a report), 1 with --strict when a block is FAIL, 2 for bad "
82 "arguments.")
83# (key, label, folder under shaders/, folder under shaders/spirv/, build settings file)
84FAMILIES = (
85 ("game", "game programs (shaders.rpf)", "dxbc", "", None),
86 ("library", "pipeline library compute", "library", "library", "library_build.json"),
87 ("fspx", "FidelityFX FSPX", "fspx", "fspx", "fspx_build.json"),
88 ("bvh", "BVH builder", "bvh", "bvh", "bvh_build.json"),
89 ("exe", "executable", "exe", "exe", "exe_build.json"),
90)
91# The sub-folders the runtime's ShaderLibrary::load() reads (runtime/src/shader_library.h).
92RUNTIME_FOLDERS = ("fspx", "fspx_compute", "fspx_gfx", "bvh", "exe", "library")
93
94CMD = re.compile(r"rdna2spirv\.py\s+(\S+)")
95SUMMARY = re.compile(r"^\s*(\d+) shaders: (\d+) translated, (\d+) ")
96REASON = re.compile(r"^\s*(\d+)\s{2,}(\S.{0,300}?)\s*$") # free text here: normalize_reason() closes it
97LLVM_VERSION = re.compile(r"LLVM version (\d+)(?:\.(\d+))?(?:\.(\d+))?")
98SPIRV_VAL_VERSION = re.compile(r"(v\d{4}\.\d+)")
99DEFAULT_TABLE = re.compile(r'"--descriptor-table",\s*choices=DESCRIPTOR_TABLES,\s*default="(\w+)"')
100
101LOADED = re.compile(r"\[rt\] d3d12: (\d+) translated shaders \((\d+) fspx, (\d+) fspx_compute, (\d+) fspx_gfx, "
102 r"(\d+) bvh, (\d+) exe\)")
103TABLE_ALL = re.compile(r"\[rt\] d3d12: descriptor table: (plain|tagged) \(all (\d+) modules\)")
104TABLE_MIX = re.compile(r"\[rt\] d3d12: descriptor table: (\d+) tagged / (\d+) plain modules; using (plain|tagged)")
105TABLE_FORCED = re.compile(r"\[rt\] d3d12: descriptor table: (plain|tagged) \(LEONIDA_DESCRIPTOR_TABLE; (\d+) tagged / "
106 r"(\d+) plain modules\)")
107SLOT_FAIL = re.compile(r"\[rt\] d3d12_xs: slot (\d+) call \d+ failed with (0x[0-9a-fA-F]{8})")
108NO_COMPUTE = re.compile(r"\[rt\] d3d12: no translated compute shader for ")
109BUILD_START = re.compile(r"\[rt\] d3d12: compute pipeline \S+ \(\d+ B SPIR-V, [^)]*\) build starts")
110# "to build" is the line of older logs. The line now names where the pipeline came from, and only a compile is a build.
111BUILD_SLOW = re.compile(r"\[rt\] d3d12: compute pipeline \S+ took [0-9.]+ s to (?:build|obtain from a compile) ")
112TRACE = re.compile(r"\[d3d12-trace\] #\d+ (.+) (failed|unsupported|refused|partial)\s*$")
113GATE = re.compile(r"\[rt\] submit-lock: thread \d+ is waiting at the compile gate")
114STALL = re.compile(r"\[rt\] device-fault: submitted dispatch ") # also printed for a plain stall
115FAULT = re.compile(r"\[rt\] device-fault: (?!enabled|submitted dispatch )")
116LOST = re.compile(r"VK_ERROR_DEVICE_LOST")
117EXITED = re.compile(r"game exited with code (-?\d+)")
118# A trace method is printed only when it is a string literal of the runtime's sources, or Interface::Method /
119# Interface::Slot<N> built from one (d3d12_xs_device.cpp, child_trace_name()); anything else is "(other)".
120COMPOSED_METHOD = re.compile(r"^([A-Za-z_][A-Za-z0-9_]*)::([A-Za-z_][A-Za-z0-9_]*)$")
121C_STRING = re.compile(r'"((?:[^"\\\n]|\\.){1,120})"')
122RUNTIME_SOURCE_DIRS = ("runtime/shims", "runtime/src")
123# A variable part of a refusal reason is kept only when it is an instruction of tools/rdna2_isa_tables.py (with a
124# _dpp, _sdwa, _e32 or _e64 encoding suffix removed first) or a built-in exception name; else it is "#".
125MNEMONIC = re.compile(r"^[a-z][a-z0-9]*(?:_[a-z0-9]+)+$")
126ISA_NAME = re.compile(r"'([a-z][a-z0-9]*(?:_[a-z0-9]+)+)'")
127ISA_SUFFIX = re.compile(r"_(?:dpp|sdwa|e32|e64)$")
128UNSUPPORTED_CALL = re.compile(r"(?<![\w.])Unsupported\(")
129# The three verdicts scripts/windows-boot/boot.ps1 writes on its digest's first line; anything else is "other".
130ENDINGS = (re.compile(r"^ran its full time limit \(\d+ s\), stopped$"),
131 re.compile(r"^exited by itself after \d+ s, exit code (?:unknown|(-?\d+) \(0x[0-9a-f]{8}\))$"),
132 re.compile(r"^digest of an earlier run \(-DigestOnly\)$"))
133
134
135# ------------------------------------------------------------------------------------------------ reading helpers
136def load_json(path: str):
137 try:
138 with open(path, encoding="utf-8-sig") as f:
139 return json.load(f)
140 except (OSError, ValueError):
141 return None
142
143
144def read_utf8(path: str) -> str | None:
145 try:
146 with open(path, encoding="utf-8-sig", errors="replace") as f:
147 return f.read().strip()
148 except OSError:
149 return None
150
151
152def log_encoding(path: str) -> str:
153 """UTF-8, or UTF-16 with a BOM (PowerShell 5.1 redirection) or without one: ASCII text in UTF-16 has a zero in
154 every other byte, little-endian at the odd offsets."""
155 with open(path, "rb") as f:
156 head = f.read(4096)
157 if head[:2] in (b"\xff\xfe", b"\xfe\xff"):
158 return "utf-16"
159 if head.count(0) * 4 >= len(head) > 0:
160 return "utf-16-le" if head[1::2].count(0) >= head[0::2].count(0) else "utf-16-be"
161 return "utf-8"
162
163
164def log_lines(path: str):
165 """The lines of a log in the encoding log_encoding() finds."""
166 with open(path, encoding=log_encoding(path), errors="replace") as f:
167 yield from f
168
169
170def _safe_lines(path: str):
171 """log_lines(), ending quietly at an unreadable file instead of raising."""
172 try:
173 yield from log_lines(path)
174 except (OSError, UnicodeError):
175 return
176
177
178def listing_count(folder: str) -> int | None:
179 try:
180 with os.scandir(folder) as entries:
181 return sum(1 for e in entries if e.name.endswith(".s") and e.is_file() and e.stat().st_size > 0)
182 except OSError:
183 return None
184
185
186def shard_parts(spirv: str) -> int:
187 """The shard plans and index parts make_game.py's translate() leaves while a translation runs or once it stopped."""
188 try:
189 with os.scandir(spirv) as entries:
190 return sum(1 for e in entries if re.fullmatch(r"(?:shard\d+|index\.part\d+)\.json", e.name))
191 except OSError:
192 return 0
193
194
195def pct(part: int, whole: int) -> str:
196 return f"{100.0 * part / whole:.1f}%" if whole else "-"
197
198
199def short(digest: str | None) -> str:
200 return digest[:12] if isinstance(digest, str) and digest else "none"
201
202
203# ------------------------------------------------------------------------------------------------ repository side
204def repo_translation_digest(root: str = ROOT) -> str | None:
205 """make_game.py's translation_sources_digest(), computed without importing make_game.py: the TRANSLATION_SOURCES
206 tuple is read from its source, then SHA-256 over each file's name, length and bytes (sources_digest())."""
207 try:
208 with open(os.path.join(root, "make_game.py"), encoding="utf-8") as f:
209 tree = ast.parse(f.read())
210 except (OSError, SyntaxError):
211 return None
212 names = None
213 for node in tree.body:
214 if isinstance(node, ast.Assign) and any(getattr(t, "id", None) == "TRANSLATION_SOURCES" for t in node.targets):
215 names = ast.literal_eval(node.value)
216 if not names:
217 return None
218 h = hashlib.sha256(b"")
219 try:
220 for name in names:
221 with open(os.path.join(root, "tools", name), "rb") as f:
222 data = f.read()
223 h.update(f"{name}\0{len(data)}\0".encode())
224 h.update(data)
225 except OSError:
226 return None
227 return h.hexdigest()
228
229
230def translator_default_table(root: str = ROOT) -> str | None:
231 text = read_utf8(os.path.join(root, "tools", "rdna2spirv.py")) or ""
232 m = DEFAULT_TABLE.search(text)
233 return m.group(1) if m else None
234
235
236def run_quiet(command: list[str], timeout: int = 20) -> str | None:
237 try:
238 r = subprocess.run(command, capture_output=True, text=True, errors="replace", timeout=timeout)
239 except (OSError, subprocess.SubprocessError):
240 return None
241 return (r.stdout + r.stderr).strip() if r.returncode == 0 else None
242
243
244def parse_llvm(text: str | None) -> dict:
245 """Version and AMDGPU target from an llvm-mc --version text, or from make_game.py's signature (a JSON pair)."""
246 command = None
247 if text and text.startswith("["):
248 try:
249 command, text = json.loads(text)
250 except (ValueError, TypeError):
251 pass
252 m = LLVM_VERSION.search(text or "")
253 program = os.path.basename(str(command[-1])) if isinstance(command, list) and command else None
254 via = "wsl" if isinstance(command, list) and any("wsl" in str(c).lower() for c in command[:1]) else None
255 return {"version": ".".join(g for g in m.groups() if g) if m else None,
256 "major": int(m.group(1)) if m else None,
257 "amdgpu": ("amdgcn" in text) if text else None,
258 "program": program, "via": via}
259
260
261# ------------------------------------------------------------------------------------------------ refusal reasons
262def _pattern(node) -> list:
263 """An Unsupported(...) message as a list of literal strings, with None for each variable part."""
264 if isinstance(node, ast.Constant) and isinstance(node.value, str):
265 return [node.value]
266 if isinstance(node, ast.JoinedStr):
267 return [v.value if isinstance(v, ast.Constant) else None for v in node.values]
268 if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
269 return _pattern(node.left) + _pattern(node.right)
270 return [None]
271
272
273def _unsupported_args(source: str):
274 """The first argument of each Unsupported(...) call in source. Each call is parsed on its own (the shortest text
275 up to a closing parenthesis that parses), since parsing the whole 20,000-line translator takes seconds."""
276 for m in UNSUPPORTED_CALL.finditer(source):
277 start = m.end()
278 end = start
279 while (end := source.find(")", end + 1 if end > start else start)) != -1 and end - start < 2000:
280 try:
281 call = ast.parse("f(" + source[start:end] + ")", mode="eval").body
282 except SyntaxError:
283 continue
284 if isinstance(call, ast.Call) and call.args:
285 yield call.args[0]
286 break
287
288
289@functools.lru_cache(maxsize=4)
290def reason_templates(root: str = ROOT) -> tuple:
291 """The refusal messages rdna2spirv.py counts, as (regex, parts) pairs with the most literal text first, plus its
292 "translator error <exception>" count. Empty when the translator's source cannot be read."""
293 try:
294 with open(os.path.join(root, "tools", "rdna2spirv.py"), encoding="utf-8") as f:
295 source = f.read()
296 except (OSError, ValueError):
297 return ()
298 found = {("translator error ", None)}
299 for arg in _unsupported_args(source):
300 merged = []
301 for part in _pattern(arg): # adjacent variable parts are one
302 if not (part is None and merged and merged[-1] is None):
303 merged.append(part)
304 found.add(tuple(merged))
305 templates = [(re.compile("^" + "".join("(.+?)" if p is None else re.escape(p) for p in parts) + "$"), parts)
306 for parts in found]
307 templates.sort(key=lambda t: (-sum(len(p) for p in t[1] if p), t[0].pattern))
308 return tuple(templates)
309
310
311@functools.lru_cache(maxsize=4)
312def isa_names(root: str = ROOT) -> frozenset:
313 """The instruction names of tools/rdna2_isa_tables.py (empty when it cannot be read)."""
314 try:
315 with open(os.path.join(root, "tools", "rdna2_isa_tables.py"), encoding="utf-8") as f:
316 return frozenset(ISA_NAME.findall(f.read()))
317 except (OSError, ValueError):
318 return frozenset()
319
320
321def known_value(value: str) -> bool:
322 """A variable part that may be printed: an ISA instruction of the decoder's tables or a built-in exception."""
323 if MNEMONIC.match(value) and ISA_SUFFIX.sub("", value) in isa_names():
324 return True
325 builtin = getattr(builtins, value, None)
326 return isinstance(builtin, type) and issubclass(builtin, BaseException)
327
328
329@functools.lru_cache(maxsize=4)
330def runtime_literals(root: str = ROOT) -> frozenset:
331 """Every short C string literal in the runtime's sources: the closed set a trace method name must come from."""
332 found = set()
333 for folder in RUNTIME_SOURCE_DIRS:
334 for dirpath, _, files in os.walk(os.path.join(root, folder)):
335 for name in files:
336 if name.endswith((".cpp", ".h", ".hpp", ".inl")):
337 try:
338 with open(os.path.join(dirpath, name), encoding="utf-8", errors="replace") as f:
339 found.update(C_STRING.findall(f.read()))
340 except OSError:
341 continue
342 return frozenset(found)
343
344
345def trace_method(method: str) -> str:
346 """The method of a [d3d12-trace] line when the runtime's sources name it, else "(other)"."""
347 literals = runtime_literals()
348 if method in literals:
349 return method
350 m = COMPOSED_METHOD.match(method)
351 if m and m.group(1) in literals and (m.group(2) in literals or re.fullmatch(r"Slot\d{1,3}", m.group(2))):
352 return method
353 return "(other)"
354
355
356def normalize_reason(reason: str, templates: list) -> str:
357 """The reason when it is one of the translator's messages, each variable part kept only when known_value() (else
358 "#"); "other" for anything else."""
359 for regex, parts in templates:
360 m = regex.match(reason)
361 if not m:
362 continue
363 values = iter(m.groups())
364 out = []
365 for part in parts:
366 if part is None:
367 value = next(values)
368 part = value if known_value(value) else "#"
369 out.append(part)
370 text = "".join(out)
371 # A message that is only a variable part (Unsupported(op)) says nothing once that part is masked.
372 return "other" if not text.strip("# ") else text
373 return "other"
374
375
376# ------------------------------------------------------------------------------------------------ the build log
377def family_of(disasm_path: str) -> str | None:
378 parts = [p for p in re.split(r"[\\/]+", disasm_path.lower()) if p]
379 parent = parts[-2] if len(parts) >= 2 else ""
380 return {"dxbc": "game", "library": "library", "fspx": "fspx", "bvh": "bvh", "exe": "exe"}.get(parent)
381
382
383def parse_build_log(path: str, templates: list | None = None) -> dict:
384 """The latest translator run of each family in logs/shaders.log: programs, translated, and refusals by reason.
385 A run starts at an rdna2spirv.py command line (not --merge) and its shards' summaries follow it."""
386 runs: dict = {}
387 current = None
388 in_reasons = False
389 try:
390 lines = log_lines(path)
391 for line in lines:
392 m = CMD.search(line)
393 if m and "--merge" not in line:
394 current = family_of(m.group(1))
395 if current:
396 runs[current] = {"programs": 0, "translated": 0, "valid": 0, "reasons": Counter()}
397 in_reasons = False
398 continue
399 m = SUMMARY.match(line)
400 if m and current:
401 run = runs[current]
402 run["programs"] += int(m.group(1))
403 run["translated"] += int(m.group(2))
404 run["valid"] += int(m.group(3))
405 in_reasons = True
406 continue
407 if in_reasons and current:
408 m = REASON.match(line)
409 if m:
410 reason = normalize_reason(m.group(2), templates or [])
411 runs[current]["reasons"][reason] += int(m.group(1))
412 continue
413 in_reasons = False
414 except (OSError, UnicodeError):
415 return {}
416 return runs
417
418
419# ------------------------------------------------------------------------------------------------ the blocks
420def tools_block(work: str, probe: bool) -> dict:
421 sh = os.path.join(work, "shaders")
422 records = {}
423 done = load_json(os.path.join(sh, "dxbc", "disasm.done"))
424 if isinstance(done, dict) and isinstance(done.get("llvm"), str):
425 records["game"] = parse_llvm(done["llvm"])
426 translator = {"game": read_utf8(os.path.join(sh, "spirv", "translation_sources.sha256"))}
427 for key, _, _, spirv_sub, settings in FAMILIES:
428 if not settings:
429 continue
430 s = load_json(os.path.join(sh, "spirv", spirv_sub, settings))
431 if isinstance(s, dict):
432 if isinstance(s.get("llvm_mc"), str):
433 records[key] = parse_llvm(s["llvm_mc"])
434 translator[key] = s.get("translator")
435 versions = Counter(r["version"] or "?" for r in records.values())
436 repo = repo_translation_digest()
437 translator = {k: v for k, v in translator.items() if isinstance(v, str) and v}
438 local = Counter(short(v) for v in translator.values())
439 stale = sorted(k for k, v in translator.items() if repo and v != repo)
440 current = spirv_val = head = None
441 if probe:
442 sys.path.insert(0, HERE)
443 try:
444 from mc_command import mc_command
445 command = mc_command()
446 command[0] = shutil.which(command[0]) or command[0]
447 text = run_quiet([*command, "--version"])
448 current = parse_llvm(text) if text else {"version": None}
449 except (Exception, SystemExit): # noqa: BLE001 - a broken LLVM_MC is reported, not raised
450 current = {"version": None}
451 exe = shutil.which("spirv-val")
452 text = run_quiet([exe, "--version"]) if exe else None
453 m = SPIRV_VAL_VERSION.search(text or "")
454 spirv_val = (m.group(1) if m else "found, version unread") if exe else "not found"
455 head = run_quiet(["git", "-C", ROOT, "rev-parse", "--short", "HEAD"])
456 verdict, causes = OK, []
457 majors = {r["major"] for r in records.values()}
458 if not records and not translator:
459 verdict, causes = NA, ["nothing disassembled or translated in this work folder"]
460 elif not records:
461 verdict, causes = FAIL, ["no llvm-mc record in the work folder (disassembly never finished)"]
462 elif any(r["amdgpu"] is False for r in records.values()):
463 verdict, causes = FAIL, ["a recorded llvm-mc has no AMDGPU (amdgcn) target"]
464 else:
465 old = {k: r["version"] for k, r in records.items() if r["major"] is not None and r["major"] < GOOD_LLVM_MAJOR}
466 if old:
467 verdict = WARN
468 causes.append(f"llvm-mc {'/'.join(sorted(set(old.values())))} (used for {', '.join(sorted(old))}) "
469 f"predates {GOOD_LLVM_MAJOR}: its gfx1013 decoder rejects words the library needs (#1923)")
470 if len(versions) > 1:
471 verdict = WARN
472 causes.append("families were disassembled with different llvm-mc versions")
473 if current and current.get("version") and current["version"] not in versions:
474 verdict = WARN
475 causes.append(f"llvm-mc now on LLVM_MC is {current['version']}: the folder was made with another")
476 if stale and verdict != NA:
477 verdict = max(verdict, WARN, key=RANK.get)
478 causes.append(f"translation of {', '.join(stale)} made by other translator sources than this checkout's "
479 "(make_game.py shaders translates again)")
480 if spirv_val == "not found" and verdict != NA:
481 verdict = max(verdict, WARN, key=RANK.get)
482 causes.append("spirv-val not on PATH")
483 return {"name": "tools", "verdict": verdict, "cause": "; ".join(causes) or "-",
484 "_majors": {k: r["major"] for k, r in records.items()},
485 "llvm_mc_recorded": dict(versions), "llvm_mc_records": len(records),
486 "llvm_mc_amdgpu": (False if any(r["amdgpu"] is False for r in records.values()) else
487 True if records and all(r["amdgpu"] for r in records.values()) else None),
488 "llvm_mc_via": sorted({r["via"] or "native" for r in records.values()}),
489 "llvm_mc_current": (current or {}).get("version") if probe else NA,
490 "spirv_val": spirv_val if probe else NA,
491 "translator_local": dict(local), "translator_repo": short(repo), "repo_head": head,
492 "translator_stale": stale}
493
494
495def family_block(work: str, key: str, label: str, folder: str, spirv_sub: str, build: dict, llvm_major) -> dict:
496 sh = os.path.join(work, "shaders")
497 unpacked = os.path.join(sh, folder)
498 block = {"name": key, "label": label}
499 if not os.path.isdir(unpacked):
500 block.update(verdict=NA, cause="not unpacked in this work folder")
501 return block
502 index = load_json(os.path.join(unpacked, "fssm_index.json" if key == "game" else "index.json"))
503 expected = len(index) if isinstance(index, (list, dict)) else None
504 rejected = None
505 if isinstance(index, list) and index and isinstance(index[0], dict) and "invalid_words" in index[0]:
506 rejected = sum(1 for e in index if isinstance(e, dict) and isinstance(e.get("invalid_words"), int)
507 and e["invalid_words"] > 0)
508 listings = listing_count(os.path.join(unpacked, "disasm"))
509 spirv = os.path.join(sh, "spirv", spirv_sub) if spirv_sub else os.path.join(sh, "spirv")
510 translated_index = load_json(os.path.join(spirv, "index.json"))
511 translated = no_module = None
512 tables = Counter()
513 if isinstance(translated_index, dict):
514 present = [n for n in translated_index if n and os.path.isfile(os.path.join(spirv, n + ".spv"))]
515 translated, no_module = len(present), len(translated_index) - len(present)
516 tables = Counter(m["descriptor_table"] if isinstance(m, dict) and m.get("descriptor_table") == "tagged"
517 else "plain" for m in translated_index.values())
518 run = build.get(key)
519 reasons = run["reasons"].most_common(5) if run else []
520 block.update(expected=expected, listings=listings, listings_with_rejected_words=rejected,
521 translated=translated, modules_missing=no_module, tables=dict(tables),
522 reasons=[[n, r] for r, n in reasons],
523 log_run=({"programs": run["programs"], "translated": run["translated"]} if run else None))
524 if expected is None:
525 block.update(verdict=FAIL, cause="no readable unpack index")
526 elif translated is None:
527 parts = shard_parts(spirv)
528 block.update(verdict=FAIL, cause=f"no translated index: translation in progress or interrupted ({parts} shard "
529 "files)" if parts else "no translated index (translation never finished)")
530 else:
531 failed = max(expected - translated, 0)
532 block.update(failed=failed, percent=pct(translated, expected))
533 if translated > expected:
534 block.update(verdict=WARN, cause=f"{translated - expected} more modules than unpacked programs "
535 "(a translation from another unpack?)")
536 elif failed == 0 and not no_module:
537 block.update(verdict=OK, cause="-")
538 else:
539 block["verdict"] = WARN if failed <= expected * FAIL_FRACTION and not no_module else FAIL
540 top = reasons[0][0] if reasons else None
541 if top and "undecodable" in top and llvm_major is not None and llvm_major < GOOD_LLVM_MAJOR:
542 cause = f"llvm-mc {llvm_major}.x leaves undecodable words ({reasons[0][1]} refusals; #1923)"
543 elif top:
544 cause = f"translator refusal: {top} ({reasons[0][1]})"
545 elif no_module:
546 cause = f"{no_module} index entries without their .spv"
547 else:
548 cause = "untranslated, no reason in logs/shaders.log"
549 block["cause"] = cause
550 return block
551
552
553def contract_block(work: str, families: list[dict]) -> dict:
554 spirv = os.path.join(work, "shaders", "spirv")
555 default = translator_default_table()
556 tables = Counter()
557 for f in families:
558 tables.update(f.get("tables") or {})
559 folders = {name: os.path.isfile(os.path.join(spirv, name, "index.json")) for name in RUNTIME_FOLDERS}
560 library_failed = next((f.get("failed") or 0 for f in families if f["name"] == "library"), 0)
561 verdict, causes = (OK, []) if tables else (NA, ["no translated modules"])
562 if tables.get("tagged") and tables.get("plain"):
563 verdict = WARN
564 causes.append("mixed tagged and plain modules: the runtime picks one table for all")
565 elif default == "tagged" and tables and not tables.get("tagged"):
566 verdict = WARN
567 causes.append("every module is plain while this checkout's translator writes tagged (#2098): "
568 "the runtime falls back to the plain table without a word")
569 if tables and not folders["fspx_compute"] and library_failed:
570 verdict = max(verdict, WARN, key=RANK.get)
571 causes.append(f"no fspx_compute/ to cover the {library_failed} untranslated library programs")
572 return {"name": "contract", "verdict": verdict, "cause": "; ".join(causes) or "-",
573 "translator_default_table": default, "modules": dict(tables),
574 "folders_present": [n for n, ok in folders.items() if ok],
575 "folders_absent": [n for n, ok in folders.items() if not ok]}
576
577
578def runtime_block(path: str, families: list[dict]) -> dict:
579 loaded = table = None
580 slots, trace = Counter(), Counter()
581 counts = Counter()
582 exit_code = None
583 try:
584 encoding = log_encoding(path)
585 except OSError:
586 encoding = None
587 for line in _safe_lines(path):
588 if "[rt]" not in line and "[d3d12-trace]" not in line and "VK_ERROR" not in line and "exited" not in line:
589 continue
590 m = TRACE.search(line)
591 if m:
592 trace[f"{trace_method(m.group(1))} {m.group(2)}"] += 1
593 continue
594 if loaded is None and (m := LOADED.search(line)):
595 loaded = dict(zip(("total", "fspx", "fspx_compute", "fspx_gfx", "bvh", "exe"), map(int, m.groups())))
596 elif m := SLOT_FAIL.search(line):
597 slots[f"slot {m.group(1)} {m.group(2).lower()}"] += 1
598 elif NO_COMPUTE.search(line):
599 counts["no_translated_compute"] += 1
600 elif BUILD_START.search(line):
601 counts["compute_builds"] += 1
602 elif BUILD_SLOW.search(line):
603 counts["slow_compute_builds"] += 1
604 elif GATE.search(line):
605 counts["compile_gate_waits"] += 1
606 elif STALL.search(line):
607 counts["stalled_dispatch_lines"] += 1
608 elif FAULT.search(line):
609 counts["device_fault_lines"] += 1
610 elif m := TABLE_ALL.search(line):
611 table = m.group(1)
612 elif m := TABLE_MIX.search(line):
613 table = f"{m.group(3)} ({m.group(1)} tagged / {m.group(2)} plain)"
614 elif m := TABLE_FORCED.search(line):
615 table = f"{m.group(1)} forced by LEONIDA_DESCRIPTOR_TABLE ({m.group(2)} tagged / {m.group(3)} plain)"
616 if LOST.search(line):
617 counts["device_lost_lines"] += 1
618 if m := EXITED.search(line):
619 exit_code = int(m.group(1))
620 stem = path[:-4] if path.lower().endswith(".log") else path
621 if exit_code is None and os.path.isfile(stem + ".stdout.log"):
622 for line in _safe_lines(stem + ".stdout.log"):
623 if m := EXITED.search(line):
624 exit_code = int(m.group(1))
625 digest = read_utf8(stem + ".digest.txt")
626 ending = None
627 if digest:
628 first = digest.splitlines()[0]
629 ending = first.split(":", 1)[1].strip() if first.startswith("== boot") and ":" in first else None
630 if ending:
631 matched = next((m for m in (e.match(ending) for e in ENDINGS) if m), None)
632 if not matched:
633 ending = "other"
634 elif exit_code is None and matched.groups() and matched.group(1) is not None:
635 exit_code = int(matched.group(1))
636 local = sum(f.get("translated") or 0 for f in families)
637 library = next((f for f in families if f["name"] == "library"), {})
638 verdict, causes = OK, []
639 if counts["device_lost_lines"] or counts["device_fault_lines"]:
640 verdict = FAIL
641 if counts["device_lost_lines"] or counts["device_fault_lines"] or counts["stalled_dispatch_lines"]:
642 verdict = max(verdict, WARN, key=RANK.get)
643 causes.append(f"device lost, faulted or stalled (lost {counts['device_lost_lines']}, fault "
644 f"{counts['device_fault_lines']}, stalled dispatch {counts['stalled_dispatch_lines']} lines)")
645 if slots:
646 verdict = FAIL
647 worst, n = slots.most_common(1)[0]
648 hint = ""
649 if worst.startswith("slot 67") and library.get("failed"):
650 hint = f", against {library['failed']} untranslated library programs"
651 causes.append(f"{sum(slots.values())} device slot calls failed ({worst}: {n}{hint})")
652 failed_pso = sum(n for k, n in trace.items() if k.endswith((" failed", " unsupported", " refused")))
653 if failed_pso:
654 verdict = max(verdict, WARN, key=RANK.get)
655 causes.append(f"{failed_pso} D3D12 calls failed or unsupported")
656 if loaded is None:
657 verdict = FAIL
658 causes.append("no translated-shaders line (Vulkan device not reached?)" if encoding else
659 "the log could not be read")
660 elif loaded["total"] != local:
661 verdict = max(verdict, WARN, key=RANK.get)
662 causes.append(f"loaded {loaded['total']} modules, the work folder holds {local} (another folder or build?)")
663 if exit_code not in (None, 0):
664 verdict = FAIL
665 causes.append(f"exit code {exit_code}")
666 return {"name": "runtime", "verdict": verdict, "cause": "; ".join(causes) or "-", "loaded": loaded,
667 "descriptor_table": table, "slot_failures": dict(slots.most_common(5)),
668 "d3d12_problems": dict(trace.most_common(5)), "exit_code": exit_code, "ending": ending,
669 "log_encoding": encoding,
670 **{k: counts[k] for k in ("no_translated_compute", "compute_builds", "slow_compute_builds",
671 "compile_gate_waits", "device_fault_lines", "device_lost_lines",
672 "stalled_dispatch_lines")}}
673
674
675def check(work: str, log: str | None = None, probe: bool = True, show_paths: bool = False) -> dict:
676 tools = tools_block(work, probe)
677 majors = tools.pop("_majors") # the llvm-mc major each family was disassembled with
678 build = parse_build_log(os.path.join(work, "logs", "shaders.log"), reason_templates())
679 families = [family_block(work, key, label, folder, sub, build, majors.get(key))
680 for key, label, folder, sub, _ in FAMILIES]
681 blocks = [tools, *families, contract_block(work, families)]
682 if log:
683 blocks.append(runtime_block(log, families))
684 worst = max(RANK[b["verdict"]] for b in blocks)
685 weakest = next(b for b in blocks if RANK[b["verdict"]] == worst)
686 report = {"blocks": blocks,
687 "weakest": ({"name": weakest["name"], "verdict": weakest["verdict"], "cause": weakest["cause"]}
688 if worst >= 0 else {"name": "none", "verdict": NA, "cause": "nothing to check"})}
689 if show_paths:
690 report.update(work=work, log=log)
691 return report
692
693
694# ------------------------------------------------------------------------------------------------ text output
695def fmt_counter(d: dict, joiner: str = "") -> str:
696 sep = f" {joiner} " if joiner else " "
697 return ", ".join(f"{k}{sep}{v}" for k, v in d.items()) or "none"
698
699
700def render(report: dict) -> str:
701 out = ["chain check" + (f" of {report['work']}" if report.get("work") else "")
702 + (f" with log {report['log']}" if report.get("log") else "")]
703 for b in report["blocks"]:
704 out.append(f"[{b['verdict']}] {b['name']}" + (f" {b['label']}" if b.get("label") else ""))
705 if b["verdict"] == NA:
706 pass
707 elif b["name"] == "tools":
708 recorded = fmt_counter(b["llvm_mc_recorded"], "in")
709 amdgcn = {True: "yes", False: "NO", None: "n/a"}[b["llvm_mc_amdgpu"]]
710 out.append(f" llvm-mc recorded {recorded} ({b['llvm_mc_records']} records, "
711 f"amdgcn {amdgcn}, via {'/'.join(b['llvm_mc_via']) or 'n/a'}); "
712 f"LLVM_MC now {b['llvm_mc_current'] or 'unreadable'}")
713 out.append(f" spirv-val {b['spirv_val']}")
714 local = fmt_counter(b["translator_local"], "in")
715 out.append(f" translator local {local}; checkout {b['translator_repo']}"
716 f"{' at ' + b['repo_head'] if b['repo_head'] else ''}; stale: "
717 f"{', '.join(b['translator_stale']) or 'none'}")
718 elif b["name"] == "contract":
719 out.append(f" modules {fmt_counter(b['modules'])}; translator default {b['translator_default_table']}")
720 out.append(f" folders present {', '.join(b['folders_present']) or 'none'}; absent "
721 f"{', '.join(b['folders_absent']) or 'none'}")
722 elif b["name"] == "runtime":
723 ld = b["loaded"]
724 out.append(" loaded " + (fmt_counter(ld) if ld else "no translated-shaders line")
725 + f"; descriptor table {b['descriptor_table'] or '?'}")
726 out.append(f" slot fails {fmt_counter(b['slot_failures'])}; no translated compute shader "
727 f"{b['no_translated_compute']}")
728 out.append(f" d3d12 {fmt_counter(b['d3d12_problems'])}")
729 out.append(f" pipelines compute builds {b['compute_builds']} (slow {b['slow_compute_builds']}); "
730 f"compile gate waits {b['compile_gate_waits']}")
731 out.append(f" device fault lines {b['device_fault_lines']}, device lost lines "
732 f"{b['device_lost_lines']}, stalled dispatch lines {b['stalled_dispatch_lines']}; exit code "
733 f"{'none logged' if b['exit_code'] is None else b['exit_code']}"
734 + (f"; boot.ps1: {b['ending']}" if b['ending'] else ""))
735 else:
736 def n(key):
737 return "none" if b.get(key) is None else b[key]
738 rej = b.get("listings_with_rejected_words")
739 out.append(f" expected {n('expected')} listings {n('listings')}"
740 + (f" ({rej} with rejected words)" if rej is not None else "")
741 + f" translated {n('translated')} ({b.get('percent', '-')}) failed {b.get('failed', '-')}"
742 + (f" index without .spv {b['modules_missing']}" if b.get("modules_missing") else ""))
743 if b.get("reasons"):
744 out.append(" reasons " + "; ".join(f"{n} {r}" for n, r in b["reasons"]))
745 out.append(f" cause: {b['cause']}")
746 w = report["weakest"]
747 out.append(f"weakest link: {w['name']} [{w['verdict']}]: {w['cause']}")
748 return "\n".join(out)
749
750
751def main(argv=None) -> int:
752 ap = argparse.ArgumentParser(description="One page of counts for the shader chain of a work folder.",
753 epilog=VERDICTS)
754 ap.add_argument("work", help="make_game.py's work folder (holds shaders/ and logs/)")
755 ap.add_argument("--log", help="a gta6rt stderr log of one run (scripts/windows-boot/boot.ps1's <Name>.log)")
756 ap.add_argument("--no-probe", action="store_true", help="run nothing: no llvm-mc, spirv-val or git --version")
757 ap.add_argument("--json", action="store_true", help="print the report as JSON")
758 ap.add_argument("--strict", action="store_true", help="exit 1 when a block is FAIL (default: 0, a report)")
759 ap.add_argument("--show-paths", action="store_true",
760 help="name the work folder and the log in the report (not for publishing)")
761 a = ap.parse_args(argv)
762 if not os.path.isdir(a.work):
763 ap.error(f"no work folder at {a.work}")
764 if a.log and not os.path.isfile(a.log):
765 ap.error(f"no log at {a.log}")
766 report = check(a.work, a.log, probe=not a.no_probe, show_paths=a.show_paths)
767 print(json.dumps(report, indent=1) if a.json else render(report))
768 return 1 if a.strict and any(b["verdict"] == FAIL for b in report["blocks"]) else 0
769
770
771if __name__ == "__main__":
772 try:
773 sys.stdout.reconfigure(errors="replace")
774 except AttributeError:
775 pass
776 sys.exit(main())
diff --git a/tools/fmisc_diff.py b/tools/fmisc_diff.py
index b5196ae62..c674cd60a 100644
--- a/tools/fmisc_diff.py
+++ b/tools/fmisc_diff.py
@@ -33,9 +33,12 @@ Every rule was checked against an RDNA2 GPU (AMD Radeon iGPU, gfx1036, Windows d
33 33
34Not judged (the program is skipped with the reason, counted): a denormal operand or result (whether f32 denormals 34Not judged (the program is skipped with the reason, counted): a denormal operand or result (whether f32 denormals
35are flushed is the MODE question, SHADER-35), a NaN whose payload is later read as an integer (payloads are not 35are flushed is the MODE question, SHADER-35), a NaN whose payload is later read as an integer (payloads are not
36modelled), the clamp of a NaN and an output modifier whose result is a zero (tools/f32_fuzz.py measures both), and 36modelled), the clamp of a NaN and an output modifier whose result is a zero (tools/f32_fuzz.py measures both), an
37an output modifier on a signalling-NaN result (the translator's multiply quiets it, which a later v_cmp_class sees; 37output modifier on a signalling-NaN result (the translator's multiply quiets it, which a later v_cmp_class sees;
38whether the hardware does is not measured). 38whether the hardware does is not measured), and the class bits of a NaN that a float op computed (v_fmamk_f32 & co.:
39whether the hardware quiets a signalling NaN operand is payload-level and only partly measured - on gfx1036 under
40the game's MODE it mostly passes the NaN source through unchanged but sometimes quiets or flips its sign, so a
41v_cmp_class_f32 on the result cannot be judged).
39 42
40Known divergences (KNOWN_DIVERGENCES): by default the generator leaves out the forms where the translator is known to 43Known divergences (KNOWN_DIVERGENCES): by default the generator leaves out the forms where the translator is known to
41differ from the hardware, so that a run shows new problems only; --known puts them back (a hardware-only run always 44differ from the hardware, so that a run shows new problems only; --known puts them back (a hardware-only run always
@@ -450,12 +453,39 @@ def raw(tok, st):
450 return int(tok, 0) & M32 453 return int(tok, 0) & M32
451 454
452 455
456def _vreg(tok):
457 """The VGPR a source token reads, ignoring neg/abs modifiers; None for anything else."""
458 if tok.startswith("-") and not tok[1:2].isdigit():
459 tok = tok[1:]
460 tok = tok.strip("|")
461 m = re.fullmatch(r"v(\d+)", tok)
462 return int(m.group(1)) if m else None
463
464
453def ivalue(tok, st): 465def ivalue(tok, st):
454 if re.fullmatch(r"v\d+", tok) and int(tok[1:]) in st["nan"]: 466 if re.fullmatch(r"v\d+", tok) and int(tok[1:]) in st["nan"]:
455 raise Uncertain("a computed NaN read as an integer") 467 raise Uncertain("a computed NaN read as an integer")
456 return raw(tok, st) 468 return raw(tok, st)
457 469
458 470
471# Ops whose NaN output is the NaN input's word, unchanged (a pass-through or a bit move): the quiet bit a
472# v_cmp_class_f32 later reads is the input's, modelled exactly when the input's is (st["nanf"] does not propagate
473# through them, it only survives). v_fmamk_f32 is the one op here that makes a NaN from its operands: on gfx1036
474# under the game's MODE (IEEE off) the hardware mostly returns the NaN source's word but sometimes quiets a
475# signalling one, so a signalling-NaN operand - or an operand whose NaN quiet bit is already unmodelled - makes
476# the result's class bits unmodelled too.
477NAN_PASSTHROUGH = {"v_fract_f32", "v_frexp_mant_f32", "v_frexp_exp_i32_f32", "v_ldexp_f32"}
478
479
480def _nan_fuzzy(tok, w, st):
481 """Whether a NaN input to v_fmamk_f32 leaves the result's quiet bit unmodelled: the input is signalling, or
482 it is a register whose NaN quiet bit already is."""
483 if not is_nan(w):
484 return False
485 r = _vreg(tok)
486 return (r is not None and r in st["nanf"]) or not w & 0x400000
487
488
459def fvalue(tok, st): 489def fvalue(tok, st):
460 neg = tok.startswith("-") and not tok[1:2].isdigit() 490 neg = tok.startswith("-") and not tok[1:2].isdigit()
461 if neg: 491 if neg:
@@ -489,7 +519,9 @@ def out_mods(w, mods):
489 519
490def reference(lines): 520def reference(lines):
491 """Run the program; returns the four exported words. Raises Uncertain for what it does not judge.""" 521 """Run the program; returns the four exported words. Raises Uncertain for what it does not judge."""
492 st = {"v": {}, "s": {}, "nan": set()} # nan: VGPRs holding a computed NaN (payload not modelled) 522 st = {"v": {}, "s": {}, "nan": set(), "nanf": set()} # nan: VGPRs holding a computed NaN (payload not
523 # modelled); nanf: of those, the ones whose quiet bit is not modelled either (a v_fmamk_f32 NaN, or a
524 # pass-through of one): a later v_cmp_class_f32 on them is Uncertain, everything else still judges them.
493 for line in lines: 525 for line in lines:
494 op, _, rest = line.partition(" ") 526 op, _, rest = line.partition(" ")
495 args, mods = parse(rest) 527 args, mods = parse(rest)
@@ -499,6 +531,9 @@ def reference(lines):
499 if op.startswith("v_cmp_"): 531 if op.startswith("v_cmp_"):
500 a = fvalue(args[1], st) 532 a = fvalue(args[1], st)
501 if op.startswith("v_cmp_class_f32"): 533 if op.startswith("v_cmp_class_f32"):
534 r = _vreg(args[1])
535 if r is not None and r in st["nanf"]:
536 raise Uncertain("the class bits of a NaN whose quiet bit is not modelled")
502 bit = class_bits(a) & ivalue(args[2], st) 537 bit = class_bits(a) & ivalue(args[2], st)
503 else: 538 else:
504 bit = fcmp(op[len("v_cmp_"):].split("_f32")[0], a, fvalue(args[2], st)) 539 bit = fcmp(op[len("v_cmp_"):].split("_f32")[0], a, fvalue(args[2], st))
@@ -508,8 +543,11 @@ def reference(lines):
508 if op in ("v_mov_b32_e32", "v_cndmask_b32_e64"): 543 if op in ("v_mov_b32_e32", "v_cndmask_b32_e64"):
509 src = args[1] if op == "v_mov_b32_e32" else args[2 if raw(args[3], st) & 1 else 1] 544 src = args[1] if op == "v_mov_b32_e32" else args[2 if raw(args[3], st) & 1 else 1]
510 st["v"][d] = raw(src, st) 545 st["v"][d] = raw(src, st)
511 nan = re.fullmatch(r"v\d+", src) and int(src[1:]) in st["nan"] 546 r = _vreg(src)
547 nan = r is not None and r in st["nan"]
512 (st["nan"].add if nan else st["nan"].discard)(d) 548 (st["nan"].add if nan else st["nan"].discard)(d)
549 fuzzy = r is not None and r in st["nanf"]
550 (st["nanf"].add if fuzzy else st["nanf"].discard)(d)
513 continue 551 continue
514 base = op[:-4] if op.endswith(("_e32", "_e64")) else op 552 base = op[:-4] if op.endswith(("_e32", "_e64")) else op
515 if base not in OPS: 553 if base not in OPS:
@@ -524,7 +562,18 @@ def reference(lines):
524 if is_denorm(w): 562 if is_denorm(w):
525 raise Uncertain("denormal result") 563 raise Uncertain("denormal result")
526 w = out_mods(w, mods) 564 w = out_mods(w, mods)
527 (st["nan"].add if fout and is_nan(w) else st["nan"].discard)(d) 565 nan_out = fout and is_nan(w)
566 # Read the sources' nanf before d's own entry is replaced (d may alias a source).
567 if not nan_out:
568 fuzzy = False
569 elif base == "v_fmamk_f32":
570 fuzzy = any(_nan_fuzzy(t, v, st) for t, v in zip(args[1:4], vals))
571 elif base in NAN_PASSTHROUGH:
572 fuzzy = any(_vreg(t) in st["nanf"] for t, f in zip(args[1:], fin) if f)
573 else:
574 fuzzy = False
575 (st["nan"].add if nan_out else st["nan"].discard)(d)
576 (st["nanf"].add if fuzzy else st["nanf"].discard)(d)
528 st["v"][d] = w 577 st["v"][d] = w
529 return [st["v"].get(8 + i, 0) for i in range(4)] 578 return [st["v"].get(8 + i, 0) for i in range(4)]
530 579
diff --git a/tools/lod_bias_probe.py b/tools/lod_bias_probe.py
new file mode 100644
index 000000000..ac5421a2c
--- /dev/null
+++ b/tools/lod_bias_probe.py
@@ -0,0 +1,128 @@
1"""Measure whether the Vulkan driver applies VkSamplerCreateInfo::mipLodBias, for rdna2spirv.py --explicit-lod-bias.
2
3 python -I tools/lod_bias_probe.py [--build <folder with vk_sampler_test>]
4
5The answer is measured, not looked up: MoltenVK 1.4.2 drops the sampler's bias on an Apple M3 (ps_ssharp fails on
6main) but applies it on an Apple M5 Pro (ps_ssharp passes on main), so a driver ID can't decide.
7
8First it asks tools/vk_subgroup_info.py --lod-bias, which measures it with one compute dispatch from Python
9(tools/vk_lod_bias.py) and needs no built test programs, llvm-mc or SPIR-V tools. Only when that has no answer and
10--build names the test programs does it fall back to the draw below. The draw translates runtime/test/shaders/vs_ids and ps_ssharp *without* the flag into a temporary folder (build.py with
11LEONIDA_EXPLICIT_LOD_BIAS=0), then draws them with vk_sampler_test three times: no bias, LOD_BIAS +1 and -1 (S# words
12from check.py's ssharp_words). ps_ssharp's mrt0 is (lz.r, lz.g, implicit.r, implicit.g): the explicit sample at LOD
130 and the derivative one at LOD 1, on a two-level texture.
14
15* no-bias draw wrong -> None (the probe can't judge this device)
16* +1 and -1 both as check.py expects -> False: the driver applies the bias, the flag would count it twice
17* +1 and -1 both read the no-bias levels -> True: the driver drops it, translate with --explicit-lod-bias
18* anything else -> None
19
20The last line printed is {"explicit_lod_bias": true|false|null, "reason": "..."}; the exit status is 0 either way
21(2 on a usage error). It honours the environment the tests run under (VK_DRIVER_FILES, LEONIDA_VULKAN_LOADER, ...).
22Standard library only; needs llvm-mc and the SPIR-V tools build.py needs, no game files.
23"""
24import argparse
25import json
26import os
27import subprocess
28import sys
29import tempfile
30from pathlib import Path
31
32HERE = os.path.dirname(os.path.abspath(__file__))
33ROOT = os.path.dirname(HERE)
34SHADERS = os.path.join(ROOT, "runtime", "test", "shaders")
35EXE = ".exe" if os.name == "nt" else ""
36sys.path.insert(0, SHADERS)
37import check # noqa: E402 (ssharp_words, sampler_mismatch, the SAMPLER_SIZE readback layout)
38
39
40def subgroup_info_answer(timeout: int = 120):
41 """(True | False | None, reason) from tools/vk_subgroup_info.py --lod-bias."""
42 try:
43 r = subprocess.run([sys.executable, "-I", os.path.join(HERE, "vk_subgroup_info.py"), "--lod-bias"],
44 capture_output=True, text=True, timeout=timeout)
45 answer = json.loads(r.stdout.strip().splitlines()[-1])
46 except (OSError, ValueError, IndexError, subprocess.SubprocessError) as e:
47 return None, f"vk_subgroup_info.py --lod-bias: {e}"
48 if "error" in answer:
49 return None, f"vk_subgroup_info.py --lod-bias: {answer['error']}"
50 return answer.get("explicit_lod_bias"), answer.get("explicit_lod_bias_reason", "")
51
52
53def probe(build: str | None = None, timeout: int = 120):
54 """(True | False | None, reason): vk_subgroup_info.py's measurement, else the vk_sampler_test draw."""
55 answer, reason = subgroup_info_answer(timeout)
56 if answer is not None or not build:
57 return answer, reason
58 drawn, why = draw_probe(build, timeout)
59 return drawn, why if drawn is not None else f"{reason}; {why}"
60
61
62def draw_probe(build: str, timeout: int = 120):
63 """(True | False | None, reason) from three vk_sampler_test draws of ps_ssharp."""
64 tool = os.path.join(build, "vk_sampler_test" + EXE)
65 if not os.path.isfile(tool):
66 return None, f"no vk_sampler_test{EXE} in {build}"
67 with tempfile.TemporaryDirectory(prefix="leonida-lod-bias-") as tmp:
68 env = dict(os.environ, LEONIDA_EXPLICIT_LOD_BIAS="0")
69 try:
70 r = subprocess.run([sys.executable, "-I", os.path.join(SHADERS, "build.py"), tmp, "vs_ids", "ps_ssharp"],
71 capture_output=True, text=True, env=env, timeout=timeout)
72 except (OSError, subprocess.SubprocessError) as e:
73 return None, f"build.py: {e}"
74 shaders = [os.path.join(tmp, "spirv", n + ".spv") for n in ("vs_ids", "ps_ssharp")]
75 if r.returncode or not all(os.path.isfile(s) for s in shaders):
76 out = (r.stdout + r.stderr).strip()
77 if "llvm-mc" in out and "could not be started" in out:
78 # Homebrew's llvm is keg-only: say what to set instead of a bare "could not be started".
79 sys.path.insert(0, HERE)
80 import mc_command # noqa: E402
81 return None, "the draw needs llvm-mc to translate ps_ssharp: " + mc_command.install_hint()
82 return None, "build.py could not translate vs_ids and ps_ssharp: " + out[-300:]
83 view = (0, 1)
84
85 def draw(bias):
86 words = check.ssharp_words(1, bias=bias)
87 raw = Path(tmp) / f"bias{bias:+}.raw"
88 try:
89 d = subprocess.run([tool, *shaders, str(raw), *(f"{w:x}" for w in words), *(str(v) for v in view)],
90 capture_output=True, text=True, timeout=timeout)
91 except (OSError, subprocess.SubprocessError) as e:
92 return None, f"vk_sampler_test: {e}"
93 if d.returncode or not raw.is_file():
94 return None, f"vk_sampler_test exited {d.returncode}: " + (d.stdout + d.stderr).strip()[-200:]
95 data = raw.read_bytes()
96 return check.sampler_mismatch(data, words, view), data
97
98 base = draw(0)
99 if base[0] is None:
100 return None, base[1]
101 if base[0]:
102 return None, f"the no-bias draw is already wrong ({base[0]})"
103 results = {}
104 for bias in (1, -1):
105 problem, data = draw(bias)
106 if problem is None:
107 return None, data
108 results[bias] = (problem, data)
109 if not any(p for p, _ in results.values()):
110 return False, "the sampler applies LOD_BIAS +1 and -1"
111 if all(p and data == base[1] for p, data in results.values()):
112 return True, "the sampler drops LOD_BIAS: +1 and -1 read the no-bias levels"
113 return None, "; ".join(f"bias {b:+}: {p or 'ok'}" for b, (p, _) in results.items())
114
115
116def main(argv=None):
117 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
118 ap.add_argument("--build", help="the folder with vk_sampler_test, for the draw fallback (the GPU test programs)")
119 a = ap.parse_args(argv)
120 answer, reason = probe(a.build)
121 print(json.dumps({"explicit_lod_bias": answer, "reason": reason}))
122 return 0
123
124
125if __name__ == "__main__":
126 if hasattr(sys.stdout, "reconfigure"):
127 sys.stdout.reconfigure(errors="replace")
128 sys.exit(main())
diff --git a/tools/mc_command.py b/tools/mc_command.py
index 762008d7a..17fde8437 100644
--- a/tools/mc_command.py
+++ b/tools/mc_command.py
@@ -4,7 +4,7 @@ LLVM_MC may be one executable (a path, spaces and all, with or without its .exe)
4needs the command-line form when llvm-mc runs inside WSL, because the official Windows LLVM build has no AMDGPU 4needs the command-line form when llvm-mc runs inside WSL, because the official Windows LLVM build has no AMDGPU
5target: 5target:
6 6
7 set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc 7 set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-23/bin/llvm-mc
8 8
9On Windows, arguments follow the MSVC C runtime's quoting rules. Double a trailing backslash in a quoted 9On Windows, arguments follow the MSVC C runtime's quoting rules. Double a trailing backslash in a quoted
10argument before the closing quote. 10argument before the closing quote.
@@ -116,7 +116,7 @@ def default_command() -> str:
116 116
117 117
118def mc_command(raw: str | None = None) -> list: 118def mc_command(raw: str | None = None) -> list:
119 """LLVM_MC is a path, or a command line: 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc'. Unset or empty, 119 """LLVM_MC is a path, or a command line: 'wsl -d Ubuntu -e /usr/lib/llvm-23/bin/llvm-mc'. Unset or empty,
120 default_command().""" 120 default_command()."""
121 if raw is None: 121 if raw is None:
122 raw = os.environ.get("LLVM_MC", "") 122 raw = os.environ.get("LLVM_MC", "")
@@ -127,14 +127,14 @@ def install_hint() -> str:
127 """Where to get an llvm-mc with the AMDGPU target on this OS, for the messages that report a missing one.""" 127 """Where to get an llvm-mc with the AMDGPU target on this OS, for the messages that report a missing one."""
128 if os.name == "nt": 128 if os.name == "nt":
129 return ("The official Windows LLVM build has no AMDGPU target: build a native one with " 129 return ("The official Windows LLVM build has no AMDGPU target: build a native one with "
130 "scripts\\build_llvm_mc.ps1 (it sets LLVM_MC), or install llvm-21 in WSL and set LLVM_MC to the " 130 "scripts\\build_llvm_mc.ps1 (it sets LLVM_MC), or install llvm-23 in WSL and set LLVM_MC to the "
131 "whole command, e.g.\n LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc") 131 "whole command, e.g.\n LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-23/bin/llvm-mc")
132 if sys.platform == "darwin": 132 if sys.platform == "darwin":
133 return ("Homebrew's llvm has the AMDGPU target but is keg-only (not on PATH): brew install llvm, then\n" 133 return ("Homebrew's llvm has the AMDGPU target but is keg-only (not on PATH): brew install llvm, then\n"
134 " LLVM_MC=\"$(brew --prefix llvm)/bin/llvm-mc\"") 134 " LLVM_MC=\"$(brew --prefix llvm)/bin/llvm-mc\"")
135 return ("Distribution LLVM packages include the AMDGPU target: on Debian or Ubuntu, sudo apt install llvm-21\n" 135 return ("Distribution LLVM packages include the AMDGPU target: on Debian or Ubuntu, sudo apt install llvm-23\n"
136 "(found as /usr/lib/llvm-21/bin/llvm-mc without further setup); elsewhere install your distribution's\n" 136 "(found as /usr/lib/llvm-23/bin/llvm-mc without further setup); elsewhere install your distribution's\n"
137 "LLVM 21+ package and put llvm-mc on PATH, or set LLVM_MC=/path/to/llvm-mc") 137 "LLVM 23+ package and put llvm-mc on PATH, or set LLVM_MC=/path/to/llvm-mc")
138 138
139 139
140def not_found(exe: str, error: OSError, flag: str | None = None) -> str: 140def not_found(exe: str, error: OSError, flag: str | None = None) -> str:
diff --git a/tools/picture_metrics.py b/tools/picture_metrics.py
new file mode 100644
index 000000000..d12d588d7
--- /dev/null
+++ b/tools/picture_metrics.py
@@ -0,0 +1,583 @@
1"""Numbers about a frame on your disk, for the PICTURE block of docs/agent_collaboration.md.
2
3 python -I tools/picture_metrics.py <frame.png|.ppm> [<reference.png|.ppm>] [--json] [--class CLASS]
4 [--region X,Y,W,H] [--tolerance N]
5
6From one frame the tool prints its size, luma statistics, the dark share of each of a fixed 4 x 4 grid of regions,
7a lattice detector (dark marks in square tiles along one diagonal in N: tile, period, phase, diagonal, corner of
8the tile), a block-grid detector (rectangular blocks cut off from the picture around them: block size and share)
9and a measured defect class. With a second frame, the reference, it adds the per-8x8 diff of the two (count,
10share, bounding box and position of the changed tiles) and the reference's luma, and can measure FLASH.
11
12Luma is BT.601 in integers, ``(299 R + 587 G + 114 B + 500) // 1000``; a pixel is dark at luma 24 or less.
13
14Measured classes, first match: ``BLACK-NEAR`` (95% or more of the frame dark), ``FLASH`` (the two luma means
15differ by 64 or more), ``LATTICE``, ``BLOCKS``, else ``OK``. ``CHAR-BLACK``, ``CHAR-MISSING``, ``2D-MISSING``,
16``STRAY-GEO`` and ``SMEAR`` need to know what the scene should show, so the tool has no detector for them: a human
17gives one with ``--class`` and it is printed as ``given``, next to the measured class, never in its place.
18``--region`` adds the luma statistics of a rectangle the human picked (a character, a HUD element) so a given
19class comes with numbers. ``--tolerance`` lets a diff ignore channel changes up to N; it is 0 (exact) by default.
20
21Reads PNG (8-bit grey, grey + alpha, RGB or RGBA, not interlaced, all five filters; alpha is ignored) and binary
22PPM/PGM (P6/P5, maxval 255). Anything else (palette, 16-bit, interlaced PNG, other formats) is refused with one
23``error:`` line and exit 2.
24
25What it does not do: it does not look at what the scene contains, it does not write any file, and its output holds
26numbers and classes only: no pixel values beyond statistics, no image path (the path stays a local argument).
27The detectors are tuned on synthetic frames; on a real frame a scene edge on the grid or a dark texture on a
28diagonal can hide or fake them, so a class is a hint for a human to confirm. A lattice needs 8 marked tiles on 3
29half-marked diagonals of its class, so a lattice cropped to fewer repeats is not reported. BLOCKS refuses one
30sharp rectangle and a checkerboard, but several sharp rectangles (HUD panels, window frames) can still read as
31BLOCKS, and blocks off the frame's origin are given at the divisor of their edges (16-pixel blocks shifted by 4
32read as 4x4): see ``find_blocks``.
33"""
34from __future__ import annotations
35
36import argparse
37import json
38import math
39import struct
40import sys
41import zlib
42from typing import NamedTuple, Optional
43
44DARK = 24 # a pixel at this luma or below is dark
45BLACK_NEAR_SHARE = 0.95 # dark share of the frame for BLACK-NEAR
46FLASH_DELTA = 64 # luma mean difference between the two frames for FLASH
47REGIONS = 4 # the dark-share grid is REGIONS x REGIONS
48DIFF_TILE = 8
49LATTICE_TILES = (4, 8, 16, 32)
50LATTICE_MAX_PERIOD = 32
51LATTICE_MIN_SCORE = 0.5 # cover of the diagonal minus the rate of marks off it
52LATTICE_MIN_TILES = 8 # marked tiles in the winning class, not in the whole frame
53LATTICE_MAX_OUTSIDE = 0.25 # the rate of marks off the diagonal stays under this share of its cover
54LATTICE_MIN_REPEATS = 3 # half-marked diagonals in the winning class: the pattern repeats at least this often
55NEAR_BEST = 0.9 # the smallest tile and period within this share of the best score win
56EDGE_JUMP = 8 # a step across a block edge: at least this many luma levels ...
57EDGE_RATIO = 3 # ... and this many times the steps beside it
58MIN_LINE_ROWS = 4 # pixels on one grid line that must step for it to count
59MIN_BLOCK = 4
60MIN_EDGE_LINES = 3 # edge columns, and edge rows, a block grid needs
61MAX_BLOCK_SHARE = 0.5 # cut-off blocks are a minority: past this there is no picture around them
62TEXT_TILES = 16 # changed tiles listed in the text block (all of them in --json)
63
64MEASURED = ("BLACK-NEAR", "FLASH", "LATTICE", "BLOCKS", "OK")
65GIVEN_ONLY = ("CHAR-BLACK", "CHAR-MISSING", "2D-MISSING", "STRAY-GEO", "SMEAR")
66CLASSES = ("LATTICE", "BLACK-NEAR", "BLOCKS", "FLASH") + GIVEN_ONLY + ("OK",)
67
68PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
69
70
71class Frame(NamedTuple):
72 """A decoded frame: row-major RGB, 3 bytes a pixel."""
73 width: int
74 height: int
75 rgb: bytes
76
77
78# ---- reading ---------------------------------------------------------------------------------------------------
79
80def _paeth(a: int, b: int, c: int) -> int:
81 p = a + b - c
82 pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
83 if pa <= pb and pa <= pc:
84 return a
85 return b if pb <= pc else c
86
87
88def _unfilter(raw: bytes, height: int, stride: int, bpp: int) -> bytearray:
89 if len(raw) < height * (stride + 1):
90 raise ValueError("PNG image data is shorter than the image")
91 out = bytearray(height * stride)
92 prev = bytearray(stride)
93 for y in range(height):
94 kind = raw[y * (stride + 1)]
95 row = bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)])
96 if kind == 1:
97 for i in range(bpp, stride):
98 row[i] = (row[i] + row[i - bpp]) & 0xFF
99 elif kind == 2:
100 for i in range(stride):
101 row[i] = (row[i] + prev[i]) & 0xFF
102 elif kind == 3:
103 for i in range(stride):
104 left = row[i - bpp] if i >= bpp else 0
105 row[i] = (row[i] + ((left + prev[i]) >> 1)) & 0xFF
106 elif kind == 4:
107 for i in range(stride):
108 if i >= bpp:
109 row[i] = (row[i] + _paeth(row[i - bpp], prev[i], prev[i - bpp])) & 0xFF
110 else:
111 row[i] = (row[i] + prev[i]) & 0xFF
112 elif kind != 0:
113 raise ValueError(f"PNG filter type {kind} is not one of the five")
114 out[y * stride:(y + 1) * stride] = row
115 prev = row
116 return out
117
118
119def decode_png(data: bytes) -> Frame:
120 """An 8-bit, non-interlaced grey, grey + alpha, RGB or RGBA PNG as a Frame; ValueError for anything else."""
121 if not data.startswith(PNG_SIGNATURE):
122 raise ValueError("not a PNG")
123 pos, header, idat = len(PNG_SIGNATURE), None, []
124 while True:
125 if pos + 8 > len(data):
126 raise ValueError("PNG is truncated")
127 length, kind = struct.unpack(">I4s", data[pos:pos + 8])
128 body = data[pos + 8:pos + 8 + length]
129 if len(body) != length or pos + 12 + length > len(data):
130 raise ValueError("PNG is truncated")
131 (crc,) = struct.unpack(">I", data[pos + 8 + length:pos + 12 + length])
132 if zlib.crc32(kind + body) & 0xFFFFFFFF != crc:
133 raise ValueError(f"PNG chunk {kind.decode('latin-1')!r} has a bad CRC")
134 pos += 12 + length
135 if kind == b"IHDR":
136 if length != 13:
137 raise ValueError("PNG IHDR is not 13 bytes")
138 header = struct.unpack(">IIBBBBB", body)
139 elif kind == b"IDAT":
140 idat.append(body)
141 elif kind == b"IEND":
142 break
143 if header is None:
144 raise ValueError("PNG has no IHDR")
145 width, height, depth, color, _compression, _filter, interlace = header
146 channels = {0: 1, 2: 3, 4: 2, 6: 4}.get(color)
147 if channels is None:
148 raise ValueError(f"PNG colour type {color} is not read (grey, grey + alpha, RGB or RGBA only)")
149 if depth != 8:
150 raise ValueError(f"PNG bit depth {depth} is not read (8 only)")
151 if interlace:
152 raise ValueError("interlaced PNG is not read")
153 if not width or not height:
154 raise ValueError("PNG has no pixels")
155 try:
156 raw = zlib.decompress(b"".join(idat))
157 except zlib.error as e:
158 raise ValueError(f"PNG image data does not inflate: {e}") from None
159 px = _unfilter(raw, height, width * channels, channels)
160 return Frame(width, height, _to_rgb(px, channels))
161
162
163def _to_rgb(px: bytes, channels: int) -> bytes:
164 if channels == 3:
165 return bytes(px)
166 out = bytearray(len(px) // channels * 3)
167 if channels in (1, 2):
168 grey = px[0::channels]
169 out[0::3] = out[1::3] = out[2::3] = grey
170 else:
171 for c in range(3):
172 out[c::3] = px[c::4]
173 return bytes(out)
174
175
176def decode_ppm(data: bytes) -> Frame:
177 """A binary PPM (P6) or PGM (P5) with maxval 255 as a Frame; ValueError for anything else."""
178 fields, pos = [], 2
179 while len(fields) < 3:
180 while pos < len(data) and data[pos:pos + 1].isspace():
181 pos += 1
182 if data[pos:pos + 1] == b"#":
183 while pos < len(data) and data[pos:pos + 1] not in (b"\n", b"\r"):
184 pos += 1
185 continue
186 start = pos
187 while pos < len(data) and data[pos:pos + 1].isdigit():
188 pos += 1
189 if start == pos:
190 raise ValueError("PPM header is not three numbers")
191 fields.append(int(data[start:pos]))
192 width, height, maxval = fields
193 if maxval != 255:
194 raise ValueError(f"PPM maxval {maxval} is not read (255 only)")
195 if not width or not height:
196 raise ValueError("PPM has no pixels")
197 channels = 3 if data[:2] == b"P6" else 1
198 px = data[pos + 1:pos + 1 + width * height * channels]
199 if len(px) != width * height * channels:
200 raise ValueError("PPM is truncated")
201 return Frame(width, height, _to_rgb(px, channels))
202
203
204def decode_image(data: bytes) -> Frame:
205 """A PNG or a binary PPM/PGM, told apart by their first bytes."""
206 if data.startswith(PNG_SIGNATURE):
207 return decode_png(data)
208 if data[:2] in (b"P6", b"P5"):
209 return decode_ppm(data)
210 raise ValueError("neither a PNG nor a binary PPM/PGM")
211
212
213# ---- one frame -------------------------------------------------------------------------------------------------
214
215def luma(frame: Frame) -> bytes:
216 """BT.601 integer luma of every pixel, row-major."""
217 rgb = frame.rgb
218 return bytes((299 * r + 587 * g + 114 * b + 500) // 1000 for r, g, b in zip(rgb[0::3], rgb[1::3], rgb[2::3]))
219
220
221def luma_stats(lumas: bytes) -> dict:
222 """Mean, minimum, maximum, population standard deviation and dark share of a list of luma values."""
223 n = len(lumas)
224 total = sum(lumas)
225 squares = sum(v * v for v in lumas)
226 mean = total / n
227 sd = math.sqrt(max(squares / n - mean * mean, 0.0))
228 dark = sum(1 for v in lumas if v <= DARK)
229 return {"mean": round(mean, 2), "min": min(lumas), "max": max(lumas), "sd": round(sd, 2),
230 "dark": round(dark / n, 4)}
231
232
233def dark_regions(lumas: bytes, width: int, height: int) -> list[list[float]]:
234 """Dark share of each region of a REGIONS x REGIONS grid, rows top to bottom; region edges at ``i * size // 4``."""
235 xs = [i * width // REGIONS for i in range(REGIONS + 1)]
236 ys = [i * height // REGIONS for i in range(REGIONS + 1)]
237 grid = []
238 for r in range(REGIONS):
239 row = []
240 for c in range(REGIONS):
241 dark = sum(1 for y in range(ys[r], ys[r + 1]) for v in lumas[y * width + xs[c]:y * width + xs[c + 1]]
242 if v <= DARK)
243 area = (xs[c + 1] - xs[c]) * (ys[r + 1] - ys[r])
244 row.append(round(dark / area, 4) if area else 0.0)
245 grid.append(row)
246 return grid
247
248
249def region_stats(lumas: bytes, width: int, rect: tuple[int, int, int, int]) -> dict:
250 x, y, w, h = rect
251 values = b"".join(lumas[(y + j) * width + x:(y + j) * width + x + w] for j in range(h))
252 return {"width": w, "height": h, **luma_stats(values)}
253
254
255def _diagonal_sizes(nx: int, ny: int) -> list[int]:
256 """Number of tiles on each '+' diagonal ``tx + ty = s``, s = 0 .. nx + ny - 2."""
257 return [min(s, nx - 1, ny - 1, nx + ny - 2 - s) + 1 for s in range(nx + ny - 1)]
258
259
260def find_lattice(lumas: bytes, width: int, height: int) -> Optional[dict]:
261 """Dark marks in square tiles along one diagonal in N, or None.
262
263 A tile is marked when it holds dark pixels but fewer than half. For each tile size, diagonal direction
264 (``+``: ``tx + ty``, ``-``: ``tx - ty``) and period P, the tiles fall into P classes by diagonal index mod P;
265 the score of the best class is its cover (marked share) minus the rate of marked tiles outside it. The
266 smallest tile, then the smallest period, scoring within NEAR_BEST of the best wins: a lattice of period 16 also
267 covers fully at 32, and one in 8-pixel tiles at 16-pixel tiles for some phases.
268 """
269 nx4, ny4 = width // 4, height // 4
270 if nx4 < 2 or ny4 < 2:
271 return None
272 counts = [0] * (nx4 * ny4)
273 for y in range(ny4 * 4):
274 base = (y // 4) * nx4
275 row = lumas[y * width:y * width + nx4 * 4]
276 for x, v in enumerate(row):
277 if v <= DARK:
278 counts[base + x // 4] += 1
279 grids = {4: (nx4, ny4, counts)}
280 for tile in LATTICE_TILES[1:]:
281 cnx, cny, prev = grids[tile // 2]
282 nx, ny = cnx // 2, cny // 2
283 grids[tile] = (nx, ny, [prev[(2 * ty) * cnx + 2 * tx] + prev[(2 * ty) * cnx + 2 * tx + 1]
284 + prev[(2 * ty + 1) * cnx + 2 * tx] + prev[(2 * ty + 1) * cnx + 2 * tx + 1]
285 for ty in range(ny) for tx in range(nx)])
286 candidates = []
287 for tile in LATTICE_TILES:
288 nx, ny, grid = grids[tile]
289 if nx < 2 or ny < 2:
290 continue
291 marked = [(tx, ty) for ty in range(ny) for tx in range(nx) if 0 < grid[ty * nx + tx] < tile * tile / 2]
292 if len(marked) < LATTICE_MIN_TILES:
293 continue
294 sizes = _diagonal_sizes(nx, ny)
295 total = nx * ny
296 for diagonal in "+-":
297 offset = 0 if diagonal == "+" else ny - 1 # tx - ty + ny - 1 indexes the same sizes
298 hist = [0] * len(sizes)
299 for tx, ty in marked:
300 hist[(tx + ty) if diagonal == "+" else (tx - ty + offset)] += 1
301 for period in range(2, min(LATTICE_MAX_PERIOD, len(sizes)) + 1):
302 n_c, m_c, repeats = [0] * period, [0] * period, [0] * period
303 for s, size in enumerate(sizes):
304 c = (s - offset) % period
305 n_c[c] += size
306 m_c[c] += hist[s]
307 if hist[s] * 2 >= size: # this diagonal is a repeat of the pattern
308 repeats[c] += 1
309 # A class counts only with LATTICE_MIN_TILES marked tiles on LATTICE_MIN_REPEATS diagonals that
310 # are each half marked or more: one or two corner diagonals cover fully at a large period by
311 # chance, which is no repetition.
312 supported = [c for c in range(period) if n_c[c] and m_c[c] >= LATTICE_MIN_TILES
313 and repeats[c] >= LATTICE_MIN_REPEATS]
314 if not supported:
315 continue
316 best = max(supported, key=lambda c: (m_c[c] / n_c[c], -c))
317 if n_c[best] == total:
318 continue
319 cover = m_c[best] / n_c[best]
320 outside = (len(marked) - m_c[best]) / (total - n_c[best])
321 if outside > LATTICE_MAX_OUTSIDE * cover: # marks everywhere: dark texture, not a lattice
322 continue
323 candidates.append((cover - outside, tile, period, diagonal, best, m_c[best], cover))
324 if not candidates:
325 return None
326 top = max(c[0] for c in candidates)
327 if top < LATTICE_MIN_SCORE:
328 return None
329 score, tile, period, diagonal, phase, tiles, cover = min(
330 (c for c in candidates if c[0] >= NEAR_BEST * top), key=lambda c: (c[1], c[2], c[3] != "+"))
331 return {"tile": tile, "period": period, "phase": phase, "diagonal": diagonal,
332 "corner": _corner(lumas, width, height, tile, period, diagonal, phase),
333 "tiles": tiles, "cover": round(cover, 4), "score": round(score, 4)}
334
335
336def _corner(lumas: bytes, width: int, height: int, tile: int, period: int, diagonal: str, phase: int) -> str:
337 """Which corner of its tile the dark pixels of the lattice sit in: TL, TR, BL, BR, or C when centred."""
338 sx = sy = n = 0
339 for ty in range(height // tile):
340 for tx in range(width // tile):
341 if ((tx + ty) if diagonal == "+" else (tx - ty)) % period != phase:
342 continue
343 for ly in range(tile):
344 start = (ty * tile + ly) * width + tx * tile
345 for lx, v in enumerate(lumas[start:start + tile]):
346 if v <= DARK:
347 sx, sy, n = sx + lx, sy + ly, n + 1
348 if not n:
349 return "C"
350 mid = (tile - 1) / 2
351 dx, dy = sx / n - mid, sy / n - mid
352 if abs(dx) < 0.5 or abs(dy) < 0.5:
353 return "C"
354 return ("T" if dy < 0 else "B") + ("L" if dx < 0 else "R")
355
356
357def _steps(lumas: bytes, width: int, height: int, vertical: bool) -> list[list[bool]]:
358 """For each grid line (column x, or row y when ``vertical`` is False) whether each pixel along it steps.
359
360 A pixel steps when it differs from the one before it across the line by EDGE_JUMP or more and by EDGE_RATIO
361 times the larger of the steps just before and just after.
362 """
363 def at(i: int, j: int) -> int: # i across the line, j along it
364 return lumas[j * width + i] if vertical else lumas[i * width + j]
365
366 across, along = (width, height) if vertical else (height, width)
367 lines: list[list[bool]] = [[] for _ in range(across)]
368 for i in range(1, across):
369 for j in range(along):
370 jump = abs(at(i, j) - at(i - 1, j))
371 before = abs(at(i - 1, j) - at(i - 2, j)) if i >= 2 else 0
372 after = abs(at(i + 1, j) - at(i, j)) if i + 1 < across else 0
373 lines[i].append(jump >= EDGE_JUMP and jump >= EDGE_RATIO * max(before, after))
374 return lines
375
376
377def find_blocks(lumas: bytes, width: int, height: int) -> Optional[dict]:
378 """Rectangular blocks cut off from the picture around them, or None.
379
380 A grid line is an edge line when MIN_LINE_ROWS or more of its pixels step (see ``_steps``); the block width is
381 the greatest common divisor of the edge columns and the height that of the edge rows (both at least
382 MIN_BLOCK). On that grid a block edge is cut when half its pixels or more step; the blocks outside the largest
383 region joined by uncut edges are the blocks counted.
384
385 Refused: fewer than MIN_EDGE_LINES edge lines on either axis (one sharp rectangle, such as a HUD panel, has two
386 a side, and the divisor of two positions is no grid), and a share over MAX_BLOCK_SHARE (a checkerboard texture:
387 no picture around the blocks). Still misread: a grid that only ever shows multiples of the true size (every
388 cut block on even positions) reads as the larger size; blocks off the frame's origin (a grid shifted by 4)
389 read at the divisor of their edges (4x4); several sharp rectangles on a few common divisors (HUD panels,
390 window frames) can read as BLOCKS.
391 """
392 cols = _steps(lumas, width, height, True)
393 rows = _steps(lumas, width, height, False)
394 edge_cols = [x for x, line in enumerate(cols) if sum(line) >= MIN_LINE_ROWS]
395 edge_rows = [y for y, line in enumerate(rows) if sum(line) >= MIN_LINE_ROWS]
396 if len(edge_cols) < MIN_EDGE_LINES or len(edge_rows) < MIN_EDGE_LINES:
397 return None
398 bw, bh = math.gcd(*edge_cols), math.gcd(*edge_rows)
399 if bw < MIN_BLOCK or bh < MIN_BLOCK:
400 return None
401 nx, ny = width // bw, height // bh
402 if nx < 2 or ny < 2:
403 return None
404 parent = list(range(nx * ny))
405
406 def root(i: int) -> int:
407 while parent[i] != i:
408 parent[i] = parent[parent[i]]
409 i = parent[i]
410 return i
411
412 for by in range(ny):
413 for bx in range(nx):
414 if bx + 1 < nx and sum(cols[(bx + 1) * bw][by * bh:(by + 1) * bh]) * 2 < bh:
415 parent[root(by * nx + bx)] = root(by * nx + bx + 1)
416 if by + 1 < ny and sum(rows[(by + 1) * bh][bx * bw:(bx + 1) * bw]) * 2 < bw:
417 parent[root(by * nx + bx)] = root((by + 1) * nx + bx)
418 sizes: dict[int, int] = {}
419 for i in range(nx * ny):
420 r = root(i)
421 sizes[r] = sizes.get(r, 0) + 1
422 cut = nx * ny - max(sizes.values())
423 if not cut or cut > MAX_BLOCK_SHARE * nx * ny:
424 return None
425 return {"width": bw, "height": bh, "blocks": cut, "of": nx * ny, "share": round(cut / (nx * ny), 4)}
426
427
428# ---- two frames ------------------------------------------------------------------------------------------------
429
430def tile_diff(frame: Frame, reference: Frame, tolerance: int = 0) -> dict:
431 """The 8x8 tiles where a channel of ``frame`` differs from ``reference`` by more than ``tolerance``.
432
433 Tiles are listed as ``[tx, ty]`` in row order; partial tiles at the right and bottom edges count.
434 """
435 if (frame.width, frame.height) != (reference.width, reference.height):
436 raise ValueError(f"the frames differ in size: {frame.width}x{frame.height} and "
437 f"{reference.width}x{reference.height}")
438 width, height = frame.width, frame.height
439 nx, ny = -(-width // DIFF_TILE), -(-height // DIFF_TILE)
440 changed = set()
441 a, b = frame.rgb, reference.rgb
442 for y in range(height):
443 start, end = y * width * 3, (y + 1) * width * 3
444 if a[start:end] == b[start:end]:
445 continue
446 ty = y // DIFF_TILE
447 for i in range(start, end):
448 if abs(a[i] - b[i]) > tolerance:
449 changed.add((ty, (i - start) // 3 // DIFF_TILE))
450 tiles = [[tx, ty] for ty, tx in sorted(changed)]
451 box = None
452 if tiles:
453 box = [min(t[0] for t in tiles), min(t[1] for t in tiles), max(t[0] for t in tiles),
454 max(t[1] for t in tiles)]
455 return {"tile": DIFF_TILE, "changed": len(tiles), "of": nx * ny, "share": round(len(tiles) / (nx * ny), 4),
456 "box": box, "tiles": tiles}
457
458
459# ---- the block -------------------------------------------------------------------------------------------------
460
461def measure(frame: Frame, reference: Optional[Frame] = None, given: Optional[str] = None,
462 region: Optional[tuple[int, int, int, int]] = None, tolerance: int = 0) -> dict:
463 """Every number of the PICTURE block, as a dict (the ``--json`` output)."""
464 lumas = luma(frame)
465 out: dict = {"picture": 1, "frame": {"width": frame.width, "height": frame.height},
466 "luma": luma_stats(lumas), "dark_regions": dark_regions(lumas, frame.width, frame.height),
467 "lattice": find_lattice(lumas, frame.width, frame.height),
468 "blocks": find_blocks(lumas, frame.width, frame.height),
469 "reference": None, "diff": None, "region": None}
470 if reference is not None:
471 out["diff"] = tile_diff(frame, reference, tolerance)
472 out["reference"] = {"width": reference.width, "height": reference.height,
473 "luma": luma_stats(luma(reference))}
474 if region is not None:
475 out["region"] = region_stats(lumas, frame.width, region)
476 if out["luma"]["dark"] >= BLACK_NEAR_SHARE:
477 measured = "BLACK-NEAR"
478 elif out["reference"] and abs(out["luma"]["mean"] - out["reference"]["luma"]["mean"]) >= FLASH_DELTA:
479 measured = "FLASH"
480 elif out["lattice"]:
481 measured = "LATTICE"
482 elif out["blocks"]:
483 measured = "BLOCKS"
484 else:
485 measured = "OK"
486 out["class"] = {"measured": measured, "given": given}
487 return out
488
489
490def _luma_text(s: dict) -> str:
491 return f"mean {s['mean']} | min {s['min']} | max {s['max']} | sd {s['sd']} | dark {s['dark']}"
492
493
494def render(m: dict) -> str:
495 """The PICTURE block as text: numbers and classes only."""
496 f = m["frame"]
497 lines = ["PICTURE | <date UTC> | <GitHub handle> | AI-assisted: <tool>"]
498 frame = f"{f['width']}x{f['height']}"
499 if m["reference"]:
500 frame += f" | reference {m['reference']['width']}x{m['reference']['height']}"
501 lines.append(f"FRAME: {frame}")
502 lines.append(f"LUMA: {_luma_text(m['luma'])}")
503 lines.append("DARK 4x4: " + " / ".join(" ".join(f"{v:.2f}" for v in row) for row in m["dark_regions"]))
504 lat = m["lattice"]
505 lines.append("LATTICE: " + ("none" if not lat else
506 f"tile {lat['tile']} | period {lat['period']} | phase {lat['phase']} | "
507 f"diagonal {lat['diagonal']} | corner {lat['corner']} | tiles {lat['tiles']} | "
508 f"cover {lat['cover']}"))
509 blk = m["blocks"]
510 lines.append("BLOCKS: " + ("none" if not blk else
511 f"block {blk['width']}x{blk['height']} | blocks {blk['blocks']} of {blk['of']} | "
512 f"share {blk['share']}"))
513 d = m["diff"]
514 if d is None:
515 lines.append("DIFF: none (one frame)")
516 else:
517 text = f"changed {d['changed']} of {d['of']} {d['tile']}x{d['tile']} tiles | share {d['share']}"
518 if d["box"]:
519 text += " | box {},{}-{},{}".format(*d["box"])
520 listed = " ".join(f"{tx},{ty}" for tx, ty in d["tiles"][:TEXT_TILES])
521 more = len(d["tiles"]) - TEXT_TILES
522 text += f" | tiles {listed}" + (f" (+{more})" if more > 0 else "")
523 text += f" | reference luma mean {m['reference']['luma']['mean']}"
524 lines.append(f"DIFF: {text}")
525 if m["region"]:
526 r = m["region"]
527 lines.append(f"REGION: {r['width']}x{r['height']} | {_luma_text(r)}")
528 lines.append(f"CLASS: {m['class']['measured']} (measured) | given: {m['class']['given'] or 'none'}")
529 lines.append("EVIDENCE: MEASURED (tools/picture_metrics.py, 1 frame)" if d is None
530 else "EVIDENCE: MEASURED (tools/picture_metrics.py, 2 frames)")
531 return "\n".join(lines) + "\n"
532
533
534def _read(path: str, what: str) -> Frame:
535 try:
536 with open(path, "rb") as fh:
537 return decode_image(fh.read())
538 except OSError as e:
539 raise ValueError(f"{what}: cannot read it: {e.strerror or e}") from None
540 except ValueError as e:
541 raise ValueError(f"{what}: {e}") from None
542
543
544def main(argv=None) -> int:
545 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
546 ap.add_argument("frame", help="the frame to measure (PNG or binary PPM/PGM)")
547 ap.add_argument("reference", nargs="?", help="a second frame: adds the per-8x8 diff and FLASH")
548 ap.add_argument("--json", action="store_true", help="print the numbers as JSON instead of the text block")
549 ap.add_argument("--class", dest="given", choices=CLASSES, metavar="CLASS",
550 help="a class a human saw, printed as given next to the measured one: " + ", ".join(CLASSES))
551 ap.add_argument("--region", help="X,Y,W,H: also print the luma statistics of this rectangle of the frame")
552 ap.add_argument("--tolerance", type=int, default=0,
553 help="diff: ignore channel changes up to N (default 0: any change counts)")
554 a = ap.parse_args(argv)
555 if not 0 <= a.tolerance <= 255:
556 ap.error("--tolerance must be within 0..255")
557 region = None
558 if a.region is not None:
559 try:
560 region = tuple(int(v) for v in a.region.split(","))
561 except ValueError:
562 ap.error("--region takes four integers X,Y,W,H")
563 if len(region) != 4 or min(region) < 0 or not region[2] or not region[3]:
564 ap.error("--region takes four integers X,Y,W,H with W and H above 0")
565 try:
566 frame = _read(a.frame, "frame")
567 reference = _read(a.reference, "reference") if a.reference else None
568 if region and (region[0] + region[2] > frame.width or region[1] + region[3] > frame.height):
569 raise ValueError(f"--region goes past the {frame.width}x{frame.height} frame")
570 m = measure(frame, reference, a.given, region, a.tolerance)
571 except ValueError as e:
572 print(f"error: {e}", file=sys.stderr)
573 return 2
574 sys.stdout.write(json.dumps(m, indent=2) + "\n" if a.json else render(m))
575 return 0
576
577
578if __name__ == "__main__":
579 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
580 sys.stdout.reconfigure(errors="replace")
581 except (AttributeError, ValueError, OSError):
582 pass
583 sys.exit(main())
diff --git a/tools/rdna2_decode.py b/tools/rdna2_decode.py
index d66c1de2d..14195cfac 100644
--- a/tools/rdna2_decode.py
+++ b/tools/rdna2_decode.py
@@ -374,7 +374,15 @@ def _format_dpp16_ctrl(ctrl: int) -> str:
374 return f"dpp_ctrl:0x{ctrl:x}" 374 return f"dpp_ctrl:0x{ctrl:x}"
375 375
376 376
377def _format_ds_swizzle(offset16: int) -> str: 377def _format_ds_swizzle(offset16: int) -> str | None:
378 if offset16 == 0:
379 return None
380 if offset16 >= 0xE000:
381 return f"offset:swizzle(FFT,{offset16 & 0x1F})"
382 if offset16 >= 0xC000:
383 direction = (offset16 >> 10) & 1
384 size = (offset16 >> 5) & 0x1F
385 return f"offset:swizzle(ROTATE,{direction},{size})"
378 if (offset16 & 0x8000) == 0: 386 if (offset16 & 0x8000) == 0:
379 # Bitmask mode: bits [4:0] = and_mask, [9:5] = or_mask, [14:10] = xor_mask. 387 # Bitmask mode: bits [4:0] = and_mask, [9:5] = or_mask, [14:10] = xor_mask.
380 # Match LLVM's canonical aliases (SWAP, REVERSE, BROADCAST) before general BITMASK_PERM. 388 # Match LLVM's canonical aliases (SWAP, REVERSE, BROADCAST) before general BITMASK_PERM.
@@ -1107,9 +1115,11 @@ def _decode_one(code: bytes, pc: int, wave32: bool, mcpu: str) -> tuple[dict | N
1107 elif fn == "DATA1": 1115 elif fn == "DATA1":
1108 args.append(_vreg(data1, w)) 1116 args.append(_vreg(data1, w))
1109 mods = [] 1117 mods = []
1110 is_2addr = ("2_" in name or "2st64_" in name) 1118 is_2addr = name.startswith(("ds_read2", "ds_write2", "ds_wrxchg2"))
1111 if name == "ds_swizzle_b32": 1119 if name == "ds_swizzle_b32":
1112 mods.append(_format_ds_swizzle(offset0 | (offset1 << 8))) 1120 swz = _format_ds_swizzle(offset0 | (offset1 << 8))
1121 if swz:
1122 mods.append(swz)
1113 elif is_2addr: 1123 elif is_2addr:
1114 if offset0: 1124 if offset0:
1115 mods.append(f"offset0:{offset0}") 1125 mods.append(f"offset0:{offset0}")
diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py
index 7e4529e75..80b641633 100644
--- a/tools/rdna2spirv.py
+++ b/tools/rdna2spirv.py
@@ -111,6 +111,14 @@ FMA_EXACT = False # --fma exact: fused multiply-adds are emulated from si
111# maintenance8 outside gather. Implicit-LOD samples become Grad samples with the derivatives of the original 111# maintenance8 outside gather. Implicit-LOD samples become Grad samples with the derivatives of the original
112# coordinate, so a per-pixel offset doesn't change the LOD. Gathers keep their Offset (shaderImageGatherExtended). 112# coordinate, so a per-pixel offset doesn't change the LOD. Gathers keep their Offset (shaderImageGatherExtended).
113TEXEL_OFFSET_FALLBACK = False 113TEXEL_OFFSET_FALLBACK = False
114# --explicit-lod-bias: MoltenVK 1.4.2 on an Apple M3 drops VkSamplerCreateInfo::mipLodBias (ps_ssharp: neither
115# image_sample_lz with a +1 S# LOD_BIAS nor the derivative-LOD image_sample with -1 moves a level); on an Apple M5 Pro
116# the same MoltenVK applies it, so tools/lod_bias_probe.py measures it per device. With this flag the shader applies the
117# S#'s signed 5.8 LOD_BIAS (word 2 [13:0]) itself: added to the Lod of explicit-LOD samples and to the bias of
118# _b / _c_b, as a Bias operand on implicit samples, and as a 2^bias scale of Grad derivatives (lambda = log2 of
119# their length). The sampler still clamps the result to MIN_LOD..MAX_LOD. Only for a driver that drops the
120# sampler's bias: elsewhere it would count twice.
121EXPLICIT_LOD_BIAS = False
114FLOAT_CONTROLS = True # False (--no-float-controls): no SignedZeroInfNanPreserve, for drivers without the property 122FLOAT_CONTROLS = True # False (--no-float-controls): no SignedZeroInfNanPreserve, for drivers without the property
115FTZ32 = True # False (--no-ftz32): keep software flush_f32() instead of DenormFlushToZero 32 123FTZ32 = True # False (--no-ftz32): keep software flush_f32() instead of DenormFlushToZero 32
116LDS_BOUNDS = True # False (--no-lds-bounds): restore wrapped power-of-two LDS array when constant offsets stay in range 124LDS_BOUNDS = True # False (--no-lds-bounds): restore wrapped power-of-two LDS array when constant offsets stay in range
@@ -454,6 +462,23 @@ SOPC_SRC32_SPECIALS = frozenset({
454}) 462})
455SOPC_SRC64_SPECIALS = frozenset({"vcc", "exec", "null"}) 463SOPC_SRC64_SPECIALS = frozenset({"vcc", "exec", "null"})
456 464
465# Ops that read a lane-mask operand as a plain number even though the destination is not a VGPR
466# (the scalar ALU set; the v_* entries already qualify through their VGPR destinations). Ported from
467# PR #1043's lane_masks.NUMBER_READERS so scalar readers (s_add_u32 s20, s10, K after v_cmp wrote s10)
468# see the wave's mask word, not this lane's 0 / ~0 bit. Mask-preserving ops (s_mov_b32, the MASK_SOP2
469# logic ops, saveexec/wrexec) are deliberately absent: a mask moving or combining as a mask keeps the
470# per-lane bit mask_src readers rely on. _sdwa / _dpp / _dpp8 forms are excluded at the check site.
471MASK_NUMBER_READERS = frozenset((
472 "s_add_u32", "s_add_i32", "s_sub_u32", "s_sub_i32", "s_addc_u32", "s_subb_u32", "s_mul_i32",
473 "s_mul_hi_u32", "s_mul_hi_i32", "s_lshl_b32", "s_lshr_b32", "s_ashr_i32", "s_bfe_u32", "s_bfe_i32",
474 "s_min_u32", "s_min_i32", "s_max_u32", "s_max_i32", "s_brev_b32",
475 "s_lshl1_add_u32", "s_lshl2_add_u32", "s_lshl3_add_u32", "s_lshl4_add_u32",
476 "v_add_nc_u32", "v_sub_nc_u32", "v_subrev_nc_u32", "v_lshlrev_b32", "v_lshrrev_b32",
477 "v_ashrrev_i32", "v_mul_lo_u32", "v_mul_hi_u32", "v_min_u32", "v_max_u32", "v_min_i32",
478 "v_max_i32", "v_bfe_u32", "v_bfe_i32", "v_add3_u32", "v_lshl_add_u32", "v_add_lshl_u32",
479 "v_bcnt_u32_b32",
480))
481
457# Runs of lane-local VALU instructions share one `if (active)` instead of an OpSelect per VGPR write (Gen.insns). 482# Runs of lane-local VALU instructions share one `if (active)` instead of an OpSelect per VGPR write (Gen.insns).
458# VALU ops that are not lane-local: they read other lanes, write a lane mask, SCC or EXEC, or write a carry or 483# VALU ops that are not lane-local: they read other lanes, write a lane mask, SCC or EXEC, or write a carry or
459# other scalar result in every lane (v_add_co_u32's mask goes to inactive lanes too). 484# other scalar result in every lane (v_add_co_u32's mask goes to inactive lanes too).
@@ -747,7 +772,21 @@ class Gen:
747 772
748 def src_u(self, a): 773 def src_u(self, a):
749 k = a["k"] 774 k = a["k"]
750 if k in ("vgpr", "sgpr"): 775 if ((k == "sgpr" and a.get("n", 1) == 1) or
776 (k == "special" and a.get("t") in ("exec_lo", "exec_hi", "vcc", "vcc_lo", "vcc_hi"))) \
777 and self.holds_lane_mask(a) and self.mask_read_is_data():
778 # The operand holds this lane's 0 / ~0 bit of a lane mask; a data read wants the whole wave's
779 # mask word (the same in every lane), as the SOP ops that read a mask as a number already do
780 # (lane_mask_word). Until now a VALU read (v_mov_b32 v6, s16 after v_cmp wrote s16) gave each
781 # lane its own bit where hardware gives the mask itself (found by tools/crosslane_fuzz.py).
782 # Only when the destination is a VGPR: a mask moving into an SGPR, EXEC or VCC keeps this
783 # lane's bit, which mask_src readers rely on. A VGPR that stays a mask keeps the word too —
784 # mask_src extracts this lane's bit back out when a mask consumer reads one.
785 # The gather itself is eager (wave_mask): EXEC narrowing is a per-lane value in this
786 # model, not SPIR-V control flow, and mask-data readers are kept out of lane-local
787 # `if (active)` runs, so lanes off in EXEC still contribute their mask bits.
788 v = self.lane_mask_word(a)
789 elif k in ("vgpr", "sgpr"):
751 if a.get("n", 1) != 1: 790 if a.get("n", 1) != 1:
752 raise Unsupported("64-bit operand") 791 raise Unsupported("64-bit operand")
753 v = self.load_reg(k, a["r"]) 792 v = self.load_reg(k, a["r"])
@@ -788,6 +827,33 @@ class Gen:
788 v = self.sdwa_src(v, a) 827 v = self.sdwa_src(v, a)
789 return self.modify(v, a) 828 return self.modify(v, a)
790 829
830 def mask_read_is_data(self, ins=None):
831 """Whether the instruction being translated (self.cur_ins, or `ins`) consumes a lane mask as plain data.
832 A VGPR destination means the mask operand is read as a 32-bit value — the whole wave's mask word,
833 which is what hardware holds and what the VGPR then stores (a mask that stays in a VGPR keeps the
834 word too; mask_src extracts this lane's bit back out for mask consumers). Anything else — an SGPR,
835 EXEC or VCC destination — keeps this lane's 0 / ~0 bit, which mask_src readers rely on."""
836 ins = self.cur_ins if ins is None else ins
837 if ins is None:
838 return False
839 a = ins["args"]
840 if not a:
841 return False
842 if base_op(ins["op"]) in MASK_NUMBER_READERS and not ins["op"].endswith(("_sdwa", "_dpp", "_dpp8")):
843 # A scalar (or plain vector) number op reads the mask operand as data even with an SGPR
844 # destination: s_add_u32 s20, s10, K wants the wave's mask word in s20 (#1043's
845 # NUMBER_READERS). Mask moves and mask logic ops are not listed, so they keep the bit.
846 return True
847 if a[0]["k"] != "vgpr":
848 return False
849 if base_op(ins["op"]) == "v_writelane_b32":
850 # A mask parked in one lane of a VGPR comes back through v_readlane as this lane's bit: the
851 # parked SGPR slot keeps the per-lane value.
852 slot = lane_masks.lane_slot(a[0], a[2], wave64=self.wave64)
853 if slot and slot[1:] in self.parked:
854 return False
855 return True
856
791 def src_u_sign_mods(self, a): 857 def src_u_sign_mods(self, a):
792 """A 32-bit source with its VOP3 abs/neg applied as sign-bit moves on the raw bits (abs clears bit 31, neg 858 """A 32-bit source with its VOP3 abs/neg applied as sign-bit moves on the raw bits (abs clears bit 31, neg
793 flips it), for an op that only moves bits: SPIR-V FAbs/OpFNegate may quiet a signalling NaN or flush a 859 flips it), for an op that only moves bits: SPIR-V FAbs/OpFNegate may quiet a signalling NaN or flush a
@@ -2073,13 +2139,43 @@ class Gen:
2073 """True when ins only reads and writes this invocation's own registers, and its VGPR writes are the only 2139 """True when ins only reads and writes this invocation's own registers, and its VGPR writes are the only
2074 ones EXEC gates. Each invocation is one lane, so skipping it where the lane is inactive is the same as 2140 ones EXEC gates. Each invocation is one lane, so skipping it where the lane is inactive is the same as
2075 keeping the old value of everything it writes: what dst()'s per-write OpSelect does. A lane mask read as 2141 keeping the old value of everything it writes: what dst()'s per-write OpSelect does. A lane mask read as
2076 data is this lane's bit (only s_bcnt1, s_ff1 and v_mbcnt gather the whole wave's); a mask on its way 2142 data gathers the whole wave's mask word (mask_data_src keeps such instructions out of
2143 the run, since the subgroup op can't sit inside `if (active)`); a mask on its way
2077 through a VGPR (mask_writes) is written in every lane, so it stays out.""" 2144 through a VGPR (mask_writes) is written in every lane, so it stays out."""
2078 op = base_op(ins["op"]) 2145 op = base_op(ins["op"])
2079 a = ins["args"] 2146 a = ins["args"]
2080 return (op.startswith("v_") and op not in NOOPS and not op.startswith(NOT_LANE_LOCAL) and "_co_" not in op 2147 return (op.startswith("v_") and op not in NOOPS and not op.startswith(NOT_LANE_LOCAL) and "_co_" not in op
2081 and not ins["op"].endswith("_dpp") and not any(m.startswith(DPP_MODS) for m in ins["mods"]) 2148 and not ins["op"].endswith("_dpp") and not any(m.startswith(DPP_MODS) for m in ins["mods"])
2082 and bool(a) and a[0]["k"] == "vgpr" and id(ins) not in self.mask_writes) 2149 and bool(a) and a[0]["k"] == "vgpr" and id(ins) not in self.mask_writes
2150 and not self.mask_data_src(ins))
2151
2152 def mask_data_src(self, ins):
2153 """Whether ins reads a lane mask as data through src_u (a mask-holding SGPR, or EXEC/VCC), which
2154 materializes the whole wave's mask word with a subgroup op. That can't happen inside an active run
2155 (RUN_FORBIDDEN bars OpGroup there, and inactive lanes wouldn't vote), so lane_local keeps the
2156 instruction out; dst()'s per-write EXEC select gates the VGPR write instead. A mask-holding VGPR is
2157 not listed: it already stores the wave's mask word, so reading it is a plain register load. The mask
2158 state is the one lane_masks.py precomputed for this instruction (self.lane_masks), since lane_local
2159 runs before the instruction is translated."""
2160 masks = self.lane_masks.get(id(ins)) or {}
2161 return any(self._mask_data_operand(x, masks, ins) for x in ins["args"][1:])
2162
2163 def _mask_data_operand(self, x, masks, ins):
2164 """Whether src_u will materialize operand `x`'s lane mask as the wave's mask word for `ins`
2165 (a subgroup op or, under --wave64-emulate, an exchange round): `masks` is the lane_masks state
2166 for ins — self.lane_masks[id(ins)], the same dict self.cur_masks holds while translating."""
2167 if x["k"] == "sgpr":
2168 if x.get("n", 1) != 1 or x["r"] not in masks:
2169 return False
2170 elif x["k"] == "special":
2171 t = x.get("t", "")
2172 if not (t in ("exec_lo", "exec_hi") or
2173 (t in ("vcc", "vcc_lo") and "vcc" in masks) or
2174 (t == "vcc_hi" and ("vcc" if self.wave64 else "vcc_hi") in masks)):
2175 return False
2176 else:
2177 return False
2178 return self.mask_read_is_data(ins)
2083 2179
2084 def insns(self, seq): 2180 def insns(self, seq):
2085 """Translate seq, a straight run of instructions (no branch among them). A run of at least MIN_ACTIVE_RUN 2181 """Translate seq, a straight run of instructions (no branch among them). A run of at least MIN_ACTIVE_RUN
@@ -7032,6 +7128,16 @@ class Gen:
7032 ) 7128 )
7033 all_slots = sorted(set(slots) | self.scalar_spills | set(spill_read_slots)) 7129 all_slots = sorted(set(slots) | self.scalar_spills | set(spill_read_slots))
7034 self.parked = {slot: self.SGPRS + i for i, slot in enumerate(all_slots)} 7130 self.parked = {slot: self.SGPRS + i for i, slot in enumerate(all_slots)}
7131 # Instructions whose lane-mask data read will gather the wave's mask word (src_u's
7132 # lane_mask_word path) are cross-lane exchanges for the
7133 # wave64-emulation planner: it must not fold them into a lane-local region or schedule
7134 # a barrier beside them (wave64_emulate_opt checks ins["mask_words"]).
7135 for blk in blocks[0]:
7136 for ins in blk:
7137 words = tuple(i for i, x in enumerate(ins["args"])
7138 if i and self._mask_data_operand(x, self.lane_masks.get(id(ins), {}), ins))
7139 if words:
7140 ins["mask_words"] = words
7035 7141
7036 def mask_half(self, a): 7142 def mask_half(self, a):
7037 """For a 32-bit lane-mask operand in wave64, return 'lo' (lanes 0-31), 'hi' (lanes 32-63), or None.""" 7143 """For a 32-bit lane-mask operand in wave64, return 'lo' (lanes 0-31), 'hi' (lanes 32-63), or None."""
@@ -7050,6 +7156,12 @@ class Gen:
7050 return "lo" 7156 return "lo"
7051 if k == lane_masks.MASK_HI: 7157 if k == lane_masks.MASK_HI:
7052 return "hi" 7158 return "hi"
7159 if a["k"] == "vgpr" and a.get("n", 1) == 1:
7160 k = self.cur_masks.get(("v", a["r"]))
7161 if k == lane_masks.MASK_LO:
7162 return "lo"
7163 if k == lane_masks.MASK_HI:
7164 return "hi"
7053 return None 7165 return None
7054 7166
7055 def lane_mask_word(self, a): 7167 def lane_mask_word(self, a):
@@ -7380,6 +7492,23 @@ class Gen:
7380 self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") 7492 self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}")
7381 return r 7493 return r
7382 7494
7495 def _vgpr_mask_lane_bit(self, word, a):
7496 """This lane's 0 / ~0 bit of the lane-mask word `word` held by mask VGPR operand `a`: its own position
7497 of the word — and only when the lane is in the half the register covers (a MASK_LO/MASK_HI word means
7498 nothing to the other half)."""
7499 half = self.mask_half(a)
7500 if half is None:
7501 return self._scalar_word_lane_bit(word)
7502 lane = self.wave_lane()
7503 in_half = self.tmp()
7504 self.emit(f"{in_half} = OpULessThan %bool {lane} {self.cu(32)}"
7505 if half == "lo" else
7506 f"{in_half} = OpUGreaterThanEqual %bool {lane} {self.cu(32)}")
7507 bit = self._scalar_word_lane_bit(word, lane)
7508 r = self.tmp()
7509 self.emit(f"{r} = OpSelect %uint {in_half} {bit} {self.cu(0)}")
7510 return r
7511
7383 def mask_src(self, a, wide=True): 7512 def mask_src(self, a, wide=True):
7384 """A lane mask operand (sgpr pair, vcc, exec, imm) as one uint for this lane. A constant is a mask with one 7513 """A lane mask operand (sgpr pair, vcc, exec, imm) as one uint for this lane. A constant is a mask with one
7385 bit per lane, so lane L takes its bit L: of the 64-bit value (`wide`, the default: a 64-bit SALU operand or 7514 bit per lane, so lane L takes its bit L: of the 64-bit value (`wide`, the default: a 64-bit SALU operand or
@@ -7410,6 +7539,8 @@ class Gen:
7410 return self._scalar_word_lane_bit(word, lane) 7539 return self._scalar_word_lane_bit(word, lane)
7411 if a["k"] == "special" and a["t"] == "null": 7540 if a["k"] == "special" and a["t"] == "null":
7412 return self.cu(0) 7541 return self.cu(0)
7542 if a["k"] == "vgpr" and a.get("n", 1) == 1 and ("v", a["r"]) in self.cur_masks:
7543 return self._vgpr_mask_lane_bit(self.load_reg("vgpr", a["r"]), a)
7413 if a["k"] == "special" and a["t"] == "vcc_hi" and not self.wave64: 7544 if a["k"] == "special" and a["t"] == "vcc_hi" and not self.wave64:
7414 v = self.tmp() 7545 v = self.tmp()
7415 self.emit(f"{v} = OpLoad %uint %vcc_hi") 7546 self.emit(f"{v} = OpLoad %uint %vcc_hi")
@@ -8800,11 +8931,15 @@ class Gen:
8800 # lane took its own value. That is the same thing only when all lanes hold the value, and after a 8931 # lane took its own value. That is the same thing only when all lanes hold the value, and after a
8801 # kill the dead lanes don't: where the result is an address (a loop that picks a descriptor per group 8932 # kill the dead lanes don't: where the result is an address (a loop that picks a descriptor per group
8802 # of lanes), they loaded from wherever their stale register pointed. 8933 # of lanes), they loaded from wherever their stale register pointed.
8803 if a[1]["k"] == "vgpr" and ("v", a[1]["r"]) in self.cur_masks: 8934 # A VGPR that holds a lane mask keeps the whole wave's mask word, but only in the lanes a write
8804 # A lane mask that went through the vector unit (three SGPRs ORed with v_or3_b32, say). The 8935 # reached: an EXEC-gated v_mov_b32 leaves the other lanes' old word behind (SHADER-21 part 2), so
8805 # hardware reads the first lane's copy of the whole mask; here the lane's own copy is its bit. 8936 # this lane's own copy can be a stale half's word. Hardware reads the first active lane's copy —
8806 self.dst(a[0], self.src_u(a[1])) 8937 # the broadcast below. A VGPR destination is never mask-tracked (lane_masks.put ignores VGPR
8807 return 8938 # writes), so it gets the broadcast word itself, as hardware leaves it; a mask-tracked SGPR or
8939 # special destination gets this lane's bit of that word (_vgpr_mask_lane_bit, half-aware in
8940 # wave64), the per-lane value mask_src readers rely on.
8941 mask_vgpr = (a[1]["k"] == "vgpr" and a[1].get("n", 1) == 1
8942 and ("v", a[1]["r"]) in self.cur_masks)
8808 if self.x_one_lane: 8943 if self.x_one_lane:
8809 # A fold that at most one lane runs and that leaves EXEC alone: this lane is the first in EXEC. 8944 # A fold that at most one lane runs and that leaves EXEC alone: this lane is the first in EXEC.
8810 self.dst(a[0], self.src_u(a[1])) 8945 self.dst(a[0], self.src_u(a[1]))
@@ -8819,7 +8954,8 @@ class Gen:
8819 self.emit(f"{lsb} = OpExtInst %uint %glsl FindILsb {word}") 8954 self.emit(f"{lsb} = OpExtInst %uint %glsl FindILsb {word}")
8820 self.emit(f"{first} = OpSelect %uint {any_} {lsb} {self.wave32_first_running_lane()}") 8955 self.emit(f"{first} = OpSelect %uint {any_} {lsb} {self.wave32_first_running_lane()}")
8821 self.g_shuffle(r, v, first) 8956 self.g_shuffle(r, v, first)
8822 self.dst(a[0], r) 8957 res = r if a[0]["k"] == "vgpr" or not mask_vgpr else self._vgpr_mask_lane_bit(r, a[1])
8958 self.dst(a[0], res)
8823 return 8959 return
8824 if self.emulate: 8960 if self.emulate:
8825 # The wave's active lanes as two mask words and every lane's value, in one round. 8961 # The wave's active lanes as two mask words and every lane's value, in one round.
@@ -8834,7 +8970,9 @@ class Gen:
8834 self.emit(f"{h32} = OpIAdd %uint {h} {self.cu(32)}") 8970 self.emit(f"{h32} = OpIAdd %uint {h} {self.cu(32)}")
8835 self.emit(f"{fh} = OpSelect %uint {hz} {h32} {self.cu(0)}") 8971 self.emit(f"{fh} = OpSelect %uint {hz} {h32} {self.cu(0)}")
8836 self.emit(f"{first} = OpSelect %uint {lz} {l} {fh}") 8972 self.emit(f"{first} = OpSelect %uint {lz} {l} {fh}")
8837 self.dst(a[0], read(first)) 8973 w = read(first)
8974 res = w if a[0]["k"] == "vgpr" or not mask_vgpr else self._vgpr_mask_lane_bit(w, a[1])
8975 self.dst(a[0], res)
8838 return 8976 return
8839 self.uses_subgroup = self.uses_ballot = True 8977 self.uses_subgroup = self.uses_ballot = True
8840 v, act = self.src_u(a[1]), self.active_b() 8978 v, act = self.src_u(a[1]), self.active_b()
@@ -8850,7 +8988,8 @@ class Gen:
8850 fallback = self.subgroup_first_running_lane() 8988 fallback = self.subgroup_first_running_lane()
8851 self.emit(f"{first} = OpSelect %uint {any_} {lsb} {fallback}") 8989 self.emit(f"{first} = OpSelect %uint {any_} {lsb} {fallback}")
8852 self.emit(f"{r} = OpGroupNonUniformShuffle %uint {self.cu(3)} {v} {first}") 8990 self.emit(f"{r} = OpGroupNonUniformShuffle %uint {self.cu(3)} {v} {first}")
8853 self.dst(a[0], r) 8991 res = r if a[0]["k"] == "vgpr" or not mask_vgpr else self._vgpr_mask_lane_bit(r, a[1])
8992 self.dst(a[0], res)
8854 elif op in ("image_gather4_c_lz", "image_gather4_c_lz_o"): 8993 elif op in ("image_gather4_c_lz", "image_gather4_c_lz_o"):
8855 self.image_op(op, a, mods) 8994 self.image_op(op, a, mods)
8856 elif op in ("image_sample_o", "image_sample_lz_o", "image_sample_l_o", "image_sample_b_o", 8995 elif op in ("image_sample_o", "image_sample_lz_o", "image_sample_l_o", "image_sample_b_o",
@@ -10404,7 +10543,12 @@ class Gen:
10404 self.emit(f"{sat} = OpSelect %uint {ov} {self.cu(0 if 'sub' in op else 0xFFFF)} {r}") 10543 self.emit(f"{sat} = OpSelect %uint {ov} {self.cu(0 if 'sub' in op else 0xFFFF)} {r}")
10405 r = sat 10544 r = sat
10406 lo = self.tmp() 10545 lo = self.tmp()
10407 self.emit(f"{lo} = OpBitwiseAnd %uint {r} {self.cu(0xFFFF)}") 10546 # BitFieldUExtract, not OpBitwiseAnd & 0xFFFF: on NVIDIA's shader compiler an And of a value that
10547 # passed through %int ops (the signed i16 add/sub/min/max and ashr paths below) feeding the
10548 # preserve-high-half merge miscompiles the KEPT high half (measured on an RTX 4070 SUPER, wave32:
10549 # v_add_nc_i16 ... op_sel:[1,1,0] clamp wrote 0x1113AAA8 for 0x0002AAA8). Extract reads the same
10550 # low 16 bits and dodges that peephole; AMD and the interpreter are unaffected.
10551 self.emit(f"{lo} = OpBitFieldUExtract %uint {r} {self.cu(0)} {self.cu(16)}")
10408 if e64 and sb[2]: 10552 if e64 and sb[2]:
10409 # op_sel destination bit: the result goes to the high half, the low half is kept. 10553 # op_sel destination bit: the result goes to the high half, the low half is kept.
10410 if a[0]["k"] != "vgpr": 10554 if a[0]["k"] != "vgpr":
@@ -10446,7 +10590,7 @@ class Gen:
10446 self.emit(f"{sat} = OpBitcast %uint {hi_c}") 10590 self.emit(f"{sat} = OpBitcast %uint {hi_c}")
10447 r = sat 10591 r = sat
10448 lo = self.tmp() 10592 lo = self.tmp()
10449 self.emit(f"{lo} = OpBitwiseAnd %uint {r} {self.cu(0xFFFF)}") 10593 self.emit(f"{lo} = OpBitFieldUExtract %uint {r} {self.cu(0)} {self.cu(16)}") # see the nc_i16 note above: And & 0xFFFF miscompiles on NVIDIA
10450 if dhi: 10594 if dhi:
10451 old, keep, sh16, v = (self.tmp() for _ in range(4)) 10595 old, keep, sh16, v = (self.tmp() for _ in range(4))
10452 self.emit(f"{old} = OpCopyObject %uint {self.load_reg('vgpr', a[0]['r'])}") 10596 self.emit(f"{old} = OpCopyObject %uint {self.load_reg('vgpr', a[0]['r'])}")
@@ -10486,7 +10630,7 @@ class Gen:
10486 else: 10630 else:
10487 r = m 10631 r = m
10488 lo = self.tmp() 10632 lo = self.tmp()
10489 self.emit(f"{lo} = OpBitwiseAnd %uint {r} {self.cu(0xFFFF)}") 10633 self.emit(f"{lo} = OpBitFieldUExtract %uint {r} {self.cu(0)} {self.cu(16)}") # same NVIDIA And-&-0xFFFF workaround as above
10490 self.write_half16(a[0], lo, dhi) 10634 self.write_half16(a[0], lo, dhi)
10491 elif op == "v_bcnt_u32_b32": 10635 elif op == "v_bcnt_u32_b32":
10492 self._check_int32_valu(op, ins["op"], a, mods) 10636 self._check_int32_valu(op, ins["op"], a, mods)
@@ -11981,7 +12125,10 @@ class Gen:
11981 self.emit(f"{conv} = OpBitcast %uint {ci}") 12125 self.emit(f"{conv} = OpBitcast %uint {ci}")
11982 else: 12126 else:
11983 self.emit(f"{conv} = OpConvertFToU %uint {cl}") 12127 self.emit(f"{conv} = OpConvertFToU %uint {cl}")
11984 self.emit(f"{lo} = OpBitwiseAnd %uint {conv} {self.cu(0xFFFF)}") 12128 # BitFieldUExtract, not And & 0xFFFF: the signed form's conv is a Bitcast of an %int
12129 # ConvertFToS, and NVIDIA's shader compiler miscompiles that And feeding the
12130 # preserve-high-half merge (same workaround as the VOP3 16-bit integer ops).
12131 self.emit(f"{lo} = OpBitFieldUExtract %uint {conv} {self.cu(0)} {self.cu(16)}")
11985 if not dhi: 12132 if not dhi:
11986 self.write_lo16(a[0], lo) 12133 self.write_lo16(a[0], lo)
11987 else: 12134 else:
@@ -12041,7 +12188,8 @@ class Gen:
12041 self.emit(f"{conv} = OpBitcast %uint {ci}") 12188 self.emit(f"{conv} = OpBitcast %uint {ci}")
12042 else: 12189 else:
12043 self.emit(f"{conv} = OpConvertFToU %uint {rn}") 12190 self.emit(f"{conv} = OpConvertFToU %uint {rn}")
12044 self.emit(f"{lo} = OpBitwiseAnd %uint {conv} {self.cu(0xFFFF)}") 12191 # Same NVIDIA And-&-0xFFFF workaround as v_cvt_i16_f16 above.
12192 self.emit(f"{lo} = OpBitFieldUExtract %uint {conv} {self.cu(0)} {self.cu(16)}")
12045 if not dhi: 12193 if not dhi:
12046 self.write_lo16(a[0], lo) 12194 self.write_lo16(a[0], lo)
12047 else: 12195 else:
@@ -14467,6 +14615,47 @@ class Gen:
14467 self.emit(f"{one} = OpLogicalOr %bool {white} {black}") 14615 self.emit(f"{one} = OpLogicalOr %bool {white} {black}")
14468 return one 14616 return one
14469 14617
14618 def ssharp_lod_bias(self, word_reg: int):
14619 """--explicit-lod-bias: the S#'s LOD_BIAS (word 2 [13:0], signed 5.8 fixed point, -32..31 in steps of 1/256)
14620 as a float id, or None when a literal S# has a zero bias."""
14621 literal = self.sgpr_imm.get(word_reg)
14622 if literal is not None:
14623 bias = ((literal & 0x3fff) ^ 0x2000) - 0x2000
14624 return self.fconst(bias / 256.0) if bias else None
14625 word = self.load_reg("sgpr", word_reg)
14626 raw, signed, value, scaled = (self.tmp() for _ in range(4))
14627 self.emit(f"{raw} = OpBitFieldSExtract %uint {word} {self.cu(0)} {self.cu(14)}")
14628 self.emit(f"{signed} = OpBitcast %int {raw}")
14629 self.emit(f"{value} = OpConvertSToF %float {signed}")
14630 self.emit(f"{scaled} = OpFMul %float {value} {self.fconst(1.0 / 256.0)}")
14631 return scaled
14632
14633 def add_ssharp_lod_bias(self, lod: str, word_reg: int) -> str:
14634 """--explicit-lod-bias: lod + the S#'s LOD_BIAS."""
14635 b = self.ssharp_lod_bias(word_reg)
14636 if b is None:
14637 return lod
14638 out = self.tmp()
14639 self.emit(f"{out} = OpFAdd %float {lod} {b}")
14640 return out
14641
14642 def scale_grads_by_ssharp_bias(self, grads, width: int, word_reg: int):
14643 """--explicit-lod-bias: (dx, dy) * 2^LOD_BIAS, which adds the bias to the LOD the derivatives give."""
14644 b = self.ssharp_lod_bias(word_reg)
14645 if b is None:
14646 return grads
14647 k = self.tmp()
14648 self.emit(f"{k} = OpExtInst %float %glsl Exp2 {b}")
14649 out = []
14650 for g in grads:
14651 t = self.tmp()
14652 if width == 1:
14653 self.emit(f"{t} = OpFMul %float {g} {k}")
14654 else:
14655 self.emit(f"{t} = OpVectorTimesScalar %v{width}float {g} {k}")
14656 out.append(t)
14657 return tuple(out)
14658
14470 def clamp_gather_lod(self, lod: str, word_reg: int) -> str: 14659 def clamp_gather_lod(self, lod: str, word_reg: int) -> str:
14471 """Clamp to S# word 1's unsigned 4.8 MIN_LOD and MAX_LOD before choosing the fetch mip. 14660 """Clamp to S# word 1's unsigned 4.8 MIN_LOD and MAX_LOD before choosing the fetch mip.
14472 14661
@@ -15449,6 +15638,8 @@ class Gen:
15449 bias = None 15638 bias = None
15450 if kind in ("_b", "_c_b"): 15639 if kind in ("_b", "_c_b"):
15451 bias, f = f[0], f[1:] 15640 bias, f = f[0], f[1:]
15641 if EXPLICIT_LOD_BIAS:
15642 bias = self.add_ssharp_lod_bias(bias, a[3]["r"] + 2)
15452 ref = None 15643 ref = None
15453 if kind.startswith("_c"): 15644 if kind.startswith("_c"):
15454 ref, f = f[0], f[1:] 15645 ref, f = f[0], f[1:]
@@ -15464,6 +15655,8 @@ class Gen:
15464 self.emit(f"{gx} = OpCompositeConstruct %v{grad_width}float {' '.join(f[:grad_width])}") 15655 self.emit(f"{gx} = OpCompositeConstruct %v{grad_width}float {' '.join(f[:grad_width])}")
15465 self.emit(f"{gy} = OpCompositeConstruct %v{grad_width}float {' '.join(f[grad_width:2 * grad_width])}") 15656 self.emit(f"{gy} = OpCompositeConstruct %v{grad_width}float {' '.join(f[grad_width:2 * grad_width])}")
15466 grads = (gx, gy) 15657 grads = (gx, gy)
15658 if EXPLICIT_LOD_BIAS:
15659 grads = self.scale_grads_by_ssharp_bias(grads, grad_width, a[3]["r"] + 2)
15467 f = f[2 * grad_width:] 15660 f = f[2 * grad_width:]
15468 if clamp: 15661 if clamp:
15469 # The clamp is the component right after the coordinates. Under a16 an f16 pad may follow it, so 15662 # The clamp is the component right after the coordinates. Under a16 an f16 pad may follow it, so
@@ -15485,12 +15678,15 @@ class Gen:
15485 uv = self.tmp() 15678 uv = self.tmp()
15486 self.emit(f"{uv} = OpCompositeConstruct %v2float {f[0]} {f[1]}") 15679 self.emit(f"{uv} = OpCompositeConstruct %v2float {f[0]} {f[1]}")
15487 lod = f[ncoord] if kind == "_l" and len(f) > ncoord else "%f0" 15680 lod = f[ncoord] if kind == "_l" and len(f) > ncoord else "%f0"
15681 if EXPLICIT_LOD_BIAS and kind in ("_lz", "_l"):
15682 lod = self.add_ssharp_lod_bias(lod, a[3]["r"] + 2)
15488 if typed_sample: 15683 if typed_sample:
15489 float_only = self._is_float_only_image_op(op, a, mods) 15684 float_only = self._is_float_only_image_op(op, a, mods)
15490 # The aliases image_read_typed declares are indexed by the dimension it reads: a cube samples its 15685 # The aliases image_read_typed declares are indexed by the dimension it reads: a cube samples its
15491 # 6-layer 2D-array view, which is what `img` was loaded from above. 15686 # 6-layer 2D-array view, which is what `img` was loaded from above.
15492 di = self.STORE_DIMS[view_dim][0] 15687 di = self.STORE_DIMS[view_dim][0]
15493 if typed_implicit and float_only: 15688 if typed_implicit and float_only and not EXPLICIT_LOD_BIAS:
15689 # With --explicit-lod-bias the Grad path below scales the derivatives by the S# bias.
15494 def sample(image, cls, ty): 15690 def sample(image, cls, ty):
15495 sampled = sampled_image(image, cls, di) 15691 sampled = sampled_image(image, cls, di)
15496 result = self.tmp() 15692 result = self.tmp()
@@ -15503,6 +15699,8 @@ class Gen:
15503 dx, dy = self.tmp(), self.tmp() 15699 dx, dy = self.tmp(), self.tmp()
15504 self.emit(f"{dx} = OpDPdx %v2float {uv}") 15700 self.emit(f"{dx} = OpDPdx %v2float {uv}")
15505 self.emit(f"{dy} = OpDPdy %v2float {uv}") 15701 self.emit(f"{dy} = OpDPdy %v2float {uv}")
15702 if EXPLICIT_LOD_BIAS:
15703 dx, dy = self.scale_grads_by_ssharp_bias((dx, dy), 2, a[3]["r"] + 2)
15506 operands = f"Grad {dx} {dy}" 15704 operands = f"Grad {dx} {dy}"
15507 15705
15508 def sample(image, cls, ty): 15706 def sample(image, cls, ty):
@@ -15525,19 +15723,31 @@ class Gen:
15525 # PS) the base LOD is 0 (or bias for _b / _c_b) and the clamp raises it, so the explicit LOD is 15723 # PS) the base LOD is 0 (or bias for _b / _c_b) and the clamp raises it, so the explicit LOD is
15526 # max(base, clamp) and no MinLod operand. 15724 # max(base, clamp) and no MinLod operand.
15527 lod_zero = "%f0" 15725 lod_zero = "%f0"
15726 if EXPLICIT_LOD_BIAS and not implicit and kind in ("", "_c_lz", "_c"):
15727 # Outside the PS these forms are explicit-LOD samples at lod_zero (_b / _c_b carry it in their bias).
15728 # The bias goes in before the _cl clamp below: Vulkan clamps the biased LOD, max(bias, minlod).
15729 lod_zero = self.add_ssharp_lod_bias(lod_zero, a[3]["r"] + 2)
15528 if minlod is not None and not implicit and kind not in ("_d", "_b", "_c_b"): 15730 if minlod is not None and not implicit and kind not in ("_d", "_b", "_c_b"):
15731 base = lod_zero
15529 lod_zero = self.tmp() 15732 lod_zero = self.tmp()
15530 self.emit(f"{lod_zero} = OpExtInst %float %glsl FMax %f0 {minlod}") 15733 self.emit(f"{lod_zero} = OpExtInst %float %glsl FMax {base} {minlod}")
15531 bias_lod = bias 15734 bias_lod = bias
15532 if kind in ("_b", "_c_b") and not implicit and minlod is not None: 15735 if kind in ("_b", "_c_b") and not implicit and minlod is not None:
15533 bias_lod = self.tmp() 15736 bias_lod = self.tmp()
15534 self.emit(f"{bias_lod} = OpExtInst %float %glsl FMax {bias} {minlod}") 15737 self.emit(f"{bias_lod} = OpExtInst %float %glsl FMax {bias} {minlod}")
15738 # Implicit samples without a bias of their own take the S# bias as a Bias operand.
15739 sbias = (self.ssharp_lod_bias(a[3]["r"] + 2)
15740 if EXPLICIT_LOD_BIAS and implicit and kind in ("", "_c") else None)
15535 grads_fb = None 15741 grads_fb = None
15536 if off is not None and TEXEL_OFFSET_FALLBACK: 15742 if off is not None and TEXEL_OFFSET_FALLBACK:
15537 fb_lod = bias_lod if (not implicit and kind in ("_b", "_c_b")) else lod 15743 fb_lod = bias_lod if (not implicit and kind in ("_b", "_c_b")) else lod
15538 uv, grads_fb = self.texel_offset_fold(img, si, uv, off, n_off, ncoord, kind, implicit, fb_lod, bias, 15744 uv, grads_fb = self.texel_offset_fold(img, si, uv, off, n_off, ncoord, kind, implicit, fb_lod, bias,
15539 a[3]) 15745 a[3])
15540 off = None 15746 off = None
15747 if grads_fb is not None and sbias is not None:
15748 # Grad, not Bias, carries these samples now: scale the derivatives instead.
15749 grads_fb = self.scale_grads_by_ssharp_bias(grads_fb, 3 if is3d else ncoord, a[3]["r"] + 2)
15750 sbias = None
15541 15751
15542 def opnd(mask, args): 15752 def opnd(mask, args):
15543 """Image operands in SPIR-V mask order: Bias / Lod, Offset (0x10), MinLod (0x80, implicit forms).""" 15753 """Image operands in SPIR-V mask order: Bias / Lod, Offset (0x10), MinLod (0x80, implicit forms)."""
@@ -15558,7 +15768,7 @@ class Gen:
15558 self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv} Grad{'|MinLod' if minlod else ''} " 15768 self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv} Grad{'|MinLod' if minlod else ''} "
15559 f"{grads_fb[0]} {grads_fb[1]}{' ' + minlod if minlod else ''}") 15769 f"{grads_fb[0]} {grads_fb[1]}{' ' + minlod if minlod else ''}")
15560 elif kind == "": 15770 elif kind == "":
15561 self.emit(f"{res} = OpImageSampleImplicitLod %v4float {si} {uv}{opnd('', '')}" if self.stage == "ps" else 15771 self.emit(f"{res} = OpImageSampleImplicitLod %v4float {si} {uv}{opnd('Bias', sbias) if sbias else opnd('', '')}" if self.stage == "ps" else
15562 f"{res} = OpImageSampleExplicitLod %v4float {si} {uv}{opnd('Lod', lod_zero)}") 15772 f"{res} = OpImageSampleExplicitLod %v4float {si} {uv}{opnd('Lod', lod_zero)}")
15563 elif kind in ("_lz", "_l"): 15773 elif kind in ("_lz", "_l"):
15564 self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv}{opnd('Lod', lod)}") 15774 self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv}{opnd('Lod', lod)}")
@@ -15570,6 +15780,8 @@ class Gen:
15570 if kind in ("_c_lz", "_c_l") or (self.stage != "ps" and kind in ("_c", "_c_b")): 15780 if kind in ("_c_lz", "_c_l") or (self.stage != "ps" and kind in ("_c", "_c_b")):
15571 # _c / _c_b outside the PS have no derivatives (base LOD 0, or bias / max(bias, minlod) for _c_b) 15781 # _c / _c_b outside the PS have no derivatives (base LOD 0, or bias / max(bias, minlod) for _c_b)
15572 d_lod = f[ncoord] if kind == "_c_l" else (bias_lod if kind == "_c_b" else lod_zero) 15782 d_lod = f[ncoord] if kind == "_c_l" else (bias_lod if kind == "_c_b" else lod_zero)
15783 if EXPLICIT_LOD_BIAS and kind == "_c_l":
15784 d_lod = self.add_ssharp_lod_bias(d_lod, a[3]["r"] + 2)
15573 self.emit(f"{d} = OpImageSampleDrefExplicitLod %float {si} {uv} {ref}{opnd('Lod', d_lod)}") 15785 self.emit(f"{d} = OpImageSampleDrefExplicitLod %float {si} {uv} {ref}{opnd('Lod', d_lod)}")
15574 elif grads_fb is not None: 15786 elif grads_fb is not None:
15575 self.emit(f"{d} = OpImageSampleDrefExplicitLod %float {si} {uv} {ref} Grad{'|MinLod' if minlod else ''} " 15787 self.emit(f"{d} = OpImageSampleDrefExplicitLod %float {si} {uv} {ref} Grad{'|MinLod' if minlod else ''} "
@@ -15577,7 +15789,7 @@ class Gen:
15577 elif kind == "_c_b": 15789 elif kind == "_c_b":
15578 self.emit(f"{d} = OpImageSampleDrefImplicitLod %float {si} {uv} {ref}{opnd('Bias', bias)}") 15790 self.emit(f"{d} = OpImageSampleDrefImplicitLod %float {si} {uv} {ref}{opnd('Bias', bias)}")
15579 else: 15791 else:
15580 self.emit(f"{d} = OpImageSampleDrefImplicitLod %float {si} {uv} {ref}{opnd('', '')}") 15792 self.emit(f"{d} = OpImageSampleDrefImplicitLod %float {si} {uv} {ref}{opnd('Bias', sbias) if sbias else opnd('', '')}")
15581 if d16: 15793 if d16:
15582 # d16: the compare result is an f16 in the low half, as in the other d16 paths below. Until 15794 # d16: the compare result is an f16 in the low half, as in the other d16 paths below. Until
15583 # 2026-11-21 it was written as f32 bits, whose low half is 0 for every result (1.0 = 0x3f800000). 15795 # 2026-11-21 it was written as f32 bits, whose low half is 0 for every result (1.0 = 0x3f800000).
@@ -15700,7 +15912,9 @@ class Gen:
15700 self.emit(f"{clamped} = OpExtInst %int %glsl SClamp {value} {self.as_int(self.cu(0xFFFF8000))} " 15912 self.emit(f"{clamped} = OpExtInst %int %glsl SClamp {value} {self.as_int(self.cu(0xFFFF8000))} "
15701 f"{self.as_int(self.cu(0x7FFF))}") 15913 f"{self.as_int(self.cu(0x7FFF))}")
15702 self.emit(f"{raw} = OpBitcast %uint {clamped}") 15914 self.emit(f"{raw} = OpBitcast %uint {clamped}")
15703 self.emit(f"{half} = OpBitwiseAnd %uint {raw} {self.cu(0xFFFF)}") 15915 # BitFieldUExtract, not And & 0xFFFF: raw is a Bitcast of an %int SClamp and the result
15916 # reaches preserve-high-half merges (d16 image/buffer stores); NVIDIA miscompiles the And.
15917 self.emit(f"{half} = OpBitFieldUExtract %uint {raw} {self.cu(0)} {self.cu(16)}")
15704 else: 15918 else:
15705 self.emit(f"{half} = OpExtInst %uint %glsl UMin {bits} {self.cu(0xFFFF)}") 15919 self.emit(f"{half} = OpExtInst %uint %glsl UMin {bits} {self.cu(0xFFFF)}")
15706 return half 15920 return half
@@ -23817,6 +24031,9 @@ def main():
23817 ap.add_argument("--texel-offset-fallback", action="store_true", 24031 ap.add_argument("--texel-offset-fallback", action="store_true",
23818 help="image_sample*_o without VK_KHR_maintenance8 (e.g. NVIDIA Pascal): fold the texel offset into " 24032 help="image_sample*_o without VK_KHR_maintenance8 (e.g. NVIDIA Pascal): fold the texel offset into "
23819 "the coordinate instead of the Offset operand") 24033 "the coordinate instead of the Offset operand")
24034 ap.add_argument("--explicit-lod-bias", action="store_true",
24035 help="apply the S# LOD_BIAS in the shader, for a driver whose sampler drops mipLodBias (measured by "
24036 "tools/lod_bias_probe.py); elsewhere the bias would count twice")
23820 ap.add_argument("--mesh-compute", action="store_true", 24037 ap.add_argument("--mesh-compute", action="store_true",
23821 help="mesh shaders become compute shaders that write their vertices and primitives to a buffer " 24038 help="mesh shaders become compute shaders that write their vertices and primitives to a buffer "
23822 "(metadata: mesh_compute), drawn by tools/mesh_compute_vs.py, for devices without " 24039 "(metadata: mesh_compute), drawn by tools/mesh_compute_vs.py, for devices without "
@@ -23898,7 +24115,7 @@ def main():
23898 LOOP_LIMIT = a.loop_limit 24115 LOOP_LIMIT = a.loop_limit
23899 MAX_STRUCTURED_DEPTH = a.max_structured_depth 24116 MAX_STRUCTURED_DEPTH = a.max_structured_depth
23900 global INTEGER_DOT_FALLBACK 24117 global INTEGER_DOT_FALLBACK
23901 global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, MESH_COMPUTE, FMA_KHR, SHADER_CLOCK, F16_HALVES, OPT_SPIRV 24118 global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, EXPLICIT_LOD_BIAS, MESH_COMPUTE, FMA_KHR, SHADER_CLOCK, F16_HALVES, OPT_SPIRV
23902 global MESH_SERIAL_WAVES 24119 global MESH_SERIAL_WAVES
23903 global PC_TAIL_UBO, ADDR_PAIR, ADDRESS_GUARD 24120 global PC_TAIL_UBO, ADDR_PAIR, ADDRESS_GUARD
23904 PC_TAIL_UBO = a.pc_tail_ubo 24121 PC_TAIL_UBO = a.pc_tail_ubo
@@ -23919,6 +24136,7 @@ def main():
23919 INTEGER_DOT_FALLBACK = a.integer_dot_fallback 24136 INTEGER_DOT_FALLBACK = a.integer_dot_fallback
23920 ADDR_PAIR = not a.int64_addresses 24137 ADDR_PAIR = not a.int64_addresses
23921 TEXEL_OFFSET_FALLBACK = a.texel_offset_fallback 24138 TEXEL_OFFSET_FALLBACK = a.texel_offset_fallback
24139 EXPLICIT_LOD_BIAS = a.explicit_lod_bias
23922 MESH_COMPUTE = a.mesh_compute 24140 MESH_COMPUTE = a.mesh_compute
23923 MESH_SERIAL_WAVES = a.mesh_serial_waves 24141 MESH_SERIAL_WAVES = a.mesh_serial_waves
23924 F16_HALVES = a.f16_interp_fallback 24142 F16_HALVES = a.f16_interp_fallback
diff --git a/tools/rpf9dump/Program.cs b/tools/rpf9dump/Program.cs
index 911ab8183..c89f08e0e 100644
--- a/tools/rpf9dump/Program.cs
+++ b/tools/rpf9dump/Program.cs
@@ -12,7 +12,7 @@ for (int i = 0; i < argv.Count; )
12{ 12{
13 if (argv[i] == "--jobs") 13 if (argv[i] == "--jobs")
14 { 14 {
15 if (i + 1 >= argv.Count || !int.TryParse(argv[i + 1], out jobs) || jobs < 1) 15 if (i + 1 >= argv.Count || !int.TryParse(argv[i + 1], NumberStyles.None, CultureInfo.InvariantCulture, out jobs) || jobs < 1)
16 { 16 {
17 Console.Error.WriteLine("--jobs must be at least 1"); 17 Console.Error.WriteLine("--jobs must be at least 1");
18 return 2; 18 return 2;
@@ -36,14 +36,18 @@ string mode = argv[0], src = Path.GetFullPath(argv[1]), outRoot = Path.GetFullPa
36long scanStart = 0; long? scanLength = null; 36long scanStart = 0; long? scanLength = null;
37for (int i = 3; i < argv.Count; i += 2) 37for (int i = 3; i < argv.Count; i += 2)
38{ 38{
39 if (argv[i] is not ("--start" or "--length"))
40 {
41 Console.Error.WriteLine($"Unknown option {argv[i]}.");
42 return 2;
43 }
39 if (i + 1 >= argv.Count || !long.TryParse(argv[i + 1], NumberStyles.None, CultureInfo.InvariantCulture, out long bytes) || bytes < 0) 44 if (i + 1 >= argv.Count || !long.TryParse(argv[i + 1], NumberStyles.None, CultureInfo.InvariantCulture, out long bytes) || bytes < 0)
40 { 45 {
41 Console.WriteLine($"{argv[i]} needs a non-negative byte count."); 46 Console.Error.WriteLine($"{argv[i]} needs a non-negative byte count.");
42 return 2; 47 return 2;
43 } 48 }
44 if (argv[i] == "--start") scanStart = bytes; 49 if (argv[i] == "--start") scanStart = bytes;
45 else if (argv[i] == "--length") scanLength = bytes; 50 else scanLength = bytes;
46 else { Console.WriteLine($"Unknown option {argv[i]}."); return 2; }
47} 51}
48bool window = scanStart != 0 || scanLength is not null; 52bool window = scanStart != 0 || scanLength is not null;
49if (window && mode is not ("models" or "textures")) 53if (window && mode is not ("models" or "textures"))
diff --git a/tools/rpf9dump/Segments.cs b/tools/rpf9dump/Segments.cs
index 206b8d5f3..69366a7fd 100644
--- a/tools/rpf9dump/Segments.cs
+++ b/tools/rpf9dump/Segments.cs
@@ -24,8 +24,11 @@ public static class RecoveredResource
24 int written = 0; 24 int written = 0;
25 foreach (var block in segments) 25 foreach (var block in segments)
26 { 26 {
27 if (block.Offset < 0 || block.StoredSize < 6 || block.Size < 0 || block.Offset + block.StoredSize > file.Length) 27 if (block.Offset < 0 || block.StoredSize < 6 || block.Size < 0
28 || block.Offset > file.Length || block.StoredSize > file.Length - block.Offset)
28 throw new InvalidDataException("A recovered block runs past the file."); 29 throw new InvalidDataException("A recovered block runs past the file.");
30 if (block.IsRaw && block.StoredSize != block.Size)
31 throw new InvalidDataException("A raw recovered block's stored and uncompressed sizes disagree.");
29 if (block.Size > data.Length - written) 32 if (block.Size > data.Length - written)
30 throw new InvalidDataException("The recovered blocks exceed the resource size."); 33 throw new InvalidDataException("The recovered blocks exceed the resource size.");
31 file.Position = block.Offset; 34 file.Position = block.Offset;
diff --git a/tools/shader_disasm.py b/tools/shader_disasm.py
index f1d4d4dda..0e4a83239 100644
--- a/tools/shader_disasm.py
+++ b/tools/shader_disasm.py
@@ -85,7 +85,7 @@ def probe(mcpu: str) -> None:
85 if p.returncode != 0 or "s_endpgm" not in p.stdout: 85 if p.returncode != 0 or "s_endpgm" not in p.stdout:
86 why = (p.stderr.strip().splitlines() or [f"exit code {p.returncode}"])[0] 86 why = (p.stderr.strip().splitlines() or [f"exit code {p.returncode}"])[0]
87 fail(f"'{' '.join(MC)}' did not disassemble an s_endpgm: {why}\n" 87 fail(f"'{' '.join(MC)}' did not disassemble an s_endpgm: {why}\n"
88 f"The disassembler needs LLVM 21+ with the AMDGPU target (docs/design.md, 'Disassembling shaders').\n" 88 f"The disassembler needs LLVM 23+ with the AMDGPU target (LLVM 21 cannot decode some pipeline-library compute programs; docs/design.md, 'Disassembling shaders').\n"
89 f"{install_hint()}") 89 f"{install_hint()}")
90 90
91 91
diff --git a/tools/vk_fuzz_run.py b/tools/vk_fuzz_run.py
index d56b59d24..0357d359b 100644
--- a/tools/vk_fuzz_run.py
+++ b/tools/vk_fuzz_run.py
@@ -18,6 +18,11 @@ wave64_text() rewrites the wave32 spellings of lane masks (vcc_lo, s20, s21) as
18cf_diff), bypassing llvm-mc while keeping the same translation and per-lane Vulkan execution path. 18cf_diff), bypassing llvm-mc while keeping the same translation and per-lane Vulkan execution path.
19For wave64 on a 32-wide GPU, LEONIDA_W64_EMULATE=1 passes --wave64-emulate to the translator. 19For wave64 on a 32-wide GPU, LEONIDA_W64_EMULATE=1 passes --wave64-emulate to the translator.
20 20
21LEONIDA_PC_TAIL_UBO=1 translates with rdna2spirv.py --pc-tail-ubo and passes the same variable to vk_compute_test
22for 128-byte push-constant devices. VK_FUZZ_SKIP_CRASH=1 records any vk_compute_test exit other than 0, 1, 2 or 77
23as a skip, including signal deaths (which Python reports as negative return codes); exits 1 and 2 stay fatal because
24they are harness/check failures, not driver crashes.
25
21opaque=True (the default of run_programs) keeps the driver from folding the program: a `v_mov_b32 vN, K` seed becomes 26opaque=True (the default of run_programs) keeps the driver from folding the program: a `v_mov_b32 vN, K` seed becomes
22`v_xor_b32 vN, K ^ FILL, vF`, where vF is read from the output buffer, which vk_compute_test fills with 0xEEEEEEEE. 27`v_xor_b32 vN, K ^ FILL, vF`, where vF is read from the output buffer, which vk_compute_test fills with 0xEEEEEEEE.
23The program computes the same values at run time, but a compiler that sees literal operands folds them itself, and 28The program computes the same values at run time, but a compiler that sees literal operands folds them itself, and
@@ -148,6 +153,11 @@ def run_programs(texts, words=4, wave=32, build=None, work_parent=None, retries=
148 emulate = wave == 64 and os.environ.get("LEONIDA_W64_EMULATE") == "1" 153 emulate = wave == 64 and os.environ.get("LEONIDA_W64_EMULATE") == "1"
149 if emulate: 154 if emulate:
150 cmd.append("--wave64-emulate") 155 cmd.append("--wave64-emulate")
156 # LEONIDA_PC_TAIL_UBO=1 (the convention the other fuzzers' --pc-tail-ubo flag sets): translate with
157 # rdna2spirv.py --pc-tail-ubo so the modules fit a device's 128-byte push-constant range; vk_compute_test
158 # reads the same variable for its own range.
159 if (os.environ.get("LEONIDA_PC_TAIL_UBO") or "").strip().lower() in ("1", "true", "yes", "on"):
160 cmd.append("--pc-tail-ubo")
151 translation = subprocess.run(cmd, capture_output=True, text=True) 161 translation = subprocess.run(cmd, capture_output=True, text=True)
152 index = {} 162 index = {}
153 index_path = os.path.join(spirv, "index.json") 163 index_path = os.path.join(spirv, "index.json")
@@ -176,6 +186,13 @@ def run_programs(texts, words=4, wave=32, build=None, work_parent=None, retries=
176 if r.returncode in (0, 77): 186 if r.returncode in (0, 77):
177 break 187 break
178 msg = (r.stdout + r.stderr).strip() 188 msg = (r.stdout + r.stderr).strip()
189 # VK_FUZZ_SKIP_CRASH=1: a vk_compute_test that dies (the AMD Windows shader compiler's access
190 # violation, exit 3221225477, or any other crash code) is recorded as a skip instead of aborting the
191 # whole batch — the crash is a driver/harness finding, not a result for this program.
192 skip_crash = (os.environ.get("VK_FUZZ_SKIP_CRASH") or "").strip().lower() in ("1", "true", "yes", "on")
193 if r.returncode not in (0, 77) and skip_crash and r.returncode not in (1, 2):
194 results[i] = f"vk_compute_test: crashed (exit {r.returncode})"
195 continue
179 if r.returncode not in (0, 77): 196 if r.returncode not in (0, 77):
180 detail = f": {msg[-400:]}" if msg else "" 197 detail = f": {msg[-400:]}" if msg else ""
181 raise RuntimeError(f"{name}: vk_compute_test exit {r.returncode}{detail}") 198 raise RuntimeError(f"{name}: vk_compute_test exit {r.returncode}{detail}")
diff --git a/tools/vk_lod_bias.py b/tools/vk_lod_bias.py
new file mode 100644
index 000000000..642e1aadc
--- /dev/null
+++ b/tools/vk_lod_bias.py
@@ -0,0 +1,351 @@
1"""Measure whether a Vulkan device applies VkSamplerCreateInfo::mipLodBias, with no built test programs.
2
3tools/vk_subgroup_info.py --lod-bias calls measure() for the device it picks and reports the answer as
4"explicit_lod_bias". The same MoltenVK 1.4.2 drops the sampler's bias on an Apple M3 and applies it on an Apple M5
5Pro (#1774), so the answer is measured, not looked up: a 4x4 R32_SFLOAT image gets 0.0 in level 0 and 1.0 in level 1
6(vkCmdClearColorImage), and one compute invocation samples it at explicit LOD 0 through a sampler with mipLodBias 0
7and one with +1 (nearest filters and mips, clamp to edge), plus once at explicit LOD 1 with no bias, writing the three
8texels to a host-visible buffer. The LOD 1 read is the control: it must return 1.0, or level 1 was never cleared (or
9mip selection is broken) and a biased 0.0 would not mean the bias was dropped.
10
11* plain 0.0, biased 1.0, level 1 1.0 -> False: the sampler applies the bias (--explicit-lod-bias would count it twice)
12* plain 0.0, biased 0.0, level 1 1.0 -> True: the sampler drops it (translate with rdna2spirv.py --explicit-lod-bias)
13* anything else, or any Vulkan error -> None, with the reason
14
15The shader is SHADER_WORDS, compiled from this GLSL with glslangValidator -V -g0 --target-env vulkan1.0:
16
17 #version 450
18 layout(local_size_x = 1) in;
19 layout(set = 0, binding = 0) uniform sampler2D plain;
20 layout(set = 0, binding = 1) uniform sampler2D biased;
21 layout(set = 0, binding = 2) buffer Out { float r[3]; };
22 void main() {
23 r[0] = textureLod(plain, vec2(0.5), 0.0).r;
24 r[1] = textureLod(biased, vec2(0.5), 0.0).r;
25 r[2] = textureLod(plain, vec2(0.5), 1.0).r;
26 }
27
28Standard library only (ctypes); 64-bit struct layouts, as vk_subgroup_info.py. No game files.
29"""
30import ctypes
31import struct
32
33SHADER_WORDS = (
34 0x07230203, 0x00010000, 0x0008000b, 0x0000002d, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, 0x00000001,
35 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, 0x0005000f, 0x00000005,
36 0x00000004, 0x6e69616d, 0x00000000, 0x00060010, 0x00000004, 0x00000011, 0x00000001, 0x00000001, 0x00000001,
37 0x00040047, 0x00000009, 0x00000006, 0x00000004, 0x00030047, 0x0000000a, 0x00000003, 0x00050048, 0x0000000a,
38 0x00000000, 0x00000023, 0x00000000, 0x00040047, 0x0000000c, 0x00000021, 0x00000002, 0x00040047, 0x0000000c,
39 0x00000022, 0x00000000, 0x00040047, 0x00000012, 0x00000021, 0x00000000, 0x00040047, 0x00000012, 0x00000022,
40 0x00000000, 0x00040047, 0x0000001f, 0x00000021, 0x00000001, 0x00040047, 0x0000001f, 0x00000022, 0x00000000,
41 0x00040047, 0x0000002c, 0x0000000b, 0x00000019, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002,
42 0x00030016, 0x00000006, 0x00000020, 0x00040015, 0x00000007, 0x00000020, 0x00000000, 0x0004002b, 0x00000007,
43 0x00000008, 0x00000003, 0x0004001c, 0x00000009, 0x00000006, 0x00000008, 0x0003001e, 0x0000000a, 0x00000009,
44 0x00040020, 0x0000000b, 0x00000002, 0x0000000a, 0x0004003b, 0x0000000b, 0x0000000c, 0x00000002, 0x00040015,
45 0x0000000d, 0x00000020, 0x00000001, 0x0004002b, 0x0000000d, 0x0000000e, 0x00000000, 0x00090019, 0x0000000f,
46 0x00000006, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x0003001b, 0x00000010,
47 0x0000000f, 0x00040020, 0x00000011, 0x00000000, 0x00000010, 0x0004003b, 0x00000011, 0x00000012, 0x00000000,
48 0x00040017, 0x00000014, 0x00000006, 0x00000002, 0x0004002b, 0x00000006, 0x00000015, 0x3f000000, 0x0005002c,
49 0x00000014, 0x00000016, 0x00000015, 0x00000015, 0x0004002b, 0x00000006, 0x00000017, 0x00000000, 0x00040017,
50 0x00000018, 0x00000006, 0x00000004, 0x0004002b, 0x00000007, 0x0000001a, 0x00000000, 0x00040020, 0x0000001c,
51 0x00000002, 0x00000006, 0x0004002b, 0x0000000d, 0x0000001e, 0x00000001, 0x0004003b, 0x00000011, 0x0000001f,
52 0x00000000, 0x0004002b, 0x0000000d, 0x00000024, 0x00000002, 0x0004002b, 0x00000006, 0x00000026, 0x3f800000,
53 0x00040017, 0x0000002a, 0x00000007, 0x00000003, 0x0004002b, 0x00000007, 0x0000002b, 0x00000001, 0x0006002c,
54 0x0000002a, 0x0000002c, 0x0000002b, 0x0000002b, 0x0000002b, 0x00050036, 0x00000002, 0x00000004, 0x00000000,
55 0x00000003, 0x000200f8, 0x00000005, 0x0004003d, 0x00000010, 0x00000013, 0x00000012, 0x00070058, 0x00000018,
56 0x00000019, 0x00000013, 0x00000016, 0x00000002, 0x00000017, 0x00050051, 0x00000006, 0x0000001b, 0x00000019,
57 0x00000000, 0x00060041, 0x0000001c, 0x0000001d, 0x0000000c, 0x0000000e, 0x0000000e, 0x0003003e, 0x0000001d,
58 0x0000001b, 0x0004003d, 0x00000010, 0x00000020, 0x0000001f, 0x00070058, 0x00000018, 0x00000021, 0x00000020,
59 0x00000016, 0x00000002, 0x00000017, 0x00050051, 0x00000006, 0x00000022, 0x00000021, 0x00000000, 0x00060041,
60 0x0000001c, 0x00000023, 0x0000000c, 0x0000000e, 0x0000001e, 0x0003003e, 0x00000023, 0x00000022, 0x0004003d,
61 0x00000010, 0x00000025, 0x00000012, 0x00070058, 0x00000018, 0x00000027, 0x00000025, 0x00000016, 0x00000002,
62 0x00000026, 0x00050051, 0x00000006, 0x00000028, 0x00000027, 0x00000000, 0x00060041, 0x0000001c, 0x00000029,
63 0x0000000c, 0x0000000e, 0x00000024, 0x0003003e, 0x00000029, 0x00000028, 0x000100fd, 0x00010038
64)
65
66u32, u64, f32, vp = ctypes.c_uint32, ctypes.c_uint64, ctypes.c_float, ctypes.c_void_p
67
68
69def _s(name, fields):
70 return type(name, (ctypes.Structure,), {"_fields_": fields})
71
72
73QueueCreateInfo = _s("QueueCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("queueFamilyIndex", u32),
74 ("queueCount", u32), ("pQueuePriorities", ctypes.POINTER(f32))])
75DeviceCreateInfo = _s("DeviceCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("queueCreateInfoCount", u32),
76 ("pQueueCreateInfos", ctypes.POINTER(QueueCreateInfo)),
77 ("enabledLayerCount", u32), ("ppEnabledLayerNames", vp),
78 ("enabledExtensionCount", u32),
79 ("ppEnabledExtensionNames", ctypes.POINTER(ctypes.c_char_p)),
80 ("pEnabledFeatures", vp)])
81QueueFamily = _s("QueueFamily", [("queueFlags", u32), ("queueCount", u32), ("timestampValidBits", u32),
82 ("granularity", u32 * 3)])
83Extent3D = _s("Extent3D", [("width", u32), ("height", u32), ("depth", u32)])
84ImageCreateInfo = _s("ImageCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("imageType", u32),
85 ("format", u32), ("extent", Extent3D), ("mipLevels", u32),
86 ("arrayLayers", u32), ("samples", u32), ("tiling", u32), ("usage", u32),
87 ("sharingMode", u32), ("queueFamilyIndexCount", u32),
88 ("pQueueFamilyIndices", vp), ("initialLayout", u32)])
89MemoryRequirements = _s("MemoryRequirements", [("size", u64), ("alignment", u64), ("memoryTypeBits", u32)])
90MemoryType = _s("MemoryType", [("propertyFlags", u32), ("heapIndex", u32)])
91MemoryHeap = _s("MemoryHeap", [("size", u64), ("flags", u32)])
92MemoryProperties = _s("MemoryProperties", [("memoryTypeCount", u32), ("memoryTypes", MemoryType * 32),
93 ("memoryHeapCount", u32), ("memoryHeaps", MemoryHeap * 16)])
94MemoryAllocateInfo = _s("MemoryAllocateInfo", [("sType", u32), ("pNext", vp), ("allocationSize", u64),
95 ("memoryTypeIndex", u32)])
96SubresourceRange = _s("SubresourceRange", [("aspectMask", u32), ("baseMipLevel", u32), ("levelCount", u32),
97 ("baseArrayLayer", u32), ("layerCount", u32)])
98ImageViewCreateInfo = _s("ImageViewCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("image", u64),
99 ("viewType", u32), ("format", u32), ("components", u32 * 4),
100 ("subresourceRange", SubresourceRange)])
101SamplerCreateInfo = _s("SamplerCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("magFilter", u32),
102 ("minFilter", u32), ("mipmapMode", u32), ("addressModeU", u32),
103 ("addressModeV", u32), ("addressModeW", u32), ("mipLodBias", f32),
104 ("anisotropyEnable", u32), ("maxAnisotropy", f32),
105 ("compareEnable", u32), ("compareOp", u32), ("minLod", f32),
106 ("maxLod", f32), ("borderColor", u32),
107 ("unnormalizedCoordinates", u32)])
108BufferCreateInfo = _s("BufferCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("size", u64),
109 ("usage", u32), ("sharingMode", u32), ("queueFamilyIndexCount", u32),
110 ("pQueueFamilyIndices", vp)])
111LayoutBinding = _s("LayoutBinding", [("binding", u32), ("descriptorType", u32), ("descriptorCount", u32),
112 ("stageFlags", u32), ("pImmutableSamplers", vp)])
113SetLayoutCreateInfo = _s("SetLayoutCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("bindingCount", u32),
114 ("pBindings", ctypes.POINTER(LayoutBinding))])
115PoolSize = _s("PoolSize", [("type", u32), ("descriptorCount", u32)])
116PoolCreateInfo = _s("PoolCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("maxSets", u32),
117 ("poolSizeCount", u32), ("pPoolSizes", ctypes.POINTER(PoolSize))])
118SetAllocateInfo = _s("SetAllocateInfo", [("sType", u32), ("pNext", vp), ("descriptorPool", u64),
119 ("descriptorSetCount", u32), ("pSetLayouts", ctypes.POINTER(u64))])
120DescriptorImageInfo = _s("DescriptorImageInfo", [("sampler", u64), ("imageView", u64), ("imageLayout", u32)])
121DescriptorBufferInfo = _s("DescriptorBufferInfo", [("buffer", u64), ("offset", u64), ("range", u64)])
122WriteDescriptorSet = _s("WriteDescriptorSet", [("sType", u32), ("pNext", vp), ("dstSet", u64), ("dstBinding", u32),
123 ("dstArrayElement", u32), ("descriptorCount", u32),
124 ("descriptorType", u32),
125 ("pImageInfo", ctypes.POINTER(DescriptorImageInfo)),
126 ("pBufferInfo", ctypes.POINTER(DescriptorBufferInfo)),
127 ("pTexelBufferView", vp)])
128ShaderModuleCreateInfo = _s("ShaderModuleCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32),
129 ("codeSize", ctypes.c_size_t), ("pCode", ctypes.POINTER(u32))])
130PipelineLayoutCreateInfo = _s("PipelineLayoutCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32),
131 ("setLayoutCount", u32),
132 ("pSetLayouts", ctypes.POINTER(u64)),
133 ("pushConstantRangeCount", u32),
134 ("pPushConstantRanges", vp)])
135StageCreateInfo = _s("StageCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("stage", u32),
136 ("module", u64), ("pName", ctypes.c_char_p), ("pSpecializationInfo", vp)])
137ComputePipelineCreateInfo = _s("ComputePipelineCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32),
138 ("stage", StageCreateInfo), ("layout", u64),
139 ("basePipelineHandle", u64),
140 ("basePipelineIndex", ctypes.c_int32)])
141CommandPoolCreateInfo = _s("CommandPoolCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32),
142 ("queueFamilyIndex", u32)])
143CommandBufferAllocateInfo = _s("CommandBufferAllocateInfo", [("sType", u32), ("pNext", vp), ("commandPool", u64),
144 ("level", u32), ("commandBufferCount", u32)])
145CommandBufferBeginInfo = _s("CommandBufferBeginInfo", [("sType", u32), ("pNext", vp), ("flags", u32),
146 ("pInheritanceInfo", vp)])
147ImageMemoryBarrier = _s("ImageMemoryBarrier", [("sType", u32), ("pNext", vp), ("srcAccessMask", u32),
148 ("dstAccessMask", u32), ("oldLayout", u32), ("newLayout", u32),
149 ("srcQueueFamilyIndex", u32), ("dstQueueFamilyIndex", u32),
150 ("image", u64), ("subresourceRange", SubresourceRange)])
151BufferMemoryBarrier = _s("BufferMemoryBarrier", [("sType", u32), ("pNext", vp), ("srcAccessMask", u32),
152 ("dstAccessMask", u32), ("srcQueueFamilyIndex", u32),
153 ("dstQueueFamilyIndex", u32), ("buffer", u64), ("offset", u64),
154 ("size", u64)])
155SubmitInfo = _s("SubmitInfo", [("sType", u32), ("pNext", vp), ("waitSemaphoreCount", u32), ("pWaitSemaphores", vp),
156 ("pWaitDstStageMask", vp), ("commandBufferCount", u32),
157 ("pCommandBuffers", ctypes.POINTER(vp)), ("signalSemaphoreCount", u32),
158 ("pSignalSemaphores", vp)])
159FenceCreateInfo = _s("FenceCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32)])
160
161R32_SFLOAT, LEVELS, SIZE = 100, 2, 4
162QUEUE_COMPUTE = 0x2
163IGNORED = 0xFFFFFFFF
164WHOLE = 0xFFFFFFFFFFFFFFFF
165
166
167class VkFailure(RuntimeError):
168 pass
169
170
171def _check(name, result):
172 if result != 0:
173 raise VkFailure(f"{name} failed ({result})")
174
175
176def _proto(vk):
177 """argtypes for every call measure() makes (all pointers and 64-bit handles)."""
178 names = {
179 "vkGetPhysicalDeviceQueueFamilyProperties": [vp, vp, vp],
180 "vkGetPhysicalDeviceMemoryProperties": [vp, vp],
181 "vkCreateDevice": [vp, vp, vp, vp], "vkDestroyDevice": [vp, vp], "vkGetDeviceQueue": [vp, u32, u32, vp],
182 "vkCreateImage": [vp, vp, vp, vp], "vkDestroyImage": [vp, u64, vp],
183 "vkGetImageMemoryRequirements": [vp, u64, vp], "vkGetBufferMemoryRequirements": [vp, u64, vp],
184 "vkAllocateMemory": [vp, vp, vp, vp], "vkFreeMemory": [vp, u64, vp],
185 "vkBindImageMemory": [vp, u64, u64, u64], "vkBindBufferMemory": [vp, u64, u64, u64],
186 "vkMapMemory": [vp, u64, u64, u64, u32, vp], "vkUnmapMemory": [vp, u64],
187 "vkCreateImageView": [vp, vp, vp, vp], "vkDestroyImageView": [vp, u64, vp],
188 "vkCreateSampler": [vp, vp, vp, vp], "vkDestroySampler": [vp, u64, vp],
189 "vkCreateBuffer": [vp, vp, vp, vp], "vkDestroyBuffer": [vp, u64, vp],
190 "vkCreateDescriptorSetLayout": [vp, vp, vp, vp], "vkDestroyDescriptorSetLayout": [vp, u64, vp],
191 "vkCreateDescriptorPool": [vp, vp, vp, vp], "vkDestroyDescriptorPool": [vp, u64, vp],
192 "vkAllocateDescriptorSets": [vp, vp, vp], "vkUpdateDescriptorSets": [vp, u32, vp, u32, vp],
193 "vkCreateShaderModule": [vp, vp, vp, vp], "vkDestroyShaderModule": [vp, u64, vp],
194 "vkCreatePipelineLayout": [vp, vp, vp, vp], "vkDestroyPipelineLayout": [vp, u64, vp],
195 "vkCreateComputePipelines": [vp, u64, u32, vp, vp, vp], "vkDestroyPipeline": [vp, u64, vp],
196 "vkCreateCommandPool": [vp, vp, vp, vp], "vkDestroyCommandPool": [vp, u64, vp],
197 "vkAllocateCommandBuffers": [vp, vp, vp], "vkBeginCommandBuffer": [vp, vp], "vkEndCommandBuffer": [vp],
198 "vkCmdPipelineBarrier": [vp, u32, u32, u32, u32, vp, u32, vp, u32, vp],
199 "vkCmdClearColorImage": [vp, u64, u32, vp, u32, vp],
200 "vkCmdBindPipeline": [vp, u32, u64], "vkCmdBindDescriptorSets": [vp, u32, u64, u32, u32, vp, u32, vp],
201 "vkCmdDispatch": [vp, u32, u32, u32],
202 "vkCreateFence": [vp, vp, vp, vp], "vkDestroyFence": [vp, u64, vp],
203 "vkQueueSubmit": [vp, u32, vp, u64], "vkWaitForFences": [vp, u32, vp, u32, u64],
204 }
205 for name, args in names.items():
206 getattr(vk, name).argtypes = args
207
208
209def _memory_type(props, bits, wanted):
210 for i in range(props.memoryTypeCount):
211 if bits >> i & 1 and props.memoryTypes[i].propertyFlags & wanted == wanted:
212 return i
213 raise VkFailure(f"no memory type with flags {wanted:#x}")
214
215
216def measure(vk, physical_device, extensions=()):
217 """(True | False | None, reason) for one physical device; `extensions` are its extension names (bytes)."""
218 try:
219 _proto(vk)
220 except AttributeError as e:
221 return None, f"the Vulkan library lacks a call: {e}"
222 pd = ctypes.c_void_p(physical_device) if not isinstance(physical_device, ctypes.c_void_p) else physical_device
223 count = u32()
224 vk.vkGetPhysicalDeviceQueueFamilyProperties(pd, ctypes.byref(count), None)
225 families = (QueueFamily * count.value)()
226 vk.vkGetPhysicalDeviceQueueFamilyProperties(pd, ctypes.byref(count), families)
227 family = next((i for i, f in enumerate(families) if f.queueFlags & QUEUE_COMPUTE), None)
228 if family is None:
229 return None, "no compute queue"
230 destroy = [] # (call, handle) in creation order, destroyed backwards
231 dev = ctypes.c_void_p()
232 try:
233 prio = f32(1.0)
234 qinfo = QueueCreateInfo(2, None, 0, family, 1, ctypes.pointer(prio))
235 ext = [b"VK_KHR_portability_subset"] if b"VK_KHR_portability_subset" in extensions else []
236 ext_arr = (ctypes.c_char_p * max(len(ext), 1))(*ext)
237 dinfo = DeviceCreateInfo(3, None, 0, 1, ctypes.pointer(qinfo), 0, None, len(ext), ext_arr, None)
238 _check("vkCreateDevice", vk.vkCreateDevice(pd, ctypes.byref(dinfo), None, ctypes.byref(dev)))
239 queue = ctypes.c_void_p()
240 vk.vkGetDeviceQueue(dev, family, 0, ctypes.byref(queue))
241 mem_props = MemoryProperties()
242 vk.vkGetPhysicalDeviceMemoryProperties(pd, ctypes.byref(mem_props))
243
244 def make(call, info, kind):
245 handle = u64()
246 _check(call, getattr(vk, call)(dev, ctypes.byref(info), None, ctypes.byref(handle)))
247 destroy.append((kind, handle.value))
248 return handle.value
249
250 image = make("vkCreateImage", ImageCreateInfo(14, None, 0, 1, R32_SFLOAT, Extent3D(SIZE, SIZE, 1), LEVELS, 1, 1,
251 0, 0x2 | 0x4, 0, 0, None, 0), "vkDestroyImage")
252 req = MemoryRequirements()
253 vk.vkGetImageMemoryRequirements(dev, image, ctypes.byref(req))
254 image_mem = make("vkAllocateMemory", MemoryAllocateInfo(5, None, req.size,
255 _memory_type(mem_props, req.memoryTypeBits, 0x1)),
256 "vkFreeMemory")
257 _check("vkBindImageMemory", vk.vkBindImageMemory(dev, image, image_mem, 0))
258 whole = SubresourceRange(1, 0, LEVELS, 0, 1)
259 view = make("vkCreateImageView", ImageViewCreateInfo(15, None, 0, image, 1, R32_SFLOAT, (u32 * 4)(0, 0, 0, 0),
260 whole), "vkDestroyImageView")
261 samplers = [make("vkCreateSampler", SamplerCreateInfo(31, None, 0, 0, 0, 0, 2, 2, 2, bias, 0, 1.0, 0, 0, 0.0,
262 1000.0, 0, 0), "vkDestroySampler") for bias in (0.0, 1.0)]
263 buffer = make("vkCreateBuffer", BufferCreateInfo(12, None, 0, 12, 0x20, 0, 0, None), "vkDestroyBuffer")
264 breq = MemoryRequirements()
265 vk.vkGetBufferMemoryRequirements(dev, buffer, ctypes.byref(breq))
266 buffer_mem = make("vkAllocateMemory", MemoryAllocateInfo(5, None, breq.size,
267 _memory_type(mem_props, breq.memoryTypeBits, 0x6)),
268 "vkFreeMemory")
269 _check("vkBindBufferMemory", vk.vkBindBufferMemory(dev, buffer, buffer_mem, 0))
270 bindings = (LayoutBinding * 3)(LayoutBinding(0, 1, 1, 0x20, None), LayoutBinding(1, 1, 1, 0x20, None),
271 LayoutBinding(2, 7, 1, 0x20, None))
272 set_layout = make("vkCreateDescriptorSetLayout", SetLayoutCreateInfo(32, None, 0, 3, bindings),
273 "vkDestroyDescriptorSetLayout")
274 sizes = (PoolSize * 2)(PoolSize(1, 2), PoolSize(7, 1))
275 pool = make("vkCreateDescriptorPool", PoolCreateInfo(33, None, 0, 1, 2, sizes), "vkDestroyDescriptorPool")
276 layouts = (u64 * 1)(set_layout)
277 dset = u64()
278 _check("vkAllocateDescriptorSets", vk.vkAllocateDescriptorSets(dev, ctypes.byref(
279 SetAllocateInfo(34, None, pool, 1, layouts)), ctypes.byref(dset)))
280 images = [DescriptorImageInfo(s, view, 5) for s in samplers]
281 binfo = DescriptorBufferInfo(buffer, 0, WHOLE)
282 writes = (WriteDescriptorSet * 3)(
283 WriteDescriptorSet(35, None, dset.value, 0, 0, 1, 1, ctypes.pointer(images[0]), None, None),
284 WriteDescriptorSet(35, None, dset.value, 1, 0, 1, 1, ctypes.pointer(images[1]), None, None),
285 WriteDescriptorSet(35, None, dset.value, 2, 0, 1, 7, None, ctypes.pointer(binfo), None))
286 vk.vkUpdateDescriptorSets(dev, 3, writes, 0, None)
287 code = (u32 * len(SHADER_WORDS))(*SHADER_WORDS)
288 module = make("vkCreateShaderModule", ShaderModuleCreateInfo(16, None, 0, 4 * len(SHADER_WORDS), code),
289 "vkDestroyShaderModule")
290 playout = make("vkCreatePipelineLayout", PipelineLayoutCreateInfo(30, None, 0, 1, layouts, 0, None),
291 "vkDestroyPipelineLayout")
292 cinfo = ComputePipelineCreateInfo(29, None, 0, StageCreateInfo(18, None, 0, 0x20, module, b"main", None),
293 playout, 0, -1)
294 pipeline = u64()
295 _check("vkCreateComputePipelines", vk.vkCreateComputePipelines(dev, 0, 1, ctypes.byref(cinfo), None,
296 ctypes.byref(pipeline)))
297 destroy.append(("vkDestroyPipeline", pipeline.value))
298 cpool = make("vkCreateCommandPool", CommandPoolCreateInfo(39, None, 0, family), "vkDestroyCommandPool")
299 cmd = ctypes.c_void_p()
300 _check("vkAllocateCommandBuffers", vk.vkAllocateCommandBuffers(dev, ctypes.byref(
301 CommandBufferAllocateInfo(40, None, cpool, 0, 1)), ctypes.byref(cmd)))
302 _check("vkBeginCommandBuffer", vk.vkBeginCommandBuffer(cmd, ctypes.byref(CommandBufferBeginInfo(42, None, 1,
303 None))))
304 to_dst = ImageMemoryBarrier(45, None, 0, 0x1000, 0, 7, IGNORED, IGNORED, image, whole)
305 vk.vkCmdPipelineBarrier(cmd, 0x1, 0x1000, 0, 0, None, 0, None, 1, ctypes.byref(to_dst))
306 for level, value in ((0, 0.0), (1, 1.0)):
307 color = (f32 * 4)(value, value, value, value)
308 rng = SubresourceRange(1, level, 1, 0, 1)
309 vk.vkCmdClearColorImage(cmd, image, 7, ctypes.byref(color), 1, ctypes.byref(rng))
310 to_read = ImageMemoryBarrier(45, None, 0x1000, 0x20, 7, 5, IGNORED, IGNORED, image, whole)
311 vk.vkCmdPipelineBarrier(cmd, 0x1000, 0x800, 0, 0, None, 0, None, 1, ctypes.byref(to_read))
312 vk.vkCmdBindPipeline(cmd, 1, pipeline.value)
313 sets = (u64 * 1)(dset.value)
314 vk.vkCmdBindDescriptorSets(cmd, 1, playout, 0, 1, sets, 0, None)
315 vk.vkCmdDispatch(cmd, 1, 1, 1)
316 to_host = BufferMemoryBarrier(44, None, 0x40, 0x2000, IGNORED, IGNORED, buffer, 0, WHOLE)
317 vk.vkCmdPipelineBarrier(cmd, 0x800, 0x4000, 0, 0, None, 1, ctypes.byref(to_host), 0, None)
318 _check("vkEndCommandBuffer", vk.vkEndCommandBuffer(cmd))
319 fence = make("vkCreateFence", FenceCreateInfo(8, None, 0), "vkDestroyFence")
320 cmds = (ctypes.c_void_p * 1)(cmd.value)
321 submit = SubmitInfo(4, None, 0, None, None, 1, cmds, 0, None)
322 _check("vkQueueSubmit", vk.vkQueueSubmit(queue, 1, ctypes.byref(submit), fence))
323 fences = (u64 * 1)(fence)
324 _check("vkWaitForFences", vk.vkWaitForFences(dev, 1, fences, 1, 10_000_000_000))
325 mapped = ctypes.c_void_p()
326 _check("vkMapMemory", vk.vkMapMemory(dev, buffer_mem, 0, 12, 0, ctypes.byref(mapped)))
327 plain, biased, level1 = struct.unpack("<3f", ctypes.string_at(mapped, 12))
328 vk.vkUnmapMemory(dev, buffer_mem)
329 except VkFailure as e:
330 return None, str(e)
331 finally:
332 if dev.value:
333 for call, handle in reversed(destroy):
334 getattr(vk, call)(dev, handle, None)
335 vk.vkDestroyDevice(dev, None)
336 return verdict(plain, biased, level1)
337
338
339def verdict(plain: float, biased: float, level1: float):
340 """The answer from the three texels: level 0 holds 0.0 and level 1 holds 1.0.
341
342 `level1` is the control read at explicit LOD 1: unless it is 1.0, a biased 0.0 could come from a level 1 that was
343 never cleared rather than from a dropped bias, so there is no answer.
344 """
345 if level1 != 1.0:
346 return None, f"control read at LOD 1 gave {level1}, not 1.0 (level 1 not cleared or not selected)"
347 if plain == 0.0 and biased == 1.0:
348 return False, "the sampler applies mipLodBias (+1 reads level 1)"
349 if plain == 0.0 and biased == 0.0:
350 return True, "the sampler drops mipLodBias (+1 still reads level 0)"
351 return None, f"unexpected texels: plain {plain}, biased {biased}"
diff --git a/tools/vk_subgroup_info.py b/tools/vk_subgroup_info.py
index 9844739c2..4e9f0948b 100644
--- a/tools/vk_subgroup_info.py
+++ b/tools/vk_subgroup_info.py
@@ -272,8 +272,10 @@ def device_rank(device_type: int, vendor_id: int) -> int:
272 return (0 if vendor_id == MICROSOFT_VENDOR_ID else 10) + type_rank 272 return (0 if vendor_id == MICROSOFT_VENDOR_ID else 10) + type_rank
273 273
274 274
275def query(*, stage_caps=False) -> dict: 275def query(*, stage_caps=False, lod_bias=False) -> dict:
276 """The answer for the device the runtime would pick; raises RuntimeError with the reason when there is none.""" 276 """The answer for the device the runtime would pick; raises RuntimeError with the reason when there is none.
277 lod_bias adds "explicit_lod_bias" (and its reason), which tools/vk_lod_bias.py measures on that device with one
278 small compute dispatch: True where the sampler drops mipLodBias, False where it applies it, None when unknown."""
277 if sys.maxsize <= 2**32: 279 if sys.maxsize <= 2**32:
278 # the struct sizes below are the 64-bit ones, and 32-bit Windows Vulkan is stdcall, not CDLL's cdecl 280 # the struct sizes below are the 64-bit ones, and 32-bit Windows Vulkan is stdcall, not CDLL's cdecl
279 raise RuntimeError("needs a 64-bit Python") 281 raise RuntimeError("needs a 64-bit Python")
@@ -431,14 +433,25 @@ def query(*, stage_caps=False) -> dict:
431 result.update(supported_subgroup_stages=supported_stages, 433 result.update(supported_subgroup_stages=supported_stages,
432 required_subgroup_size_stages=required_stages, 434 required_subgroup_size_stages=required_stages,
433 max_compute_workgroup_subgroups=max_workgroup_subgroups) 435 max_compute_workgroup_subgroups=max_workgroup_subgroups)
436 if lod_bias:
437 try:
438 here = os.path.dirname(os.path.abspath(__file__))
439 if here not in sys.path: # python -I leaves the script's folder off sys.path
440 sys.path.insert(0, here)
441 import vk_lod_bias # noqa: E402
442 answer, reason = vk_lod_bias.measure(
443 vk, chosen_d, device_extensions(vk, chosen_d) if chosen_extensions is None else chosen_extensions)
444 except Exception as e: # a measurement that can't run is "unknown", never a guess
445 answer, reason = None, f"{type(e).__name__}: {e}"
446 result.update(explicit_lod_bias=answer, explicit_lod_bias_reason=reason)
434 return result 447 return result
435 finally: 448 finally:
436 vk.vkDestroyInstance(inst, None) 449 vk.vkDestroyInstance(inst, None)
437 450
438 451
439def main(*, stage_caps=False) -> int: 452def main(*, stage_caps=False, lod_bias=False) -> int:
440 try: 453 try:
441 print(json.dumps(query(stage_caps=stage_caps))) 454 print(json.dumps(query(stage_caps=stage_caps, lod_bias=lod_bias)))
442 return 0 455 return 0
443 except Exception as e: # any failure means "unknown": the caller falls back to emulation 456 except Exception as e: # any failure means "unknown": the caller falls back to emulation
444 print(json.dumps({"error": f"{type(e).__name__}: {e}"})) 457 print(json.dumps({"error": f"{type(e).__name__}: {e}"}))
@@ -452,4 +465,7 @@ if __name__ == "__main__":
452 pass 465 pass
453 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) 466 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
454 parser.add_argument("--stage-caps", action="store_true", help="include raw subgroup stage masks and limits") 467 parser.add_argument("--stage-caps", action="store_true", help="include raw subgroup stage masks and limits")
455 sys.exit(main(stage_caps=parser.parse_args().stage_caps)) 468 parser.add_argument("--lod-bias", action="store_true",
469 help="measure whether the sampler applies mipLodBias (one compute dispatch; explicit_lod_bias)")
470 args = parser.parse_args()
471 sys.exit(main(stage_caps=args.stage_caps, lod_bias=args.lod_bias))
diff --git a/tools/wave64_emulate_opt.py b/tools/wave64_emulate_opt.py
index f92b1ad2b..f28b2461f 100644
--- a/tools/wave64_emulate_opt.py
+++ b/tools/wave64_emulate_opt.py
@@ -924,6 +924,9 @@ def _classify_block_body(insns, lane_masks, scc_live, mask_writes):
924 if sacc[1]: 924 if sacc[1]:
925 mem_w = True 925 mem_w = True
926 926
927 if ins.get("mask_words"): # a lane mask read as a number (rdna2spirv._mask_data_operand)
928 return False, _EMPTY_MEM_STATS, 0, (), ()
929
927 # 2. Cross-lane mask readers (`wave_mask`, `wave_equal`, live-SCC `scc_from_mask`). 930 # 2. Cross-lane mask readers (`wave_mask`, `wave_equal`, live-SCC `scc_from_mask`).
928 a = ins["args"] 931 a = ins["args"]
929 mask_chk = m[11] 932 mask_chk = m[11]
@@ -1330,6 +1333,9 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr
1330 if sacc[1]: 1333 if sacc[1]:
1331 mem_w = True 1334 mem_w = True
1332 1335
1336 if ins.get("mask_words"):
1337 clean = False
1338 continue
1333 a = ins["args"] 1339 a = ins["args"]
1334 mask_chk = m[11] 1340 mask_chk = m[11]
1335 if mask_chk: 1341 if mask_chk:
@@ -1581,7 +1587,7 @@ def _insn_may_barrier_with_meta(ins, meta, lane_masks, scc_live):
1581 if meta[1]: 1587 if meta[1]:
1582 return False 1588 return False
1583 flags = meta[8] 1589 flags = meta[8]
1584 if flags & _FLAG_ALWAYS_BARRIER or _vcc_pair_collects_mask(ins, lane_masks): 1590 if flags & _FLAG_ALWAYS_BARRIER or ins.get("mask_words") or _vcc_pair_collects_mask(ins, lane_masks):
1585 return True 1591 return True
1586 mask_chk = meta[11] 1592 mask_chk = meta[11]
1587 if not mask_chk: 1593 if not mask_chk: