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:
authorDadaCap <167002618+DadaCap@users.noreply.github.com>2026-11-24 21:09:02 +0100
committerDadaCap <167002618+DadaCap@users.noreply.github.com>2026-11-24 21:09:02 +0100
commitbc245e5046124941bbdc7bb5c3bd7c739da4e03e (patch)
tree5b780fbcbc1dd131ee635980dfe3e996ac72928f /tools
parent30450e0e96e1df700bbfa9505433c9b9940e8694 (diff)
parent58be9cdf8df9a31bc7f6c068991f1aed381f7f4d (diff)
Merge remote-tracking branch 'origin/main' into vcc-tuple-resync
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'tools')
-rw-r--r--tools/batch_glb.py5
-rw-r--r--tools/bink_play.py17
-rw-r--r--tools/boot_trace.py45
-rw-r--r--tools/d3d12_xs_surface.py6
-rw-r--r--tools/exe_sha.py1
-rw-r--r--tools/fssm_unpack.py32
-rw-r--r--tools/gallery.py3
-rw-r--r--tools/hw_oracle/drm.py24
-rw-r--r--tools/hw_oracle/runner.py14
-rw-r--r--tools/manifest_verifier.py9
-rw-r--r--tools/native_pso_hashes.py122
-rw-r--r--tools/pr_conflict_label.py1
-rw-r--r--tools/progress_dashboard.py5
-rw-r--r--tools/rdna2spirv.py58
-rw-r--r--tools/semantic_mutants.py227
-rw-r--r--tools/shader_stage_manifest.py23
-rw-r--r--tools/spirv_asm.py6
-rw-r--r--tools/spirv_asm_tables.py48
-rw-r--r--tools/stale_build.py32
-rw-r--r--tools/vk_fuzz_run.py20
20 files changed, 638 insertions, 60 deletions
diff --git a/tools/batch_glb.py b/tools/batch_glb.py
index 12f1949a0..162e939f2 100644
--- a/tools/batch_glb.py
+++ b/tools/batch_glb.py
@@ -6,7 +6,8 @@ and embed textures (.png or .dds) directly into glTF materials. A texture
6that cannot be read or decoded is left out of that model and reported (one 6that cannot be read or decoded is left out of that model and reported (one
7line each, counted in the summary), never dropped silently; a model that 7line each, counted in the summary), never dropped silently; a model that
8fails to convert is named with its error. Exit status is 1 only when a 8fails to convert is named with its error. Exit status is 1 only when a
9model failed. 9model failed. A missing input folder or an output path that cannot be created
10exits 2.
10 11
11Usage: 12Usage:
12 python -I tools/batch_glb.py <in_dir> <out_dir> [--jobs N] [--up z|y] [--textures <dir>] 13 python -I tools/batch_glb.py <in_dir> <out_dir> [--jobs N] [--up z|y] [--textures <dir>]
@@ -264,7 +265,7 @@ def main(argv: list[str] | None = None) -> int:
264 ) 265 )
265 except (ValueError, OSError) as exc: 266 except (ValueError, OSError) as exc:
266 print(f"ERROR: {exc}", file=sys.stderr) 267 print(f"ERROR: {exc}", file=sys.stderr)
267 return 1 268 return 2
268 elapsed = time.monotonic() - t0 269 elapsed = time.monotonic() - t0
269 270
270 for path, err in stats["failures"]: 271 for path, err in stats["failures"]:
diff --git a/tools/bink_play.py b/tools/bink_play.py
index 0d2edf634..ec3cae6f3 100644
--- a/tools/bink_play.py
+++ b/tools/bink_play.py
@@ -84,13 +84,16 @@ def load_names(archive, mount, use_cache=True):
84 tmp.unlink(missing_ok=True) 84 tmp.unlink(missing_ok=True)
85 if use_cache: 85 if use_cache:
86 fd, name = tempfile.mkstemp(prefix="bink_names.", suffix=".part", dir=cache.parent) 86 fd, name = tempfile.mkstemp(prefix="bink_names.", suffix=".part", dir=cache.parent)
87 with open(fd, "w", encoding="utf-8", newline="") as f: 87 try:
88 f.write("# " + key + "\n") 88 with open(fd, "w", encoding="utf-8", newline="") as f:
89 w = csv.writer(f, lineterminator="\n") 89 f.write("# " + key + "\n")
90 w.writerow(CACHE_FIELDS) 90 w = csv.writer(f, lineterminator="\n")
91 for r in rows: 91 w.writerow(CACHE_FIELDS)
92 w.writerow([r["path"], r["offset"], r["width"], r["height"], r["frames"]]) 92 for r in rows:
93 os.replace(name, cache) 93 w.writerow([r["path"], r["offset"], r["width"], r["height"], r["frames"]])
94 os.replace(name, cache)
95 finally:
96 Path(name).unlink(missing_ok=True)
94 return [(r["path"], int(r["offset"]), r["width"], r["height"], r["frames"]) for r in rows] 97 return [(r["path"], int(r["offset"]), r["width"], r["height"], r["frames"]) for r in rows]
95 98
96 99
diff --git a/tools/boot_trace.py b/tools/boot_trace.py
index db8966f79..e65ab7434 100644
--- a/tools/boot_trace.py
+++ b/tools/boot_trace.py
@@ -32,6 +32,12 @@ import re
32import sys 32import sys
33 33
34D3D12_LINE = re.compile(r"^(?:.+ : )?\[d3d12-trace\] #(\d+) (.+) (\S+)\s*$") 34D3D12_LINE = re.compile(r"^(?:.+ : )?\[d3d12-trace\] #(\d+) (.+) (\S+)\s*$")
35PACING_LINE = re.compile(
36 r"^(?:.+ : )?\[rt\] present: pacing summary "
37 r"frames=(\d+) samples=(\d+) target_us=(\d+) mean_us=(-?\d+(?:\.\d+)?) drift_us=([+-]?\d+(?:\.\d+)?) "
38 r"p50_us=(\d+) p95_us=(\d+) p99_us=(\d+) "
39 r"latency_samples=(\d+) latency_p50_us=(\d+) latency_p95_us=(\d+) latency_p99_us=(\d+)\s*$"
40)
35D3D12_PROBLEMS = ("failed", "unsupported", "refused", "partial") 41D3D12_PROBLEMS = ("failed", "unsupported", "refused", "partial")
36D3D12_OUTCOMES = frozenset((*D3D12_PROBLEMS, "called", "ok", "ignored")) 42D3D12_OUTCOMES = frozenset((*D3D12_PROBLEMS, "called", "ok", "ignored"))
37 43
@@ -216,10 +222,29 @@ def parse_d3d12(path: str, limit: int = 10) -> dict:
216 "last_seq": 0, 222 "last_seq": 0,
217 "sequence_break_count": 0, 223 "sequence_break_count": 0,
218 "sequence_breaks": [], 224 "sequence_breaks": [],
225 "frame_pacing": None,
219 } 226 }
220 with _open_text(path) as fh: 227 with _open_text(path) as fh:
221 for line in fh: 228 for line in fh:
222 match = D3D12_LINE.match(line.rstrip("\n")) 229 stripped = line.rstrip("\n")
230 pacing_match = PACING_LINE.match(stripped)
231 if pacing_match:
232 trace["frame_pacing"] = {
233 "frames": int(pacing_match.group(1)),
234 "samples": int(pacing_match.group(2)),
235 "target_us": int(pacing_match.group(3)),
236 "mean_us": float(pacing_match.group(4)),
237 "drift_us": float(pacing_match.group(5)),
238 "p50_us": int(pacing_match.group(6)),
239 "p95_us": int(pacing_match.group(7)),
240 "p99_us": int(pacing_match.group(8)),
241 "latency_samples": int(pacing_match.group(9)),
242 "latency_p50_us": int(pacing_match.group(10)),
243 "latency_p95_us": int(pacing_match.group(11)),
244 "latency_p99_us": int(pacing_match.group(12)),
245 }
246 continue
247 match = D3D12_LINE.match(stripped)
223 # A crash can truncate the final outcome. A known complete outcome is 248 # A crash can truncate the final outcome. A known complete outcome is
224 # still usable when the trace ends just before the newline. 249 # still usable when the trace ends just before the newline.
225 if not match or (not line.endswith("\n") and match.group(3) not in D3D12_OUTCOMES): 250 if not match or (not line.endswith("\n") and match.group(3) not in D3D12_OUTCOMES):
@@ -270,6 +295,7 @@ def counts_only(summary: dict) -> dict:
270 dllmain_failed=startup["dllmain"]["failed"], 295 dllmain_failed=startup["dllmain"]["failed"],
271 unimplemented_imports=len(startup["unimplemented"]), 296 unimplemented_imports=len(startup["unimplemented"]),
272 int3_skipped=len(startup["int3_skipped"]), 297 int3_skipped=len(startup["int3_skipped"]),
298 xmem_physical_pages_count=startup["kinds"].get("xmem_physical_pages", 0),
273 exit_observed=startup["exit"] is not None, 299 exit_observed=startup["exit"] is not None,
274 ) 300 )
275 if d3d12 := summary["d3d12"]: 301 if d3d12 := summary["d3d12"]:
@@ -283,6 +309,8 @@ def counts_only(summary: dict) -> dict:
283 "sequence_break_count": d3d12["sequence_break_count"], 309 "sequence_break_count": d3d12["sequence_break_count"],
284 "outcomes": outcomes, 310 "outcomes": outcomes,
285 } 311 }
312 if d3d12.get("frame_pacing") is not None:
313 counters["d3d12"]["frame_pacing"] = dict(d3d12["frame_pacing"])
286 return counters 314 return counters
287 315
288 316
@@ -305,7 +333,8 @@ def format_text(summary: dict, limit: int) -> str:
305 kinds = ", ".join(f"{k} {v}" for k, v in sorted(startup["kinds"].items())) 333 kinds = ", ".join(f"{k} {v}" for k, v in sorted(startup["kinds"].items()))
306 out.append(f" kinds: {kinds}") 334 out.append(f" kinds: {kinds}")
307 if startup["modules"]: 335 if startup["modules"]:
308 names = [m["module"] for m in startup["modules"]] 336 # A relocated module is marked: triage step 1 asks whether the executable sits at its preferred base.
337 names = [m["module"] + (" (relocated)" if m.get("relocated") else "") for m in startup["modules"]]
309 out.append(f" modules ({len(names)}): {_tail(names, limit)}") 338 out.append(f" modules ({len(names)}): {_tail(names, limit)}")
310 out.append(f" tls callbacks: {startup['tls_callbacks']}") 339 out.append(f" tls callbacks: {startup['tls_callbacks']}")
311 if callback := startup.get("last_tls_callback"): 340 if callback := startup.get("last_tls_callback"):
@@ -382,6 +411,18 @@ def format_text(summary: dict, limit: int) -> str:
382 " (the [rt] diagnostics are not summarized)" 411 " (the [rt] diagnostics are not summarized)"
383 + (f": {outcomes}" if outcomes else "") 412 + (f": {outcomes}" if outcomes else "")
384 ) 413 )
414 if fp := d3d12.get("frame_pacing"):
415 line = (
416 f" frame pacing: {fp['frames']} frame(s), {fp['samples']} interval(s), "
417 f"target {fp['target_us']} us, mean {fp['mean_us']:.1f} us (drift {fp['drift_us']:+.1f} us), "
418 f"p50/p95/p99 {fp['p50_us']}/{fp['p95_us']}/{fp['p99_us']} us"
419 )
420 if fp["latency_samples"]:
421 line += (
422 f"; origin-to-present p50/p95/p99 "
423 f"{fp['latency_p50_us']}/{fp['latency_p95_us']}/{fp['latency_p99_us']} us"
424 )
425 out.append(line)
385 if last_call := d3d12.get("last_call"): 426 if last_call := d3d12.get("last_call"):
386 out.append(f" last recorded call: #{last_call['seq']} {last_call['method']} {last_call['outcome']}") 427 out.append(f" last recorded call: #{last_call['seq']} {last_call['method']} {last_call['outcome']}")
387 if d3d12["sequence_break_count"]: 428 if d3d12["sequence_break_count"]:
diff --git a/tools/d3d12_xs_surface.py b/tools/d3d12_xs_surface.py
index 72d7d86cb..fe54de18c 100644
--- a/tools/d3d12_xs_surface.py
+++ b/tools/d3d12_xs_surface.py
@@ -404,7 +404,7 @@ def check_iid_order():
404 404
405 405
406def find_sdk_include(): 406def find_sdk_include():
407 """Return (um_dir, shared_dir) for the newest installed Windows SDK, or (None, None).""" 407 """Return (um_dir, shared_dir) for the newest installed Windows SDK with the D3D headers, or (None, None)."""
408 env = os.environ.get("WINDOWS_SDK_INCLUDE") or os.environ.get("SDK_INCLUDE") 408 env = os.environ.get("WINDOWS_SDK_INCLUDE") or os.environ.get("SDK_INCLUDE")
409 if env: 409 if env:
410 candidates = [env] 410 candidates = [env]
@@ -420,7 +420,9 @@ def find_sdk_include():
420 path = os.path.normpath(path) # "...\um\" has an empty basename 420 path = os.path.normpath(path) # "...\um\" has an empty basename
421 um = path if os.path.basename(path).lower() == "um" else os.path.join(path, "um") 421 um = path if os.path.basename(path).lower() == "um" else os.path.join(path, "um")
422 shared = os.path.join(os.path.dirname(um), "shared") 422 shared = os.path.join(os.path.dirname(um), "shared")
423 if os.path.isdir(um): 423 # A Windows Driver Kit installs its own version folder (10.0.26100.0 beside an SDK's 10.0.19041.0, say) that
424 # holds only driver headers; take the newest folder that has the D3D headers, not the newest one there is.
425 if os.path.isdir(um) and (env or os.path.isfile(os.path.join(um, "d3d12.h"))):
424 name = os.path.basename(os.path.dirname(um)) 426 name = os.path.basename(os.path.dirname(um))
425 try: 427 try:
426 key = (1, tuple(map(int, name.split(".")))) 428 key = (1, tuple(map(int, name.split("."))))
diff --git a/tools/exe_sha.py b/tools/exe_sha.py
index b42d6978c..8be64f80c 100644
--- a/tools/exe_sha.py
+++ b/tools/exe_sha.py
@@ -156,4 +156,5 @@ def main(argv: list[str] | None = None) -> int:
156 156
157 157
158if __name__ == "__main__": 158if __name__ == "__main__":
159 sys.stdout.reconfigure(errors="replace")
159 sys.exit(main()) 160 sys.exit(main())
diff --git a/tools/fssm_unpack.py b/tools/fssm_unpack.py
index 42d3658a8..85ef82c4e 100644
--- a/tools/fssm_unpack.py
+++ b/tools/fssm_unpack.py
@@ -37,7 +37,7 @@ from collections import Counter
37 37
38# `python -I` leaves the script's directory off sys.path. 38# `python -I` leaves the script's directory off sys.path.
39sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) 39sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
40from shader_stage_manifest import shader_stems # noqa: E402 40from shader_stage_manifest import shader_stages # noqa: E402
41from replace_retry import replace as replace_retry # noqa: E402 41from replace_retry import replace as replace_retry # noqa: E402
42 42
43# Defensive per-blob ceiling, not a maximum defined by the XBCH format. 43# Defensive per-blob ceiling, not a maximum defined by the XBCH format.
@@ -152,6 +152,22 @@ def unpack(dxbc: bytes, payload: str = "last"):
152 return _inflate_xbch(blob), ents 152 return _inflate_xbch(blob), ents
153 153
154 154
155def program_counts(rows: list, stages: dict) -> dict:
156 """Containers, programs (tag-0x0D payloads) and containers with more than one payload, per stage.
157
158 A container is one carved DXBC file and one row here; a program is one tag-0x0D payload in it. The two counts
159 differ wherever a container carries more than one payload (docs/shader_library.md, "Containers and programs").
160 `stages` maps a row's name to the stage the carve index recorded. A name it lacks, or one it holds without a
161 stage, is counted under None: its stage is unknown."""
162 out = {}
163 for row in rows:
164 counts = out.setdefault(stages.get(row["name"]), {"containers": 0, "programs": 0, "multi_payload": 0})
165 counts["containers"] += 1
166 counts["programs"] += row["xbch_payloads"]
167 counts["multi_payload"] += row["xbch_payloads"] > 1
168 return out
169
170
155def main(argv=None) -> int: 171def main(argv=None) -> int:
156 ap = argparse.ArgumentParser(description="Unpack the FSSM program from each carved shader container.") 172 ap = argparse.ArgumentParser(description="Unpack the FSSM program from each carved shader container.")
157 ap.add_argument("src", help="carved shader directory") 173 ap.add_argument("src", help="carved shader directory")
@@ -165,10 +181,11 @@ def main(argv=None) -> int:
165 what = "is not a folder" if os.path.exists(src) else "does not exist" 181 what = "is not a folder" if os.path.exists(src) else "does not exist"
166 print(f"ERROR: {src} {what}. Give the folder with the carved .dxbc files.", file=sys.stderr) 182 print(f"ERROR: {src} {what}. Give the folder with the carved .dxbc files.", file=sys.stderr)
167 return 2 183 return 2
184 stages = {}
168 try: 185 try:
169 if a.carve_index: 186 if a.carve_index:
170 names = shader_stems(a.carve_index, "file", ".dxbc") 187 stages = shader_stages(a.carve_index, "file", ".dxbc")
171 shaders = sorted(os.path.join(src, name + ".dxbc") for name in names) 188 shaders = sorted(os.path.join(src, name + ".dxbc") for name in stages)
172 for path in shaders: 189 for path in shaders:
173 if not os.path.isfile(path): 190 if not os.path.isfile(path):
174 raise ValueError(f"{a.carve_index}: declared shader file is missing: {path}") 191 raise ValueError(f"{a.carve_index}: declared shader file is missing: {path}")
@@ -225,6 +242,15 @@ def main(argv=None) -> int:
225 replace_retry(tmp, os.path.join(src, "fssm_index.json")) # a scanner or sync client may hold tmp briefly on Windows 242 replace_retry(tmp, os.path.join(src, "fssm_index.json")) # a scanner or sync client may hold tmp briefly on Windows
226 print("magic:", dict(Counter(r["magic"] for r in rows))) 243 print("magic:", dict(Counter(r["magic"] for r in rows)))
227 print("s_endpgm per blob:", dict(Counter(len(r["endpgm"]) for r in rows))) 244 print("s_endpgm per blob:", dict(Counter(len(r["endpgm"]) for r in rows)))
245 counts = program_counts(rows, stages)
246 print(f"programs: {sum(c['programs'] for c in counts.values())} tag-0x0D payloads in {len(rows)} containers, "
247 f"{sum(c['multi_payload'] for c in counts.values())} containers with more than one "
248 f"(--payload {a.payload} is the one unpacked)")
249 if stages: # a stage comes from the carve index; without one there is nothing to break the counts down by
250 for stage in sorted(counts, key=lambda s: (s is None, s or "")):
251 c = counts[stage]
252 print(f" {stage or 'stage unknown'}: {c['containers']} containers, {c['programs']} payloads, "
253 f"{c['multi_payload']} with more than one")
228 sizes = sorted(r["size"] for r in rows) 254 sizes = sorted(r["size"] for r in rows)
229 print(f"size min {sizes[0]}, median {sizes[len(sizes) // 2]}, max {sizes[-1]}, total {sum(sizes) / 2**20:.0f} MiB") 255 print(f"size min {sizes[0]}, median {sizes[len(sizes) // 2]}, max {sizes[-1]}, total {sum(sizes) / 2**20:.0f} MiB")
230 return 0 256 return 0
diff --git a/tools/gallery.py b/tools/gallery.py
index 2762858c3..e163a6846 100644
--- a/tools/gallery.py
+++ b/tools/gallery.py
@@ -529,6 +529,9 @@ def main(argv: list[str] | None = None) -> int:
529 port = 8080 if args.port is None else args.port 529 port = 8080 if args.port is None else args.port
530 if not 0 <= port <= 65535: 530 if not 0 <= port <= 65535:
531 parser.error("--port must be between 0 and 65535") 531 parser.error("--port must be between 0 and 65535")
532 for flag, path in (("--models-dir", args.models_dir), ("--textures-dir", args.textures_dir)):
533 if path is not None and not os.path.isdir(path):
534 parser.error(f"{flag} is not a directory: {path}")
532 try: 535 try:
533 start_server( 536 start_server(
534 port=port, 537 port=port,
diff --git a/tools/hw_oracle/drm.py b/tools/hw_oracle/drm.py
index 701bbcb84..0ea20147a 100644
--- a/tools/hw_oracle/drm.py
+++ b/tools/hw_oracle/drm.py
@@ -155,17 +155,23 @@ class DrmOracle(runner.Oracle):
155 self.node = find_node() 155 self.node = find_node()
156 self.clang = runner.find_clang() 156 self.clang = runner.find_clang()
157 self.chunk = chunk 157 self.chunk = chunk
158 owned = not workdir # a temporary directory made here is removed if the constructor fails
158 self.workdir = workdir or tempfile.mkdtemp(prefix="leonida-hw-oracle-") 159 self.workdir = workdir or tempfile.mkdtemp(prefix="leonida-hw-oracle-")
159 self._offsets, self._registers = {}, {}
160 self.exe = self._build_launcher()
161 self.arch = arch or os.environ.get("LEONIDA_HW_ARCH") or self._device_arch()
162 try: 160 try:
163 asm.family(self.arch) 161 self._offsets, self._registers = {}, {}
164 except ValueError as e: # as in runner.Oracle: an architecture without spellings is a skip 162 self.exe = self._build_launcher()
165 raise Unavailable(f"{e} (set LEONIDA_HW_ARCH)") from None 163 self.arch = arch or os.environ.get("LEONIDA_HW_ARCH") or self._device_arch()
166 self.device = self._probe() 164 try:
167 if hasattr(self, "_probe_waves"): # runner.Oracle has it once it runs kernels of both wave sizes 165 asm.family(self.arch)
168 self._probe_waves() 166 except ValueError as e: # as in runner.Oracle: an architecture without spellings is a skip
167 raise Unavailable(f"{e} (set LEONIDA_HW_ARCH)") from None
168 self.device = self._probe()
169 if hasattr(self, "_probe_waves"): # runner.Oracle has it once it runs kernels of both wave sizes
170 self._probe_waves()
171 except BaseException: # close() never runs for an object that was not built: remove the directory here
172 if owned:
173 shutil.rmtree(self.workdir, ignore_errors=True)
174 raise
169 175
170 def _build_launcher(self): 176 def _build_launcher(self):
171 with open(SOURCE, "rb") as f: 177 with open(SOURCE, "rb") as f:
diff --git a/tools/hw_oracle/runner.py b/tools/hw_oracle/runner.py
index fc9b274f9..61e926296 100644
--- a/tools/hw_oracle/runner.py
+++ b/tools/hw_oracle/runner.py
@@ -209,11 +209,17 @@ class Oracle:
209 except ValueError as e: # a GPU the kernels have no spellings for is a skip, like a missing tool 209 except ValueError as e: # a GPU the kernels have no spellings for is a skip, like a missing tool
210 raise Unavailable(f"{e} (set LEONIDA_HW_ARCH)") from None 210 raise Unavailable(f"{e} (set LEONIDA_HW_ARCH)") from None
211 self.chunk = chunk 211 self.chunk = chunk
212 owned = not workdir # a temporary directory made here is removed if the constructor fails
212 self.workdir = workdir or tempfile.mkdtemp(prefix="leonida-hw-oracle-") 213 self.workdir = workdir or tempfile.mkdtemp(prefix="leonida-hw-oracle-")
213 self.exe = self._build_launcher() 214 try:
214 self.device = self._probe() 215 self.exe = self._build_launcher()
215 self.true16 = self._needs_true16() 216 self.device = self._probe()
216 self._probe_waves() 217 self.true16 = self._needs_true16()
218 self._probe_waves()
219 except BaseException: # close() never runs for an object that was not built: remove the directory here
220 if owned:
221 shutil.rmtree(self.workdir, ignore_errors=True)
222 raise
217 223
218 def _build_launcher(self): 224 def _build_launcher(self):
219 src = os.path.join(HERE, "hw_oracle.c") 225 src = os.path.join(HERE, "hw_oracle.c")
diff --git a/tools/manifest_verifier.py b/tools/manifest_verifier.py
index 49a96f912..5fe36fcd5 100644
--- a/tools/manifest_verifier.py
+++ b/tools/manifest_verifier.py
@@ -28,6 +28,9 @@ import sys
28import time 28import time
29from typing import Callable, Optional, TextIO 29from typing import Callable, Optional, TextIO
30 30
31sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
32from report_paths import same_report_path # noqa: E402
33
31CHUNK = 8 * 1024 * 1024 34CHUNK = 8 * 1024 * 1024
32DEFAULT_MANIFEST = os.path.join(os.path.dirname(__file__), "..", "reports", "manifest.json") 35DEFAULT_MANIFEST = os.path.join(os.path.dirname(__file__), "..", "reports", "manifest.json")
33CACHE_VERSION = 1 36CACHE_VERSION = 1
@@ -326,6 +329,8 @@ def verify_manifest(
326 cache_path: Optional[str] = None, 329 cache_path: Optional[str] = None,
327) -> ManifestReport: 330) -> ManifestReport:
328 """Verifies target_dir against manifest_path, optionally in parallel.""" 331 """Verifies target_dir against manifest_path, optionally in parallel."""
332 if cache_path is not None and same_report_path(cache_path, manifest_path):
333 raise ManifestError(f"cache must not overwrite the manifest: {cache_path}")
329 try: 334 try:
330 mode = os.stat(target_dir).st_mode 335 mode = os.stat(target_dir).st_mode
331 except FileNotFoundError: 336 except FileNotFoundError:
@@ -336,6 +341,10 @@ def verify_manifest(
336 raise ManifestError(f"target path is not a directory: {target_dir}") 341 raise ManifestError(f"target path is not a directory: {target_dir}")
337 342
338 want = load_manifest(manifest_path) 343 want = load_manifest(manifest_path)
344 if cache_path is not None:
345 for rel in want:
346 if same_report_path(cache_path, os.path.join(target_dir, rel)):
347 raise ManifestError(f"cache must not overwrite a listed input: {rel}")
339 have = dict(walk(target_dir, exclude=manifest_path if cache_path is None else (manifest_path, cache_path))) 348 have = dict(walk(target_dir, exclude=manifest_path if cache_path is None else (manifest_path, cache_path)))
340 if not want and have: 349 if not want and have:
341 # A cut-short create or a mistyped --manifest would otherwise print OK without checking a file. 350 # A cut-short create or a mistyped --manifest would otherwise print OK without checking a file.
diff --git a/tools/native_pso_hashes.py b/tools/native_pso_hashes.py
new file mode 100644
index 000000000..d6316be61
--- /dev/null
+++ b/tools/native_pso_hashes.py
@@ -0,0 +1,122 @@
1"""Write <spirv>/native_hashes.txt: the HASH digest of each carved DXBC container -> its stage and path.
2
3Xbox device slot 57 creates the game's graphics pipelines from native code, and each stage's records name the
4source container by the 16-byte digest of its HASH part (docs/fspx.md, kind 7). This catalog connects that
5identifier to the original local container and the stage in the translation index.
6
7Usage: python -I tools/native_pso_hashes.py <work>/shaders/dxbc <work>/shaders/spirv
8
9Only containers in the translator's index are written. Entries sharing a digest must agree on stage and
10fssm_sha256. Adapted from enx/leonida's native graphics PSO index (commit 5c175db90).
11"""
12import json
13import os
14import re
15import sys
16import tempfile
17
18sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
19from shader_carve import parts
20
21HEADER = "# native_pso_hashes 1"
22OUT_NAME = "native_hashes.txt"
23
24
25class DigestClash(ValueError):
26 """One digest names two different programs."""
27
28
29def hash_digest(data: bytes):
30 """The 16-byte digest of a DXBC container's HASH part (after its u32 flags), or None."""
31 if data[:4] != b"DXBC":
32 return None
33 try:
34 chunk = parts(data).get("HASH")
35 except ValueError:
36 return None
37 if not chunk or chunk[1] < 20:
38 return None
39 offset, _ = chunk
40 return data[offset + 4:offset + 20]
41
42
43def build(dxbc: str, spirv: str) -> dict:
44 """{digest hex: (stage, path relative to spirv)}. Raises DigestClash when one digest names two programs."""
45 workspace = os.path.dirname(os.path.realpath(spirv))
46 if os.path.commonpath((workspace, os.path.realpath(dxbc))) != workspace:
47 raise ValueError("the carved folder must be inside the same shader workspace as the translation")
48 with open(os.path.join(spirv, "index.json"), encoding="utf-8") as f:
49 index = json.load(f)
50 if not isinstance(index, dict):
51 raise ValueError("index.json is not an object")
52 found = {}
53 for name in sorted(os.listdir(dxbc)):
54 if not name.endswith(".dxbc"):
55 continue
56 stem = name[:-5]
57 entry = index.get(stem)
58 if not isinstance(entry, dict):
59 continue
60 with open(os.path.join(dxbc, name), "rb") as f:
61 digest = hash_digest(f.read())
62 if digest is None:
63 continue
64 stage, fssm = entry.get("stage"), entry.get("fssm_sha256")
65 if (not isinstance(stage, str) or re.fullmatch(r"[a-z]+", stage) is None or
66 not isinstance(fssm, str) or re.fullmatch(r"[0-9a-f]{64}", fssm) is None):
67 raise ValueError(f"invalid translated stage or FSSM hash for {name!r}")
68 if any(c in stem for c in "\\:\t\r\n"):
69 raise ValueError(f"cannot represent this container name in the native catalog: {name!r}")
70 key = digest.hex()
71 path = os.path.relpath(os.path.join(dxbc, name), spirv).replace(os.sep, "/")
72 if key in found:
73 first = found[key]
74 if first[2] != fssm or first[0] != stage:
75 raise DigestClash(f"digest {key} names two programs: {first[3]} and {stem}")
76 continue
77 found[key] = (stage, path, fssm, stem)
78 return {k: (v[0], v[1]) for k, v in found.items()}
79
80
81def write(spirv: str, table: dict) -> str:
82 out = os.path.join(spirv, OUT_NAME)
83 tmp = tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", newline="\n", dir=spirv,
84 prefix=".native_hashes.", suffix=".tmp", delete=False)
85 try:
86 with tmp:
87 tmp.write(HEADER + "\n")
88 for key in sorted(table):
89 stage, path = table[key]
90 tmp.write(f"{key}\t{stage}\t{path}\n")
91 os.replace(tmp.name, out)
92 finally:
93 if os.path.exists(tmp.name):
94 os.unlink(tmp.name)
95 return out
96
97
98def main(argv) -> int:
99 if argv[1:] in (["-h"], ["--help"]):
100 print(__doc__.strip())
101 return 0
102 if len(argv) != 3:
103 print(__doc__.strip().splitlines()[0], file=sys.stderr)
104 print("usage: native_pso_hashes.py <dxbc dir> <spirv dir>", file=sys.stderr)
105 return 2
106 dxbc, spirv = argv[1], argv[2]
107 try:
108 table = build(dxbc, spirv)
109 out = write(spirv, table)
110 except (OSError, ValueError) as e:
111 print(f"native_pso_hashes: {e}", file=sys.stderr)
112 return 1
113 print(f"native_pso_hashes: {len(table)} digests -> {out}")
114 return 0
115
116
117if __name__ == "__main__":
118 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
119 sys.stdout.reconfigure(errors="replace")
120 except (AttributeError, ValueError, OSError):
121 pass
122 sys.exit(main(sys.argv))
diff --git a/tools/pr_conflict_label.py b/tools/pr_conflict_label.py
index 79206f9c1..69afe760e 100644
--- a/tools/pr_conflict_label.py
+++ b/tools/pr_conflict_label.py
@@ -146,4 +146,5 @@ def main(argv=None):
146 146
147 147
148if __name__ == "__main__": 148if __name__ == "__main__":
149 sys.stdout.reconfigure(errors="replace")
149 sys.exit(main()) 150 sys.exit(main())
diff --git a/tools/progress_dashboard.py b/tools/progress_dashboard.py
index 9e9d0eb28..43d3fafdb 100644
--- a/tools/progress_dashboard.py
+++ b/tools/progress_dashboard.py
@@ -5,7 +5,7 @@
5 5
6Writes, into --out only (a folder inside the repository is refused, so nothing here can be committed by accident): 6Writes, into --out only (a folder inside the repository is refused, so nothing here can be committed by accident):
7 progress.html one self-contained page (no network, no packages; open it from disk) 7 progress.html one self-contained page (no network, no packages; open it from disk)
8 snapshots/progress_<utc>.json the data behind it; a snapshot equal to the previous one is not written again 8 snapshots/progress_<utc>_<hash>.json the data behind it; an unchanged snapshot is not written again
9 history.json one summary line per snapshot, for the trend chart 9 history.json one summary line per snapshot, for the trend chart
10 unit_results.json the last --run-tests outcome, kept so a later run can show what changed since 10 unit_results.json the last --run-tests outcome, kept so a later run can show what changed since
11 11
@@ -1025,7 +1025,8 @@ def write_outputs(snap, out_dir):
1025 new = not history or history[-1]["content_hash"] != snap["content_hash"][:16] 1025 new = not history or history[-1]["content_hash"] != snap["content_hash"][:16]
1026 if new: 1026 if new:
1027 stamp = snap["generated_at"].replace("-", "").replace(":", "") 1027 stamp = snap["generated_at"].replace("-", "").replace(":", "")
1028 save_text(os.path.join(out_dir, "snapshots", f"progress_{stamp}.json"), dump_json(snap)) 1028 archive = f"progress_{stamp}_{snap['content_hash']}.json"
1029 save_text(os.path.join(out_dir, "snapshots", archive), dump_json(snap))
1029 history.append(summary_line(snap)) 1030 history.append(summary_line(snap))
1030 save_text(hist_path, dump_json(history)) 1031 save_text(hist_path, dump_json(history))
1031 save_text(os.path.join(out_dir, "progress.html"), render_page(snap, history)) 1032 save_text(os.path.join(out_dir, "progress.html"), render_page(snap, history))
diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py
index 802096fcf..85c79b637 100644
--- a/tools/rdna2spirv.py
+++ b/tools/rdna2spirv.py
@@ -1229,7 +1229,8 @@ class Gen:
1229 1229
1230 def emit_fma64(self, r, x, y, z): 1230 def emit_fma64(self, r, x, y, z):
1231 """r = x * y + z on doubles with ONE rounding, as RDNA2's f64 multiply-adds do. GLSL.std.450 Fma may round 1231 """r = x * y + z on doubles with ONE rounding, as RDNA2's f64 multiply-adds do. GLSL.std.450 Fma may round
1232 twice here as for f32, and NVIDIA's driver does (RTX 4090, 621.24: the fma(a, a, c) cancellation probe with 1232 twice here as for f32, and NVIDIA's driver does when it folds an all-constant Fma at pipeline compile time
1233 (run-time operands are fused there) (RTX 4090, 621.24: the fma(a, a, c) cancellation probe with
1233 a = 1 + 2^-30 gives 0, not 2^-60). With --fma khr it is OpFmaKHR on doubles, which needs VK_KHR_shader_fma + 1234 a = 1 + 2^-30 gives 0, not 2^-60). With --fma khr it is OpFmaKHR on doubles, which needs VK_KHR_shader_fma +
1234 shaderFmaFloat64 (feature shaderFmaFloat64 in the index). --fma exact has no f64 form and keeps Fma.""" 1235 shaderFmaFloat64 (feature shaderFmaFloat64 in the index). --fma exact has no f64 form and keeps Fma."""
1235 if FMA_KHR: 1236 if FMA_KHR:
@@ -6593,8 +6594,13 @@ class Gen:
6593 self.emit(f"{g} = OpFMul %float {v} {c}") 6594 self.emit(f"{g} = OpFMul %float {v} {c}")
6594 v = g 6595 v = g
6595 if "clamp" in mods: 6596 if "clamp" in mods:
6596 g = self.tmp() 6597 # The game's MODE has DX10_CLAMP=1, so the clamp bit turns a NaN result into +0
6597 self.emit(f"{g} = OpExtInst %float %glsl FClamp {v} %f0 %f1") 6598 # (docs/shader_validation.md). GLSL.std.450 FClamp leaves a NaN operand undefined,
6599 # so select +0 for a NaN first, as the div_fixup and cvt_pknorm clamps do.
6600 nan, safe, g = self.tmp(), self.tmp(), self.tmp()
6601 self.emit(f"{nan} = OpIsNan %bool {v}")
6602 self.emit(f"{safe} = OpSelect %float {nan} %f0 {v}")
6603 self.emit(f"{g} = OpExtInst %float %glsl FClamp {safe} %f0 %f1")
6598 return g 6604 return g
6599 return v 6605 return v
6600 6606
@@ -12436,7 +12442,9 @@ class Gen:
12436 (n == 2 and d["k"] == "special" and d["t"] == "vcc") 12442 (n == 2 and d["k"] == "special" and d["t"] == "vcc")
12437 slist_dst = d["k"] == "slist" and len(d["r"]) == n 12443 slist_dst = d["k"] == "slist" and len(d["r"]) == n
12438 base_slots = (list(range(base["r"], base["r"] + base.get("n", 1))) if base["k"] == "sgpr" 12444 base_slots = (list(range(base["r"], base["r"] + base.get("n", 1))) if base["k"] == "sgpr"
12439 else list(base["r"]) if base["k"] == "slist" else None) 12445 else list(base["r"]) if base["k"] == "slist"
12446 else ["vcc_lo", "vcc_hi"] if (base["k"] == "special" and base["t"] == "vcc")
12447 else None)
12440 if (d["k"] != "sgpr" and not single_special and not slist_dst) or base_slots is None: 12448 if (d["k"] != "sgpr" and not single_special and not slist_dst) or base_slots is None:
12441 raise Unsupported(f"{op} operands {d.get('t', d['k'])} {base.get('t', base['k'])}") 12449 raise Unsupported(f"{op} operands {d.get('t', d['k'])} {base.get('t', base['k'])}")
12442 12450
@@ -16656,14 +16664,28 @@ def sdwa_reads_dst(op: str, mods: list[str]) -> bool:
16656 and any(m.startswith(("dst_sel:BYTE_", "dst_sel:WORD_")) for m in mods)) 16664 and any(m.startswith(("dst_sel:BYTE_", "dst_sel:WORD_")) for m in mods))
16657 16665
16658 16666
16667# Ops whose VGPR destination is also a source operand (the accumulating forms, and v_swap_b32, which reads both).
16668DST_ALSO_READ = ("v_swap_b32", "v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16", "v_dot4c_i32_i8", "v_pk_fmac_f16",
16669 "v_dot2c_f32_f16", "v_dot2c_i32_i16", "v_dot2c_u32_u16", "v_dot4c_u32_u8", "v_dot8c_i32_i4",
16670 "v_dot8c_u32_u4")
16671
16672
16659# All VGPR operands of these instructions are sources, including store address and data ranges. 16673# All VGPR operands of these instructions are sources, including store address and data ranges.
16660VGPR_READ_ONLY_PREFIXES = ("exp", "buffer_store", "tbuffer_store", "image_store", "v_cmp", "ds_write", 16674VGPR_READ_ONLY_PREFIXES = ("exp", "buffer_store", "tbuffer_store", "image_store", "v_cmp", "ds_write",
16661 "global_store", "flat_store", "scratch_store") 16675 "global_store", "flat_store", "scratch_store")
16662 16676
16663 16677
16664def read_before_write_vgprs(insns): 16678def read_before_write_vgprs(insns):
16665 """VGPRs a shader reads before writing them: for a fetch-calling VS these are the fetched attributes.""" 16679 """VGPRs a shader reads before writing them: for a fetch-calling VS these are the fetched attributes.
16666 written, first = set(), [] 16680
16681 v_writelane_b32 writes one lane and keeps the others (SHADER-768), so its destination is not written by it: the
16682 kept lanes still hold what the register held at entry. They are *carried*, and become a read only when something
16683 other than v_readlane_b32 reads the register before a full write (shdann's two cases on #4297: a PS whose first
16684 touch of v0 is a writelane, then a v_mov of v0, reads the barycentric in the other lanes; a VS that spills an
16685 SGPR into one lane of v40 around the fetch call and reads it back with v_readlane never uses the entry value,
16686 so v40 is not a fetched attribute). The approximation: a v_readlane of a lane the writelane didn't write would
16687 read the entry value, and is not counted."""
16688 written, first, carried = set(), [], set()
16667 for ins in insns: 16689 for ins in insns:
16668 a, op = ins["args"], ins["op"] 16690 a, op = ins["args"], ins["op"]
16669 if not a: 16691 if not a:
@@ -16676,17 +16698,22 @@ def read_before_write_vgprs(insns):
16676 regs += range(x["r"], x["r"] + x.get("n", 1)) 16698 regs += range(x["r"], x["r"] + x.get("n", 1))
16677 elif x["k"] == "vlist": 16699 elif x["k"] == "vlist":
16678 regs += x["r"] 16700 regs += x["r"]
16679 if (base_op(op) in ("v_swap_b32", "v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16", "v_dot4c_i32_i8", "v_pk_fmac_f16", 16701 if (base_op(op) in DST_ALSO_READ or
16680 "v_dot2c_f32_f16", "v_dot2c_i32_i16", "v_dot2c_u32_u16", "v_dot4c_u32_u8",
16681 "v_dot8c_i32_i4", "v_dot8c_u32_u4") or
16682 (op.startswith(("global_load_", "buffer_load_")) and "_d16" in op and "format" not in op)) and \ 16702 (op.startswith(("global_load_", "buffer_load_")) and "_d16" in op and "format" not in op)) and \
16683 a[0]["k"] == "vgpr": # d16 keeps a half 16703 a[0]["k"] == "vgpr": # d16 keeps a half
16684 regs.append(a[0]["r"]) 16704 regs.append(a[0]["r"])
16705 lane_read = base_op(op) == "v_readlane_b32"
16685 for r in regs: 16706 for r in regs:
16686 if r not in written and r not in first: 16707 if r in written or r in first or (r in carried and lane_read):
16687 first.append(r) 16708 continue
16688 if not reads_all and a[0]["k"] == "vgpr": 16709 first.append(r)
16689 written.update(vgpr_dest_registers(ins)) 16710 if base_op(op) == "v_writelane_b32" and a[0]["k"] == "vgpr":
16711 if a[0]["r"] not in written:
16712 carried.add(a[0]["r"])
16713 elif not reads_all and a[0]["k"] == "vgpr":
16714 dst = vgpr_dest_registers(ins)
16715 written.update(dst)
16716 carried.difference_update(dst)
16690 return set(first) 16717 return set(first)
16691 16718
16692def interp_ij_analysis(insns, g): 16719def interp_ij_analysis(insns, g):
@@ -16937,9 +16964,8 @@ def reg_reads_writes(insns):
16937 regs += range(x["r"], x["r"] + x.get("n", 1)) 16964 regs += range(x["r"], x["r"] + x.get("n", 1))
16938 elif x["k"] == "vlist": 16965 elif x["k"] == "vlist":
16939 regs += x["r"] 16966 regs += x["r"]
16940 if base_op(op) in ("v_swap_b32", "v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16", "v_dot4c_i32_i8", "v_pk_fmac_f16", 16967 if (base_op(op) in DST_ALSO_READ or base_op(op) == "v_writelane_b32") and a[0]["k"] == "vgpr":
16941 "v_dot2c_f32_f16", "v_dot2c_i32_i16", "v_dot2c_u32_u16", "v_dot4c_u32_u8", 16968 # v_writelane_b32 keeps the other lanes: over a slice that is a read of the destination
16942 "v_dot8c_i32_i4", "v_dot8c_u32_u4") and a[0]["k"] == "vgpr":
16943 regs.append(a[0]["r"]) 16969 regs.append(a[0]["r"])
16944 rr.update(regs) 16970 rr.update(regs)
16945 if not reads_all and a[0]["k"] == "vgpr": 16971 if not reads_all and a[0]["k"] == "vgpr":
diff --git a/tools/semantic_mutants.py b/tools/semantic_mutants.py
index 2350e0b8b..32be6525d 100644
--- a/tools/semantic_mutants.py
+++ b/tools/semantic_mutants.py
@@ -9,7 +9,12 @@ branch naming it (--op), a whole method (--function), or an explicit line range
9mutants of that code with standard operators: swapped opcode pairs (OpIAdd/OpISub, OpBitwiseAnd/Or, shifts), swapped 9mutants of that code with standard operators: swapped opcode pairs (OpIAdd/OpISub, OpBitwiseAnd/Or, shifts), swapped
10GLSL.std.450 pairs (UMin/UMax, SMin/UMin, NMin/FMin, Floor/Ceil, ...), comparisons made strict or non-strict or of the 10GLSL.std.450 pairs (UMin/UMax, SMin/UMin, NMin/FMin, Floor/Ceil, ...), comparisons made strict or non-strict or of the
11other signedness, small `self.cu(N)` constants moved by one, the two arms of an OpSelect swapped, and the last operand 11other signedness, small `self.cu(N)` constants moved by one, the two arms of an OpSelect swapped, and the last operand
12of an emitted instruction replaced by the one before it. Each mutant is written into a private copy of tools/ (the 12of an emitted instruction replaced by the one before it. The Python around the emission (register liveness, lane-mask
13tracking, operand checks) gets mutants too: comparisons flipped (== / !=, < / <=, > / >=, in / not in, is / is not),
14and / or swapped, a `not` dropped, True / False swapped, and a one-line statement that can fail silently replaced by
15`pass` (a call that is not an emit, an augmented assignment, or a rebinding of a name assigned earlier in the range).
16The branch's own `if op ...` condition is left alone: a mutant there only sends other ops through the branch. Each
17mutant is written into a private copy of tools/ (the
13repository's own tools/ is never modified) and the test file is run against it through LEONIDA_TOOLS_DIR, as 18repository's own tools/ is never modified) and the test file is run against it through LEONIDA_TOOLS_DIR, as
14tests/semantic/test_mutations.py does. A mutant the test file still passes is reported as SURVIVED. 19tests/semantic/test_mutations.py does. A mutant the test file still passes is reported as SURVIVED.
15 20
@@ -27,7 +32,9 @@ import shutil
27import subprocess 32import subprocess
28import sys 33import sys
29import tempfile 34import tempfile
35import textwrap
30import time 36import time
37import tokenize
31from dataclasses import dataclass 38from dataclasses import dataclass
32 39
33ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 40ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -52,6 +59,14 @@ CU = re.compile(r"self\.cu\((0x[0-9A-Fa-f]+|\d+)\)")
52SELECT = re.compile(r"(OpSelect %\w+ \{[^}]+\} )(\{[^}]+\}|%\w+)( )(\{[^}]+\}|%\w+)") 59SELECT = re.compile(r"(OpSelect %\w+ \{[^}]+\} )(\{[^}]+\}|%\w+)( )(\{[^}]+\}|%\w+)")
53LAST_OPERAND = re.compile(r"(\{[A-Za-z_][\w\[\]]*\}) (\{[A-Za-z_][\w\[\]]*\})(\"\))") 60LAST_OPERAND = re.compile(r"(\{[A-Za-z_][\w\[\]]*\}) (\{[A-Za-z_][\w\[\]]*\})(\"\))")
54 61
62# Python logic: comparison flips, and the statements whose removal is not a NameError or a syntax error.
63COMPARE = {"==": "!=", "!=": "==", "<": "<=", "<=": "<", ">": ">=", ">=": ">"}
64AUG_ASSIGN = {"+=", "-=", "*=", "/=", "//=", "%=", "&=", "|=", "^=", "<<=", ">>="}
65NOT_SIMPLE = {"if", "elif", "else", "for", "while", "def", "class", "return", "raise", "try", "except", "finally",
66 "with", "yield", "break", "continue", "pass", "import", "from", "assert", "global", "nonlocal", "del",
67 "async", "await", "lambda", "match", "case"}
68SKIPPED_TOKENS = (tokenize.NL, tokenize.COMMENT, tokenize.INDENT, tokenize.DEDENT, tokenize.ENDMARKER)
69
55 70
56@dataclass 71@dataclass
57class Mutant: 72class Mutant:
@@ -140,9 +155,215 @@ def find_function(lines: list[str], name: str) -> tuple[int, int]:
140 raise LookupError(f"no method named {name}") 155 raise LookupError(f"no method named {name}")
141 156
142 157
158def docstring_lines(lines: list[str]) -> set[int]:
159 """0-based lines that belong to a string standing alone as a statement (a docstring): text, not code, so a
160 mutant there can never fail a test. Empty when the lines do not tokenize."""
161 out: set[int] = set()
162 source = iter(line + "\n" for line in lines)
163 prev = tokenize.NEWLINE
164 try:
165 tokens = list(tokenize.generate_tokens(lambda: next(source, "")))
166 except (tokenize.TokenError, SyntaxError):
167 return out
168 for i, tok in enumerate(tokens):
169 if tok.type == tokenize.STRING and prev in (tokenize.NEWLINE, tokenize.INDENT, tokenize.DEDENT):
170 # Adjacent literals are one string ("a " "b"), so the statement may go on with more of them.
171 rest = (t for t in tokens[i + 1:] if t.type not in (tokenize.COMMENT, tokenize.NL))
172 end, after = tok, next(rest, None)
173 while after is not None and after.type == tokenize.STRING:
174 end, after = after, next(rest, None)
175 if after is None or after.type in (tokenize.NEWLINE, tokenize.ENDMARKER):
176 out.update(range(tok.start[0] - 1, end.end[0]))
177 if tok.type not in (tokenize.COMMENT, tokenize.NL):
178 prev = tok.type
179 return out
180
181
182def open_triple_quote(line: str, open_: str | None) -> str | None:
183 """The triple-quote delimiter still open at the end of `line` (None when none), given the one open at its start.
184 Quotes in a comment or inside a one-line string do not count, nor does an escaped delimiter."""
185 i, n = 0, len(line)
186 while i < n:
187 if open_:
188 j = line.find(open_, i)
189 while j > 0 and (len(line[:j]) - len(line[:j].rstrip("\\"))) % 2 == 1:
190 j = line.find(open_, j + 1) # \""" inside the string
191 if j < 0:
192 return open_
193 i, open_ = j + 3, None
194 elif line.startswith(('"""', "'''"), i):
195 open_, i = line[i:i + 3], i + 3
196 elif line[i] == "#":
197 return None
198 elif line[i] in "\"'":
199 j = i + 1
200 while j < n and line[j] != line[i]:
201 j += 2 if line[j] == "\\" else 1
202 i = j + 1
203 else:
204 i += 1
205 return open_
206
207
208def string_context(lines: list[str], first: int, last: int) -> tuple[int, int]:
209 """Widen [first, last] to whole triple-quoted strings, so a range that starts or ends inside a docstring (a
210 --lines span) is tokenized with both of its delimiters. Delimiters are followed from the enclosing def or class,
211 a text scan that stays cheap inside the translator's long dispatch method."""
212 top = first
213 while top > 0 and not re.match(r"\s*(async\s+def|def|class)\s", lines[top]):
214 top -= 1
215 open_, opened_at = None, first
216 for i in range(top, first):
217 before, open_ = open_, open_triple_quote(lines[i], open_)
218 if open_ and not before:
219 opened_at = i # a string that is still open at `first` began here
220 start = opened_at if open_ else first
221 end, open_ = last, None
222 for i in range(start, len(lines)):
223 open_ = open_triple_quote(lines[i], open_)
224 if i >= last and not open_:
225 end = i
226 break
227 return start, end
228
229
230def condition_lines(lines: list[str], first: int) -> set[int]:
231 """0-based lines of the `if op ...` / `elif op ...` condition that starts at `first`, empty when `first` does not
232 start one. It decides which ops run the branch at all, so mutating it only sends other ops through the code."""
233 stripped = lines[first].lstrip()
234 if not re.match(r"(el)?if\b", stripped):
235 return set()
236 cond, j = lines[first], first
237 while not cond.rstrip().endswith(":") and j + 1 < len(lines):
238 j += 1
239 cond += lines[j]
240 return set(range(first, j + 1)) if re.search(r"\bop\b", cond) and '"' in cond else set()
241
242
243def logical_lines(span: list[str]) -> list[list[tokenize.TokenInfo]]:
244 """The tokens of each logical line of `span` (NL, comments, indents and dedents dropped). A span that stops
245 inside a bracket or a string keeps the lines that tokenized before it."""
246 source = iter(s + "\n" for s in span)
247 out: list[list[tokenize.TokenInfo]] = [[]]
248 try:
249 for tok in tokenize.generate_tokens(lambda: next(source, "")):
250 if tok.type == tokenize.NEWLINE:
251 out.append([])
252 elif tok.type not in SKIPPED_TOKENS:
253 out[-1].append(tok)
254 except (tokenize.TokenError, SyntaxError):
255 out[-1] = [] # the unfinished line
256 return [ll for ll in out if ll]
257
258
259def logic_mutants(lines: list[str], first: int, last: int, start: int, span: list[str],
260 skip: set[int]) -> list[tuple[int, str, str]]:
261 """(0-based line, label, mutated line) for the Python logic in lines[first..last]; `span` is lines[start..]
262 dedented. Only names and operators are touched, so strings, f-strings (the emitted SPIR-V) and comments are
263 left alone; lines in `skip` (docstrings, the branch condition) get none."""
264 out: list[tuple[int, str, str]] = []
265 assigned: set[str] = set()
266
267 def line_of(tok: tokenize.TokenInfo) -> int:
268 return start + tok.start[0] - 1
269
270 def in_range(i: int) -> bool:
271 return first <= i <= last and i not in skip
272
273 def replace(tok_a: tokenize.TokenInfo, tok_b: tokenize.TokenInfo, text: str, label: str, a_end: bool = False,
274 b_end: bool = True) -> None:
275 # Replace lines[i] from tok_a's start (or end) to tok_b's end (or start) with `text`; both on line i.
276 i = line_of(tok_a)
277 if line_of(tok_b) != i or not in_range(i):
278 return
279 k = tok_a.start[0] - 1
280 off = len(lines[i]) - len(span[k]) # the indentation dedent removed
281 a = (tok_a.end if a_end else tok_a.start)[1] + off
282 b = (tok_b.end if b_end else tok_b.start)[1] + off
283 out.append((i, label, lines[i][:a] + text + lines[i][b:]))
284
285 for ll in logical_lines(span):
286 depth, fors, consumed = 0, [], set()
287 targets: list[str] = []
288 top_eq = top_aug = False
289 for n, tok in enumerate(ll):
290 nxt = ll[n + 1] if n + 1 < len(ll) else None
291 if tok.type == tokenize.OP:
292 if tok.string in "([{":
293 depth += 1
294 elif tok.string in ")]}":
295 depth -= 1
296 elif tok.string in COMPARE:
297 replace(tok, tok, COMPARE[tok.string], f"{tok.string} -> {COMPARE[tok.string]}")
298 elif depth == 0 and tok.string == "=":
299 if not top_eq:
300 top_eq = True
301 names = [t for t in ll[:n] if not (t.type == tokenize.OP and t.string == ",")]
302 if all(t.type == tokenize.NAME for t in names):
303 targets = [t.string for t in names]
304 elif depth == 0 and tok.string in AUG_ASSIGN:
305 top_aug = True
306 continue
307 if tok.type != tokenize.NAME or n in consumed:
308 continue
309 word = tok.string
310 if word == "for":
311 fors.append(depth)
312 elif word in ("and", "or"):
313 other = "or" if word == "and" else "and"
314 replace(tok, tok, other, f"{word} -> {other}")
315 elif word in ("True", "False"):
316 other = "False" if word == "True" else "True"
317 replace(tok, tok, other, f"{word} -> {other}")
318 elif word == "not" and nxt is not None and nxt.type == tokenize.NAME and nxt.string == "in":
319 replace(tok, nxt, "", "not in -> in", b_end=False)
320 consumed.add(n + 1)
321 elif word == "not" and nxt is not None:
322 replace(tok, nxt, "", "not removed", b_end=False)
323 elif word == "in":
324 if fors and fors[-1] == depth: # the `in` of a for loop or a comprehension
325 fors.pop()
326 else:
327 replace(tok, tok, "not in", "in -> not in")
328 elif word == "is":
329 if nxt is not None and nxt.type == tokenize.NAME and nxt.string == "not":
330 replace(tok, nxt, "", "is not -> is", a_end=True)
331 consumed.add(n + 1)
332 else:
333 replace(tok, tok, "is not", "is -> is not")
334 # A one-line statement that can fail silently: a call that is not an emit, an augmented assignment, or a
335 # rebinding of a name the range assigned before. Removing a first assignment would only be a NameError.
336 i, head = line_of(ll[0]), ll[0]
337 one_line = line_of(ll[-1]) == i
338 simple = head.type == tokenize.NAME and head.string not in NOT_SIMPLE
339 call = (not top_eq and not top_aug and ll[-1].type == tokenize.OP and ll[-1].string == ")"
340 and not any(t.type == tokenize.NAME and t.string == "emit" for t in ll))
341 rebind = top_eq and bool(targets) and all(t in assigned for t in targets)
342 if one_line and simple and in_range(i) and (call or top_aug or rebind):
343 indent = lines[i][:len(lines[i]) - len(lines[i].lstrip())]
344 out.append((i, "statement removed", indent + "pass"))
345 assigned.update(targets)
346 # The same flip twice on one line (`a and b and c`) gets "#1", "#2", ... from the left, so the report tells them apart.
347 count: dict[tuple[int, str], int] = {}
348 for i, label, _ in out:
349 count[(i, label)] = count.get((i, label), 0) + 1
350 seen: dict[tuple[int, str], int] = {}
351 numbered = []
352 for i, label, new in out:
353 if count[(i, label)] > 1:
354 seen[(i, label)] = seen.get((i, label), 0) + 1
355 label = f"{label} #{seen[(i, label)]}"
356 numbered.append((i, label, new))
357 return numbered
358
359
143def mutants_for(lines: list[str], first: int, last: int) -> list[Mutant]: 360def mutants_for(lines: list[str], first: int, last: int) -> list[Mutant]:
144 out: list[Mutant] = [] 361 out: list[Mutant] = []
145 seen: set[tuple[int, str]] = set() 362 seen: set[tuple[int, str]] = set()
363 # Only the mutated range is tokenized (the whole translator takes seconds); dedented, a branch or method tokenizes.
364 start, end = string_context(lines, first, last)
365 span = textwrap.dedent("\n".join(lines[start:end + 1])).split("\n")
366 docs = {start + i for i in docstring_lines(span)}
146 367
147 def add(i: int, label: str, new: str) -> None: 368 def add(i: int, label: str, new: str) -> None:
148 if new != lines[i] and (i, new) not in seen: 369 if new != lines[i] and (i, new) not in seen:
@@ -150,6 +371,8 @@ def mutants_for(lines: list[str], first: int, last: int) -> list[Mutant]:
150 out.append(Mutant(i + 1, label, lines[i], new)) 371 out.append(Mutant(i + 1, label, lines[i], new))
151 372
152 for i in range(first, last + 1): 373 for i in range(first, last + 1):
374 if i in docs:
375 continue
153 line = lines[i] 376 line = lines[i]
154 code = line.split("#", 1)[0] if not line.lstrip().startswith(("f\"", "\"", "'")) else line 377 code = line.split("#", 1)[0] if not line.lstrip().startswith(("f\"", "\"", "'")) else line
155 if not code.strip() or code.lstrip().startswith("#"): 378 if not code.strip() or code.lstrip().startswith("#"):
@@ -178,6 +401,8 @@ def mutants_for(lines: list[str], first: int, last: int) -> list[Mutant]:
178 if m: 401 if m:
179 add(i, f"last operand {m.group(2)} -> {m.group(1)}", 402 add(i, f"last operand {m.group(2)} -> {m.group(1)}",
180 line[:m.start()] + f"{m.group(1)} {m.group(1)}{m.group(3)}" + line[m.end():]) 403 line[:m.start()] + f"{m.group(1)} {m.group(1)}{m.group(3)}" + line[m.end():])
404 for i, label, new in logic_mutants(lines, first, last, start, span, docs | condition_lines(lines, first)):
405 add(i, label, new)
181 return out 406 return out
182 407
183 408
diff --git a/tools/shader_stage_manifest.py b/tools/shader_stage_manifest.py
index eb5ffc913..fe9e94572 100644
--- a/tools/shader_stage_manifest.py
+++ b/tools/shader_stage_manifest.py
@@ -8,7 +8,8 @@ import ntpath
8import posixpath 8import posixpath
9 9
10 10
11def shader_stems(path: str, field: str, suffix: str = "") -> set[str]: 11def _stem_rows(path: str, field: str, suffix: str = "") -> list[tuple[str, dict]]:
12 """Each entry of the index as (validated stem, row)."""
12 try: 13 try:
13 # utf-8-sig: PowerShell 5.1 and old Notepad write JSON with a UTF-8 BOM. 14 # utf-8-sig: PowerShell 5.1 and old Notepad write JSON with a UTF-8 BOM.
14 with open(path, encoding="utf-8-sig") as f: 15 with open(path, encoding="utf-8-sig") as f:
@@ -19,7 +20,7 @@ def shader_stems(path: str, field: str, suffix: str = "") -> set[str]:
19 raise ValueError(f"{path}: invalid JSON: {exc}") from exc 20 raise ValueError(f"{path}: invalid JSON: {exc}") from exc
20 if not isinstance(rows, list): 21 if not isinstance(rows, list):
21 raise ValueError(f"{path}: expected an array of shader entries") 22 raise ValueError(f"{path}: expected an array of shader entries")
22 stems = set() 23 out = []
23 for row in rows: 24 for row in rows:
24 value = row.get(field) if isinstance(row, dict) else None 25 value = row.get(field) if isinstance(row, dict) else None
25 if ( 26 if (
@@ -39,5 +40,19 @@ def shader_stems(path: str, field: str, suffix: str = "") -> set[str]:
39 stem = value.removesuffix(suffix) 40 stem = value.removesuffix(suffix)
40 if not stem or stem in (".", ".."): 41 if not stem or stem in (".", ".."):
41 raise ValueError(f"{path}: expected a shader basename in {field!r}") 42 raise ValueError(f"{path}: expected a shader basename in {field!r}")
42 stems.add(stem) 43 out.append((stem, row))
43 return stems 44 return out
45
46
47def shader_stems(path: str, field: str, suffix: str = "") -> set[str]:
48 return {stem for stem, _ in _stem_rows(path, field, suffix)}
49
50
51def shader_stages(path: str, field: str, suffix: str = "") -> dict[str, str | None]:
52 """The stage the index records for each shader, by stem. None where an entry has no stage string: the stage is
53 then unknown, not absent, and the caller says so."""
54 stages = {}
55 for stem, row in _stem_rows(path, field, suffix):
56 stage = row.get("stage")
57 stages[stem] = stage if isinstance(stage, str) and stage else None
58 return stages
diff --git a/tools/spirv_asm.py b/tools/spirv_asm.py
index 49d0809e1..e32dd83af 100644
--- a/tools/spirv_asm.py
+++ b/tools/spirv_asm.py
@@ -30,7 +30,8 @@ if _HERE not in sys.path:
30 sys.path.insert(0, _HERE) 30 sys.path.insert(0, _HERE)
31 31
32from spirv_asm_tables import ( # noqa: E402 32from spirv_asm_tables import ( # noqa: E402
33 BIT_ENUMS, GLSL_STD_450, INSTRUCTIONS, NONSEMANTIC_DEBUGPRINTF, VALUE_ENUMS, 33 BIT_ENUMS, GLSL_STD_450, INSTRUCTIONS, NONSEMANTIC_DEBUGPRINTF,
34 NONSEMANTIC_SHADER_DEBUGINFO_100, VALUE_ENUMS,
34) 35)
35 36
36SPIRV_MAGIC = 0x07230203 37SPIRV_MAGIC = 0x07230203
@@ -54,6 +55,7 @@ TARGET_ENV_VERSION = {
54_ID_KINDS = frozenset(("IdRef", "IdResult", "IdResultType", "IdScope", "IdMemorySemantics")) 55_ID_KINDS = frozenset(("IdRef", "IdResult", "IdResultType", "IdScope", "IdMemorySemantics"))
55_ID_RE = re.compile(r"%[A-Za-z0-9_]+") 56_ID_RE = re.compile(r"%[A-Za-z0-9_]+")
56_EXT_SETS = { 57_EXT_SETS = {
58 "NonSemantic.Shader.DebugInfo.100": NONSEMANTIC_SHADER_DEBUGINFO_100,
57 "GLSL.std.450": GLSL_STD_450, 59 "GLSL.std.450": GLSL_STD_450,
58 "NonSemantic.DebugPrintf": NONSEMANTIC_DEBUGPRINTF, # spirv-dis writes its instruction by name 60 "NonSemantic.DebugPrintf": NONSEMANTIC_DEBUGPRINTF, # spirv-dis writes its instruction by name
59} 61}
@@ -638,7 +640,7 @@ def _assemble(instructions, version: int, track_switch_types: bool) -> bytes:
638 640
639 cur_ext_table = None 641 cur_ext_table = None
640 switch_type = None # (width, signed) of the OpSwitch selector's integer type 642 switch_type = None # (width, signed) of the OpSwitch selector's integer type
641 if opname == "OpExtInst" and arg_idx < len(toks): 643 if opname in ("OpExtInst", "OpExtInstWithForwardRefsKHR") and arg_idx < len(toks):
642 cur_ext_table = ext_imports.get(get_id(toks[arg_idx], lineno)) 644 cur_ext_table = ext_imports.get(get_id(toks[arg_idx], lineno))
643 elif opname == "OpSwitch" and arg_idx < len(toks): 645 elif opname == "OpSwitch" and arg_idx < len(toks):
644 sel_id = get_id(toks[arg_idx], lineno) 646 sel_id = get_id(toks[arg_idx], lineno)
diff --git a/tools/spirv_asm_tables.py b/tools/spirv_asm_tables.py
index a58311c14..7714d734f 100644
--- a/tools/spirv_asm_tables.py
+++ b/tools/spirv_asm_tables.py
@@ -1111,3 +1111,51 @@ GLSL_STD_450 = {
1111NONSEMANTIC_DEBUGPRINTF = { 1111NONSEMANTIC_DEBUGPRINTF = {
1112 'DebugPrintf': 1, 1112 'DebugPrintf': 1,
1113} 1113}
1114
1115# extinst.nonsemantic.shader.debuginfo.100.grammar.json (SPIRV-Headers).
1116NONSEMANTIC_SHADER_DEBUGINFO_100 = {
1117 'DebugBuildIdentifier': 105,
1118 'DebugCompilationUnit': 1,
1119 'DebugDeclare': 28,
1120 'DebugEntryPoint': 107,
1121 'DebugExpression': 31,
1122 'DebugFunction': 20,
1123 'DebugFunctionDeclaration': 19,
1124 'DebugFunctionDefinition': 101,
1125 'DebugGlobalVariable': 18,
1126 'DebugImportedEntity': 34,
1127 'DebugInfoNone': 0,
1128 'DebugInlinedAt': 25,
1129 'DebugInlinedVariable': 27,
1130 'DebugLexicalBlock': 21,
1131 'DebugLexicalBlockDiscriminator': 22,
1132 'DebugLine': 103,
1133 'DebugLocalVariable': 26,
1134 'DebugMacroDef': 32,
1135 'DebugMacroUndef': 33,
1136 'DebugNoLine': 104,
1137 'DebugNoScope': 24,
1138 'DebugOperation': 30,
1139 'DebugScope': 23,
1140 'DebugSource': 35,
1141 'DebugSourceContinued': 102,
1142 'DebugStoragePath': 106,
1143 'DebugTypeArray': 5,
1144 'DebugTypeBasic': 2,
1145 'DebugTypeComposite': 10,
1146 'DebugTypedef': 7,
1147 'DebugTypeEnum': 9,
1148 'DebugTypeFunction': 8,
1149 'DebugTypeInheritance': 12,
1150 'DebugTypeMatrix': 108,
1151 'DebugTypeMember': 11,
1152 'DebugTypePointer': 3,
1153 'DebugTypePtrToMember': 13,
1154 'DebugTypeQualifier': 4,
1155 'DebugTypeTemplate': 14,
1156 'DebugTypeTemplateParameter': 15,
1157 'DebugTypeTemplateParameterPack': 17,
1158 'DebugTypeTemplateTemplateParameter': 16,
1159 'DebugTypeVector': 6,
1160 'DebugValue': 29,
1161}
diff --git a/tools/stale_build.py b/tools/stale_build.py
index 0945e5fed..140cecd93 100644
--- a/tools/stale_build.py
+++ b/tools/stale_build.py
@@ -3,7 +3,8 @@
3make_game.py (vk_pipeline_check) and first_light.py (vk_harness) take a program already in runtime/build when there 3make_game.py (vk_pipeline_check) and first_light.py (vk_harness) take a program already in runtime/build when there
4is one. After a pull that changed the program, that copy is from the old sources and would run silently. The 4is one. After a pull that changed the program, that copy is from the old sources and would run silently. The
5sources are runtime/test/<name>.cpp and the headers it pulls in with #include "..." (followed through other 5sources are runtime/test/<name>.cpp and the headers it pulls in with #include "..." (followed through other
6headers): a change to any of them recompiles and relinks the program, so a current build is never older than them. 6headers, each looked up next to the including file, then in the include directories of runtime/CMakeLists.txt): a
7change to any of them recompiles and relinks the program, so a current build is never older than them.
7runtime/CMakeLists.txt isn't one: a change there that doesn't concern the program leaves it as it was. 8runtime/CMakeLists.txt isn't one: a change there that doesn't concern the program leaves it as it was.
8""" 9"""
9import os 10import os
@@ -11,6 +12,32 @@ import re
11 12
12_INCLUDE = re.compile(r'^\s*#\s*include\s*"([^"]+)"', re.MULTILINE) 13_INCLUDE = re.compile(r'^\s*#\s*include\s*"([^"]+)"', re.MULTILINE)
13 14
15# The include directories runtime/CMakeLists.txt gives the runtime/test programs, searched after the directory of the
16# including file: runtime/src and runtime/shims (target_include_directories of pe_loader_test, lines 657-660, which
17# other test programs repeat), then the xtaskqueue ones (lines 90-92, 1206-1210 and 1227-1229). Paths are relative to
18# the repository root. The list is the union over the programs, not one target's order: no header name exists in two
19# of these directories today, and if one did, every copy would count as a source of the program.
20_INCLUDE_DIRS = (
21 "runtime/src",
22 "runtime/shims",
23 "runtime/shims/xtaskqueue",
24 "third_party/xtaskqueue/Source/Task",
25 "third_party/xtaskqueue/Source/Common",
26 "third_party/xtaskqueue/Include",
27)
28
29
30def _resolve_include(root, path, inc):
31 """The files a quoted `#include inc` in `path` may name: the one next to `path` when there is one (the compiler
32 looks there first and nowhere else), otherwise every match in _INCLUDE_DIRS. CMake orders those directories per
33 target, so which match the compiler takes can differ from one program to the next; following all of them can add a
34 rebuild but never miss one. Empty when nothing has it (a system or generated header)."""
35 local = os.path.join(os.path.dirname(path), inc)
36 if os.path.isfile(local):
37 return [local]
38 matches = (os.path.join(root, directory, inc) for directory in _INCLUDE_DIRS)
39 return [candidate for candidate in matches if os.path.isfile(candidate)]
40
14 41
15def program_sources(root, name): 42def program_sources(root, name):
16 """The files program `name` of runtime/test is built from, as far as they exist in this checkout.""" 43 """The files program `name` of runtime/test is built from, as far as they exist in this checkout."""
@@ -29,7 +56,8 @@ def program_sources(root, name):
29 text = f.read() 56 text = f.read()
30 except OSError: 57 except OSError:
31 continue 58 continue
32 pending.extend(os.path.join(os.path.dirname(path), inc) for inc in _INCLUDE.findall(text)) 59 for inc in _INCLUDE.findall(text):
60 pending.extend(_resolve_include(root, path, inc))
33 return found 61 return found
34 62
35 63
diff --git a/tools/vk_fuzz_run.py b/tools/vk_fuzz_run.py
index 797010296..88cde0d8f 100644
--- a/tools/vk_fuzz_run.py
+++ b/tools/vk_fuzz_run.py
@@ -79,6 +79,19 @@ def program_text(name, lines, words, wave, opaque=False, rewrite=True):
79 return "\n".join(out) + "\n" 79 return "\n".join(out) + "\n"
80 80
81 81
82def read_dump(path, words, wave):
83 """The `wave` lanes of `words` words each from a VKC_DUMP file, or None when it is missing or too short.
84 vk_compute_test's output buffer is at least one 64-thread group of words (VKC_OUT_WORDS only raises it), and
85 VKC_DUMP writes the whole buffer, so a request under 64 words (wave32 with words=1) gives a larger file: only its
86 first words * wave words are the program's stores, the rest keep the fill."""
87 need = 4 * words * wave
88 if not os.path.isfile(path) or os.path.getsize(path) < need:
89 return None
90 with open(path, "rb") as f:
91 flat = struct.unpack(f"<{words * wave}I", f.read(need))
92 return [list(flat[k:k + words]) for k in range(0, words * wave, words)]
93
94
82def run_programs(texts, words=4, wave=32, build=None, work_parent=None, retries=2, opaque=True, rewrite=True, 95def run_programs(texts, words=4, wave=32, build=None, work_parent=None, retries=2, opaque=True, rewrite=True,
83 per_lane=False, uniform=True): 96 per_lane=False, uniform=True):
84 """Per program lane 0's `words` words, or a str (see the module docstring). words must be 1, 2, 4 or 8.""" 97 """Per program lane 0's `words` words, or a str (see the module docstring). words must be 1, 2, 4 or 8."""
@@ -158,12 +171,11 @@ def run_programs(texts, words=4, wave=32, build=None, work_parent=None, retries=
158 results[i] = "vk_compute_test: " + (msg.splitlines()[-1] if msg else "unsupported") 171 results[i] = "vk_compute_test: " + (msg.splitlines()[-1] if msg else "unsupported")
159 elif wave == 32 and unpinned_subgroup(msg): 172 elif wave == 32 and unpinned_subgroup(msg):
160 results[i] = f"the device can't run 32-lane subgroups ({unpinned_subgroup(msg)} lanes)" 173 results[i] = f"the device can't run 32-lane subgroups ({unpinned_subgroup(msg)} lanes)"
161 elif r.returncode or not os.path.isfile(dump) or os.path.getsize(dump) != 4 * words * wave: 174 elif r.returncode:
162 results[i] = f"vk_compute_test exit {r.returncode}" 175 results[i] = f"vk_compute_test exit {r.returncode}"
176 elif (lanes := read_dump(dump, words, wave)) is None:
177 results[i] = f"vk_compute_test: no dump of {4 * words * wave} bytes or more"
163 else: 178 else:
164 with open(dump, "rb") as f:
165 flat = struct.unpack(f"<{words * wave}I", f.read())
166 lanes = [list(flat[k:k + words]) for k in range(0, words * wave, words)]
167 odd = [k for k, w in enumerate(lanes) if w != lanes[0]] 179 odd = [k for k, w in enumerate(lanes) if w != lanes[0]]
168 if per_lane: 180 if per_lane:
169 results[i] = lanes 181 results[i] = lanes