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:
authorTomgamer <tomanhorak22@gmail.com>2026-11-22 16:32:05 +0100
committerTomgamer <tomanhorak22@gmail.com>2026-11-22 16:32:05 +0100
commiteb35aed2e7e8ea1d4a11fd4e42ab80d853f05169 (patch)
tree22bd0e6fa6363235d1feedc1c9be678ab63bee4b /tools
parent759a90c42e58886153f67dcd2d5d41c44face012 (diff)
parent4eb6155d3ac4f9d3fadb0d095c4ce13e76783615 (diff)
Merge origin/main into shader-309-wave64-lds-limit
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'tools')
-rw-r--r--tools/ab_control_flow.py4
-rw-r--r--tools/analyze_4240_full.py2
-rw-r--r--tools/anim_clips.py2
-rw-r--r--tools/anim_index.py4
-rw-r--r--tools/anim_rigs.py172
-rw-r--r--tools/awc_names.py7
-rw-r--r--tools/awc_opus.py43
-rw-r--r--tools/bink_index.py2
-rw-r--r--tools/bink_names.py4
-rw-r--r--tools/bvh_index.py2
-rw-r--r--tools/calibrated_texture.py3
-rw-r--r--tools/cf_diff.py2
-rw-r--r--tools/classify_carve.py2
-rw-r--r--tools/crosslane_fuzz.py8
-rw-r--r--tools/d16_format_probe.py341
-rw-r--r--tools/f16_trans_sweep.py2
-rw-r--r--tools/f32_fuzz.py4
-rw-r--r--tools/feature_scan.py231
-rw-r--r--tools/fma_mix_probe.py4
-rw-r--r--tools/fspx_unpack.py19
-rw-r--r--tools/fssm_unpack.py2
-rw-r--r--tools/gamedata_graph.py2
-rw-r--r--tools/gamedata_index.py10
-rw-r--r--tools/gamedata_maps.py2
-rw-r--r--tools/gamedata_xml.py2
-rw-r--r--tools/glb_writer.py13
-rw-r--r--tools/hashdict.py17
-rw-r--r--tools/hw_oracle/runner.py2
-rw-r--r--tools/image_fuzz.py4
-rw-r--r--tools/imhex/psin.hexpat193
-rw-r--r--tools/imhex/rbf0.hexpat96
-rw-r--r--tools/imhex/rpf9.hexpat32
-rw-r--r--tools/instance_lists.py2
-rw-r--r--tools/int_hw_probe.py743
-rw-r--r--tools/lds_fuzz.py24
-rw-r--r--tools/manifest.py36
-rw-r--r--tools/mem_diff.py2
-rw-r--r--tools/meshlet_page.py4
-rw-r--r--tools/mission_tables.py524
-rw-r--r--tools/navmesh_decode.py2
-rw-r--r--tools/navmesh_index.py2
-rw-r--r--tools/opus_tags.py7
-rw-r--r--tools/page_index.py2
-rw-r--r--tools/pe_inspect.py8
-rw-r--r--tools/pe_shader_containers.py272
-rw-r--r--tools/psin_names.py7
-rw-r--r--tools/rbf0_index.py2
-rw-r--r--tools/rdna2spirv.py422
-rw-r--r--tools/restofworld_index.py2
-rw-r--r--tools/rpf9_carve.py2
-rw-r--r--tools/rpf9_names.py2
-rw-r--r--tools/rpf_probe.py2
-rw-r--r--tools/salu_diff.py9
-rw-r--r--tools/save_keys.py4
-rw-r--r--tools/saves.py12
-rw-r--r--tools/shader_carve.py5
-rw-r--r--tools/shader_diff.py2
-rw-r--r--tools/shader_disasm.py2
-rw-r--r--tools/shader_profile.py2
-rw-r--r--tools/skin_streams.py2
-rw-r--r--tools/spirv_gs_to_compute.py2
-rw-r--r--tools/spirv_metal_set0.py56
-rw-r--r--tools/story_index.py2
-rw-r--r--tools/tex_export.py2
-rw-r--r--tools/tex_headers.py2
-rw-r--r--tools/text_tables.py85
-rw-r--r--tools/ttpf_assets.py4
-rw-r--r--tools/ttpf_mips.py2
-rw-r--r--tools/turing_atlas.py4
-rw-r--r--tools/user_sgpr_census.py33
-rw-r--r--tools/valu_fuzz.py4
-rw-r--r--tools/vertex_types.py2
-rw-r--r--tools/vk_subgroup_info.py25
-rw-r--r--tools/wave64_graphics_scan.py10
-rw-r--r--tools/world_census.py2
-rw-r--r--tools/world_index.py23
-rw-r--r--tools/world_lights_paths.py11
-rw-r--r--tools/world_names.py2
-rw-r--r--tools/xdxr_bvh.py10
79 files changed, 3359 insertions, 260 deletions
diff --git a/tools/ab_control_flow.py b/tools/ab_control_flow.py
index 577c402c1..d38b33a85 100644
--- a/tools/ab_control_flow.py
+++ b/tools/ab_control_flow.py
@@ -111,7 +111,7 @@ def write_outcomes(out_dir, outcomes):
111 """Write (shader name, outcome) pairs to the harness's tab-separated report.""" 111 """Write (shader name, outcome) pairs to the harness's tab-separated report."""
112 os.makedirs(out_dir, exist_ok=True) 112 os.makedirs(out_dir, exist_ok=True)
113 path = os.path.join(out_dir, "outcomes.tsv") 113 path = os.path.join(out_dir, "outcomes.tsv")
114 with open(path, "w", encoding="utf-8") as f: 114 with open(path, "w", encoding="utf-8", newline="\n") as f:
115 f.write("".join(f"{name}\t{outcome}\n" for name, outcome in outcomes)) 115 f.write("".join(f"{name}\t{outcome}\n" for name, outcome in outcomes))
116 return path 116 return path
117 117
@@ -169,7 +169,7 @@ OpFunctionEnd
169""" 169"""
170 src, dst = os.path.join(out_dir, "test_vs.spvasm"), os.path.join(out_dir, "test_vs.spv") 170 src, dst = os.path.join(out_dir, "test_vs.spvasm"), os.path.join(out_dir, "test_vs.spv")
171 os.makedirs(out_dir, exist_ok=True) 171 os.makedirs(out_dir, exist_ok=True)
172 with open(src, "w", encoding="utf-8") as f: 172 with open(src, "w", encoding="utf-8", newline="\n") as f:
173 f.write(asm) 173 f.write(asm)
174 runner(["spirv-as", "--target-env", "vulkan1.2", src, "-o", dst], check=True) 174 runner(["spirv-as", "--target-env", "vulkan1.2", src, "-o", dst], check=True)
175 runner(["spirv-val", "--target-env", "vulkan1.2", dst], check=True) 175 runner(["spirv-val", "--target-env", "vulkan1.2", dst], check=True)
diff --git a/tools/analyze_4240_full.py b/tools/analyze_4240_full.py
index 3dd9c243c..e5b6f50e3 100644
--- a/tools/analyze_4240_full.py
+++ b/tools/analyze_4240_full.py
@@ -352,7 +352,7 @@ def main() -> int:
352 parent = os.path.dirname(os.path.abspath(args.json)) 352 parent = os.path.dirname(os.path.abspath(args.json))
353 if parent: # every archive has been read by now; a missing folder used to lose the run 353 if parent: # every archive has been read by now; a missing folder used to lose the run
354 os.makedirs(parent, exist_ok=True) 354 os.makedirs(parent, exist_ok=True)
355 with open(args.json, "w", encoding="utf-8") as f: 355 with open(args.json, "w", encoding="utf-8", newline="\n") as f:
356 json.dump(output, f, indent=2) 356 json.dump(output, f, indent=2)
357 return status 357 return status
358 358
diff --git a/tools/anim_clips.py b/tools/anim_clips.py
index 047a9834a..ca48ea5cb 100644
--- a/tools/anim_clips.py
+++ b/tools/anim_clips.py
@@ -886,7 +886,7 @@ def main():
886 parent = os.path.dirname(os.path.abspath(a.out)) 886 parent = os.path.dirname(os.path.abspath(a.out))
887 if parent: 887 if parent:
888 os.makedirs(parent, exist_ok=True) 888 os.makedirs(parent, exist_ok=True)
889 with open(a.out, "w", encoding="utf-8") as f: 889 with open(a.out, "w", encoding="utf-8", newline="\n") as f:
890 json.dump({"summary": summary, "dictionaries": rows}, f, indent=1) 890 json.dump({"summary": summary, "dictionaries": rows}, f, indent=1)
891 except OSError as e: 891 except OSError as e:
892 sys.exit(f"{a.out}: cannot write: {e.strerror or e}") 892 sys.exit(f"{a.out}: cannot write: {e.strerror or e}")
diff --git a/tools/anim_index.py b/tools/anim_index.py
index 29d590685..119b81613 100644
--- a/tools/anim_index.py
+++ b/tools/anim_index.py
@@ -454,7 +454,7 @@ def write_output(path, rows, summary):
454 """Write CSV or JSON from the file extension. CSV writes one summary line to stderr.""" 454 """Write CSV or JSON from the file extension. CSV writes one summary line to stderr."""
455 ext = os.path.splitext(path)[1].lower() 455 ext = os.path.splitext(path)[1].lower()
456 if ext == ".json": 456 if ext == ".json":
457 with open(path, "w", encoding="utf-8") as f: 457 with open(path, "w", encoding="utf-8", newline="\n") as f:
458 json.dump({"summary": summary, "files": rows}, f, indent=1) 458 json.dump({"summary": summary, "files": rows}, f, indent=1)
459 return 459 return
460 with open(path, "w", encoding="utf-8", newline="") as f: 460 with open(path, "w", encoding="utf-8", newline="") as f:
@@ -570,7 +570,7 @@ def main():
570 print(f"{a.source}: RBF0 stream: {e}", file=sys.stderr) 570 print(f"{a.source}: RBF0 stream: {e}", file=sys.stderr)
571 return 2 571 return 2
572 try: 572 try:
573 with open(a.rigs, "w", encoding="utf-8") as f: 573 with open(a.rigs, "w", encoding="utf-8", newline="\n") as f:
574 json.dump({"rbf0": rbf0, "skeletons": skeletons}, f, indent=1) 574 json.dump({"rbf0": rbf0, "skeletons": skeletons}, f, indent=1)
575 except OSError as e: 575 except OSError as e:
576 sys.exit(f"{a.rigs}: cannot write: {e.strerror or e}") 576 sys.exit(f"{a.rigs}: cannot write: {e.strerror or e}")
diff --git a/tools/anim_rigs.py b/tools/anim_rigs.py
new file mode 100644
index 000000000..cd2fb9dbc
--- /dev/null
+++ b/tools/anim_rigs.py
@@ -0,0 +1,172 @@
1"""Read the rig dictionaries in anim.rpf and join the RBF0 rig-set manager's entries to them (ASSET-20).
2
3 python -I tools/anim_rigs.py <package>\\anim.rpf <work>\\anim-rigs.json [--rigs <work>\\rigs.json]
4
5A rig dictionary has the clip dictionary's root layout (docs/animation.md, "Clip dictionaries are RAGE
6resources") with `RIG` + a version byte at +0x70 instead of the pack array. Its map is keyed by `joaat32` of a rig
7path. Each value points at +0x20 to a `RIG` block, which holds tables of 8-byte `(hash, word)` items. `--rigs`
8takes the JSON `anim_index.py --rigs` writes and resolves every rig-set entry (source = rig dictionary name,
9rig = key). The output holds counts and one row per rig dictionary, no item values.
10"""
11import argparse
12import collections
13import json
14import mmap
15import os
16import struct
17import sys
18import zlib
19
20sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
21import anim_clips # noqa: E402
22import anim_index # noqa: E402
23
24SYSTEM = anim_clips.SYSTEM
25MAGIC = b"RIG"
26
27
28def is_rig_dictionary(data):
29 return len(data) >= 0x78 and data[0x70:0x73] == MAGIC
30
31
32def block_tables(s, at):
33 """Tables of a `RIG` block at page offset `at`: `RIG` + u8 version, u32 length of what follows, then tables
34 `{u32 kind hash; u32 size = 0xC + 8 * count; u32 count; u32 word}` + count × `{u32 hash; u32 word}`, with other
35 bytes between them. Returns (version, length, [(kind, count)])."""
36 if s.d[at:at + 3] != MAGIC:
37 raise anim_clips.DecodeError(f"no RIG block at 0x{at:x}")
38 version, length = s.d[at + 3], s.u32(at + 4)
39 end = min(len(s.d), at + 8 + length)
40 o, tables = at + 8, []
41 while o + 16 <= end:
42 kind, size, count, _word = struct.unpack_from("<4I", s.d, o)
43 if 0 < count < 4096 and size == 0xC + 8 * count and o + 16 + 8 * count <= end:
44 tables.append((kind, count))
45 o += 16 + 8 * count
46 else:
47 o += 4
48 return version, length, tables
49
50
51def parse_rig_dictionary(s):
52 """Root: +0x38 name, +0x48 map (key = joaat32(rig path), high half 0), +0x68 joaat32(name), +0x70 `RIG`."""
53 d = {"name": s.string(0x38), "hash": s.u32(0x68), "version": s.d[0x73], "entries": []}
54 for key, value in s.atmap(0x48):
55 if value is None:
56 continue
57 block = s.ptr(value + 0x20)
58 e = {"key": key & 0xFFFFFFFF, "key_high": key >> 32, "block": block}
59 if block is not None:
60 e["block_version"], e["block_length"], e["tables"] = block_tables(s, block)
61 d["entries"].append(e)
62 return d
63
64
65def _read(path, segments):
66 with open(path, "rb") as fh:
67 data = b""
68 for off, stored, raw in segments:
69 fh.seek(off)
70 data += fh.read(stored) if raw else zlib.decompressobj().decompress(fh.read(stored))
71 return data
72
73
74def scan(path, start=None, limit=None):
75 rows, walk = anim_index.scan_rpf(path, start, limit)
76 with open(path, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m:
77 groups, _unresolved, _gaps = anim_clips.group(m, rows)
78 stats, dicts = collections.Counter(), []
79 for _i, parts in groups:
80 segments = [anim_clips.segment(rows, k) for k in parts]
81 with open(path, "rb") as fh:
82 fh.seek(segments[0][0])
83 head = fh.read(segments[0][1])
84 first = head if segments[0][2] else zlib.decompressobj().decompress(head, 0x80)
85 if not is_rig_dictionary(first):
86 continue
87 s = anim_clips.System(_read(path, segments))
88 try:
89 d = parse_rig_dictionary(s)
90 except (anim_clips.DecodeError, struct.error) as e:
91 stats["rig_dictionaries_unparsed"] += 1
92 dicts.append({"offset": segments[0][0], "error": str(e)[:120]})
93 continue
94 d["offset"], d["streams"], d["system_bytes"] = segments[0][0], len(segments), len(s.d)
95 dicts.append(d)
96 stats["rig_dictionaries"] += 1
97 stats["rig_dictionary_hash_matches_name"] += d["name"] is not None and anim_index.joaat32(d["name"]) == d["hash"]
98 stats[f"rig_dictionary_version:{d['version']}"] += 1
99 for e in d["entries"]:
100 stats["entries"] += 1
101 stats["entries_key_high_zero"] += e["key_high"] == 0
102 if e["block"] is None:
103 stats["entries_without_block"] += 1
104 continue
105 stats["entries_with_block"] += 1
106 stats[f"block_version:{e['block_version']}"] += 1
107 stats["tables"] += len(e["tables"])
108 for kind, count in e["tables"]:
109 stats[f"table_kind:0x{kind:08x}"] += 1
110 stats[f"table_items:0x{kind:08x}"] += count
111 return dicts, {"streams": walk["files"], "dictionary_roots": len(groups), "counts": dict(sorted(stats.items()))}
112
113
114def join_rbf0(dicts, rigs):
115 """Resolve the rig-set manager's entries: source = rig dictionary name, joaat32(rig) = a key there."""
116 keys = {d["name"]: {e["key"] for e in d.get("entries", ())} for d in dicts if d.get("name")}
117 entries = [e for rs in rigs["rbf0"]["rigsets"] for e in rs["entries"]]
118 c = collections.Counter()
119 for e in entries:
120 h = anim_index.joaat32(e["rig"].lower())
121 if h in keys.get(e["source"], ()):
122 c["resolved"] += 1
123 elif any(h in k for k in keys.values()):
124 c["in_another_dictionary"] += 1
125 elif e["source"] not in keys:
126 c["no_dictionary_named_source"] += 1
127 else:
128 c["key_missing"] += 1
129 distinct = {(e["source"], e["rig"].lower()) for e in entries}
130 used = {(src, anim_index.joaat32(r)) for src, r in distinct}
131 c["distinct_rigs"] = len(distinct)
132 c["keys"] = sum(len(k) for k in keys.values())
133 c["keys_named_by_an_entry"] = sum(1 for name, k in keys.items() for h in k if (name, h) in used)
134 return dict(sorted(c.items()))
135
136
137def main():
138 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
139 ap.add_argument("archive", help="anim.rpf")
140 ap.add_argument("out", help="output .json (counts and one row per rig dictionary)")
141 ap.add_argument("--rigs", help="the JSON anim_index.py --rigs wrote, to resolve the RBF0 entries")
142 ap.add_argument("--start", type=anim_index.offset, help="first byte to scan (default: the RPF data start)")
143 ap.add_argument("--limit", type=anim_index.byte_count, help="number of bytes to scan")
144 a = ap.parse_args()
145 try:
146 dicts, summary = scan(a.archive, a.start, a.limit)
147 if a.rigs:
148 with open(a.rigs, encoding="utf-8") as f:
149 summary["rbf0_join"] = join_rbf0(dicts, json.load(f))
150 except ValueError as e:
151 sys.exit(f"{a.archive}: {e}")
152 except OSError as e:
153 sys.exit(f"{e.filename or a.archive}: {e.strerror or e}")
154 rows = [{k: v for k, v in d.items() if k != "entries"} | {"entries": len(d.get("entries", ()))} for d in dicts]
155 try:
156 with open(a.out, "w", encoding="utf-8", newline="\n") as f:
157 json.dump({"summary": summary, "rig_dictionaries": rows}, f, indent=1)
158 except OSError as e:
159 sys.exit(f"{a.out}: cannot write: {e.strerror or e}")
160 c = summary["counts"]
161 print(json.dumps({k: c.get(k, 0) for k in ("rig_dictionaries", "entries", "entries_with_block", "tables")}))
162 if "rbf0_join" in summary:
163 print(json.dumps(summary["rbf0_join"]))
164 return 0
165
166
167if __name__ == "__main__":
168 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
169 sys.stdout.reconfigure(errors="replace")
170 except (AttributeError, ValueError, OSError):
171 pass
172 sys.exit(main())
diff --git a/tools/awc_names.py b/tools/awc_names.py
index ae8b345fe..ec3568e34 100644
--- a/tools/awc_names.py
+++ b/tools/awc_names.py
@@ -281,11 +281,12 @@ def main(argv=None) -> int:
281 a = ap.parse_args(argv) 281 a = ap.parse_args(argv)
282 if not a.words and not a.conversations: 282 if not a.words and not a.conversations:
283 ap.error("give at least one --words or --conversations source") 283 ap.error("give at least one --words or --conversations source")
284 for path in a.banks + a.words + a.conversations: 284 inputs = a.banks + a.words + a.conversations
285 for path in inputs:
285 if not os.path.exists(path): 286 if not os.path.exists(path):
286 print(f"awc_names: error: {path}: no such file or directory", file=sys.stderr) 287 print(f"awc_names: error: {path}: no such file or directory", file=sys.stderr)
287 return 2 288 return 2
288 if a.out and any(os.path.exists(a.out) and os.path.samefile(p, a.out) for p in a.banks + a.words): 289 if a.out and os.path.exists(a.out) and any(os.path.samefile(p, a.out) for p in inputs):
289 ap.error("--out must not overwrite an input") 290 ap.error("--out must not overwrite an input")
290 291
291 words = [] 292 words = []
@@ -317,7 +318,7 @@ def main(argv=None) -> int:
317 if a.out: 318 if a.out:
318 try: 319 try:
319 if a.out.lower().endswith(".json"): 320 if a.out.lower().endswith(".json"):
320 with open(a.out, "w", encoding="utf-8") as fh: 321 with open(a.out, "w", encoding="utf-8", newline="\n") as fh:
321 json.dump({"summary": summary, "streams": rows}, fh, indent=1) 322 json.dump({"summary": summary, "streams": rows}, fh, indent=1)
322 else: 323 else:
323 with open(a.out, "w", encoding="utf-8", newline="") as fh: 324 with open(a.out, "w", encoding="utf-8", newline="") as fh:
diff --git a/tools/awc_opus.py b/tools/awc_opus.py
index cb96c55a9..5bad0dfbb 100644
--- a/tools/awc_opus.py
+++ b/tools/awc_opus.py
@@ -95,25 +95,47 @@ OPUS_PRE_SKIP = 312
95 95
96def write_ogg_opus(path: str, packets: list, channels: int, serial: int, length: int = 0, 96def write_ogg_opus(path: str, packets: list, channels: int, serial: int, length: int = 0,
97 pre_skip: int = OPUS_PRE_SKIP) -> int: 97 pre_skip: int = OPUS_PRE_SKIP) -> int:
98 """length: the stream's declared per-channel sample count at 48 kHz; the last page's granule position is 98 """length: the stream's declared per-channel sample count at 48 kHz; the EOS page's granule position is
99 trimmed to pre_skip + length (Ogg Opus granules count the pre-skip too), so decoders drop the encoder priming 99 trimmed to pre_skip + length (Ogg Opus granules count the pre-skip too), so decoders drop the encoder priming
100 at the start and stop at the exact end instead of the padded last frame.""" 100 at the start and stop at the exact end instead of the padded last frame.
101
102 The EOS page is emitted at the packet that first reaches pre_skip + length; any later packets are encoder
103 padding and are dropped. Clamping only the final page would make its granule smaller than the previous page's
104 when the trim point falls before that page starts, which is invalid Ogg and makes decoders keep the excess.
105 """
106 if not 0 <= pre_skip <= 0xFFFF:
107 raise ValueError(f"pre-skip must be 0..65535, got {pre_skip}")
108 if length < 0:
109 raise ValueError(f"length must be non-negative, got {length}")
110 total = sum(opus_samples(p) for p in packets)
111 if pre_skip > total:
112 pre_skip = total # a granule below the pre-skip makes the stream undecodable
101 head = b"OpusHead" + struct.pack("<BBHIhB", 1, channels, pre_skip, 48000, 0, 0) 113 head = b"OpusHead" + struct.pack("<BBHIhB", 1, channels, pre_skip, 48000, 0, 0)
102 tags = b"OpusTags" + struct.pack("<I", 8) + b"leonida " + struct.pack("<I", 0) 114 tags = b"OpusTags" + struct.pack("<I", 8) + b"leonida " + struct.pack("<I", 0)
103 out = [ogg_page(serial, 0, 0, [head], 0x02), ogg_page(serial, 1, 0, [tags], 0x00)] 115 out = [ogg_page(serial, 0, 0, [head], 0x02), ogg_page(serial, 1, 0, [tags], 0x00)]
104 seq, granule, pending, size = 2, 0, [], 0 116 seq, granule, pending, size = 2, 0, [], 0
117 target = pre_skip + length if length > 0 else None
118 written = 0
119 if not packets:
120 out.append(ogg_page(serial, 2, pre_skip, [], 0x04))
121 write_file(path, b"".join(out))
122 return pre_skip
105 for i, p in enumerate(packets): 123 for i, p in enumerate(packets):
106 pending.append(p) 124 pending.append(p)
107 granule += opus_samples(p) 125 granule += opus_samples(p)
108 size += len(p) 126 size += len(p)
127 reach = target is not None and granule >= target
109 last = i == len(packets) - 1 128 last = i == len(packets) - 1
110 if size > 4000 or len(pending) >= 50 or last: 129 if reach or size > 4000 or len(pending) >= 50 or last:
111 g = min(granule, pre_skip + length) if (last and 0 < length) else granule 130 g = target if reach else granule
112 out.append(ogg_page(serial, seq, g, pending, 0x04 if last else 0x00)) 131 out.append(ogg_page(serial, seq, g, pending, 0x04 if (reach or last) else 0x00))
132 written = g
113 seq += 1 133 seq += 1
114 pending, size = [], 0 134 pending, size = [], 0
135 if reach or last:
136 break
115 write_file(path, b"".join(out)) 137 write_file(path, b"".join(out))
116 return granule 138 return written
117 139
118 140
119def write_file(path: str, data: bytes) -> None: 141def write_file(path: str, data: bytes) -> None:
@@ -293,9 +315,12 @@ def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP):
293 pk = opus_packets(d, at, size) 315 pk = opus_packets(d, at, size)
294 if pk: 316 if pk:
295 # +0x0C is the per-channel Opus frame count: equal to the +0 count for mono and 317 # +0x0C is the per-channel Opus frame count: equal to the +0 count for mono and
296 # half of it for stereo in all 7,451 measured streams. Fall back to dividing the 318 # half of it for stereo in all 7,451 measured streams. Use it only when it agrees
297 # interleaved count when a synthetic or malformed block leaves the field zero. 319 # with the interleaved +0 count; a synthetic or malformed block that disagrees
298 frames = s["frames"] or s["samples"] // max(1, s["channels"]) 320 # must not silently truncate the real audio.
321 frames = s["frames"]
322 if not frames or frames * s["channels"] != s["samples"]:
323 frames = s["samples"] // max(1, s["channels"])
299 write_ogg_opus(os.path.join(od, stem + ".ogg"), pk, s["channels"], s["id"], frames, 324 write_ogg_opus(os.path.join(od, stem + ".ogg"), pk, s["channels"], s["id"], frames,
300 pre_skip=pre_skip) 325 pre_skip=pre_skip)
301 counts["opus"] += 1 326 counts["opus"] += 1
diff --git a/tools/bink_index.py b/tools/bink_index.py
index 2b8232834..0d4ac4315 100644
--- a/tools/bink_index.py
+++ b/tools/bink_index.py
@@ -285,7 +285,7 @@ def write_csv(path, rows, probe):
285def write_json(path, target, rows, summary, probe): 285def write_json(path, target, rows, summary, probe):
286 fields = BASE_FIELDS + (PROBE_FIELDS if probe else []) 286 fields = BASE_FIELDS + (PROBE_FIELDS if probe else [])
287 streams = [_flat(row, fields) for row in rows] 287 streams = [_flat(row, fields) for row in rows]
288 with open(path, "w", encoding="utf-8") as fh: 288 with open(path, "w", encoding="utf-8", newline="\n") as fh:
289 json.dump({"target": target, "summary": summary, "streams": streams}, 289 json.dump({"target": target, "summary": summary, "streams": streams},
290 fh, indent=1) 290 fh, indent=1)
291 291
diff --git a/tools/bink_names.py b/tools/bink_names.py
index 13bc9b12a..a31c3d2c6 100644
--- a/tools/bink_names.py
+++ b/tools/bink_names.py
@@ -299,7 +299,7 @@ def name_streams(names, streams, pins=None, max_skip=MAX_SKIP):
299 299
300def write(out, rows, unmatched, summary): 300def write(out, rows, unmatched, summary):
301 if out.lower().endswith(".json"): 301 if out.lower().endswith(".json"):
302 with open(out, "w", encoding="utf-8") as fh: 302 with open(out, "w", encoding="utf-8", newline="\n") as fh:
303 json.dump({"summary": summary, "streams": rows, "unmatched_list_entries": unmatched}, fh, indent=1) 303 json.dump({"summary": summary, "streams": rows, "unmatched_list_entries": unmatched}, fh, indent=1)
304 else: 304 else:
305 with open(out, "w", encoding="utf-8", newline="") as fh: 305 with open(out, "w", encoding="utf-8", newline="") as fh:
@@ -318,6 +318,8 @@ def main(argv=None):
318 ap.add_argument("--max-skip", type=int, default=MAX_SKIP, help="most list entries skipped in a row") 318 ap.add_argument("--max-skip", type=int, default=MAX_SKIP, help="most list entries skipped in a row")
319 ap.add_argument("--out", help="names.csv or names.json; default is a summary only") 319 ap.add_argument("--out", help="names.csv or names.json; default is a summary only")
320 a = ap.parse_args(argv) 320 a = ap.parse_args(argv)
321 if a.max_skip < 0:
322 ap.error("--max-skip must be 0 or more")
321 inputs = [a.source, *a.mount] + ([a.pins] if a.pins else []) 323 inputs = [a.source, *a.mount] + ([a.pins] if a.pins else [])
322 for path in inputs: 324 for path in inputs:
323 if not os.path.exists(path): 325 if not os.path.exists(path):
diff --git a/tools/bvh_index.py b/tools/bvh_index.py
index 90bcd3bbc..501774553 100644
--- a/tools/bvh_index.py
+++ b/tools/bvh_index.py
@@ -351,7 +351,7 @@ def write_outputs(rows, summaries, out, csv_path):
351 if out: 351 if out:
352 _make_parent(out) 352 _make_parent(out)
353 payload = summaries if len(summaries) > 1 else (summaries[0] if summaries else {}) 353 payload = summaries if len(summaries) > 1 else (summaries[0] if summaries else {})
354 with open(out, "w", encoding="utf-8") as f: 354 with open(out, "w", encoding="utf-8", newline="\n") as f:
355 json.dump({"summary": payload, "streams": rows}, f, indent=0) 355 json.dump({"summary": payload, "streams": rows}, f, indent=0)
356 if csv_path: 356 if csv_path:
357 _make_parent(csv_path) 357 _make_parent(csv_path)
diff --git a/tools/calibrated_texture.py b/tools/calibrated_texture.py
index 641b44a09..6aeefc697 100644
--- a/tools/calibrated_texture.py
+++ b/tools/calibrated_texture.py
@@ -10,6 +10,9 @@ import sys
10import tempfile 10import tempfile
11import zlib 11import zlib
12 12
13# `python -I` implies `-P`, so the script's directory is not on sys.path; the sibling modules are next to it.
14sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
15
13import numpy as np 16import numpy as np
14import bcpack 17import bcpack
15import bcpack_tables 18import bcpack_tables
diff --git a/tools/cf_diff.py b/tools/cf_diff.py
index 741e21561..70d144753 100644
--- a/tools/cf_diff.py
+++ b/tools/cf_diff.py
@@ -567,7 +567,7 @@ def self_test():
567 e.items = [it for it in e.items if not (it[0] == "ins" and it[1].startswith("s_or_b32 exec_lo"))] 567 e.items = [it for it in e.items if not (it[0] == "ins" and it[1].startswith("s_or_b32 exec_lo"))]
568 with tempfile.TemporaryDirectory(prefix="cf-diff-") as tmp: 568 with tempfile.TemporaryDirectory(prefix="cf-diff-") as tmp:
569 p = os.path.join(tmp, "c.s") 569 p = os.path.join(tmp, "c.s")
570 with open(p, "w", encoding="utf-8") as f: 570 with open(p, "w", encoding="utf-8", newline="\n") as f:
571 f.write(listing_text(e.assemble(), "ps_canary_bad")) 571 f.write(listing_text(e.assemble(), "ps_canary_bad"))
572 if len(cf_ref.run(p, wave=32)["exports"]) != 4: # 4 > lane: lanes 0-3 stay on 572 if len(cf_ref.run(p, wave=32)["exports"]) != 4: # 4 > lane: lanes 0-3 stay on
573 print("canary FAILED: the reference did not drop lanes whose EXEC was never restored") 573 print("canary FAILED: the reference did not drop lanes whose EXEC was never restored")
diff --git a/tools/classify_carve.py b/tools/classify_carve.py
index 1c3e6f5d2..819de999f 100644
--- a/tools/classify_carve.py
+++ b/tools/classify_carve.py
@@ -102,7 +102,7 @@ def main():
102 out = {"overall": {k: entry(v) for k, v in top}, "per_archive": per} 102 out = {"overall": {k: entry(v) for k, v in top}, "per_archive": per}
103 fd, temp = tempfile.mkstemp(dir=root, prefix=".types-", suffix=".tmp") 103 fd, temp = tempfile.mkstemp(dir=root, prefix=".types-", suffix=".tmp")
104 try: 104 try:
105 with os.fdopen(fd, "w", encoding="utf-8") as f: 105 with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as f:
106 json.dump(out, f, indent=1) 106 json.dump(out, f, indent=1)
107 f.flush() 107 f.flush()
108 os.fsync(f.fileno()) 108 os.fsync(f.fileno())
diff --git a/tools/crosslane_fuzz.py b/tools/crosslane_fuzz.py
index 92b9ea3fb..7072978c3 100644
--- a/tools/crosslane_fuzz.py
+++ b/tools/crosslane_fuzz.py
@@ -739,10 +739,10 @@ def assemble(mc, prog, src, disasm, fssm):
739 if r.returncode or "error:" in r.stderr: 739 if r.returncode or "error:" in r.stderr:
740 raise RuntimeError(f"{prog.name} did not assemble:\n{r.stderr}\n{src}") 740 raise RuntimeError(f"{prog.name} did not assemble:\n{r.stderr}\n{src}")
741 code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith(".")) 741 code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith("."))
742 with open(os.path.join(disasm, prog.name + ".s"), "w", encoding="utf-8") as f: 742 with open(os.path.join(disasm, prog.name + ".s"), "w", encoding="utf-8", newline="\n") as f:
743 f.write(f"; {prog.name} crosslane_fuzz\n{code}") 743 f.write(f"; {prog.name} crosslane_fuzz\n{code}")
744 asm_path = os.path.join(fssm, prog.name + ".asm") 744 asm_path = os.path.join(fssm, prog.name + ".asm")
745 with open(asm_path, "w", encoding="utf-8") as f: 745 with open(asm_path, "w", encoding="utf-8", newline="\n") as f:
746 f.write(src) 746 f.write(src)
747 with open(os.path.join(fssm, prog.name + ".fssm"), "wb") as f: 747 with open(os.path.join(fssm, prog.name + ".fssm"), "wb") as f:
748 f.write(compute_fixture.compute_header(asm_path)) 748 f.write(compute_fixture.compute_header(asm_path))
@@ -1008,7 +1008,7 @@ def main():
1008 print(describe(p, bad)) 1008 print(describe(p, bad))
1009 if args.keep: 1009 if args.keep:
1010 os.makedirs(args.keep, exist_ok=True) 1010 os.makedirs(args.keep, exist_ok=True)
1011 with open(os.path.join(args.keep, f"{p.name}_{mode}.asm"), "w", encoding="utf-8") as f: 1011 with open(os.path.join(args.keep, f"{p.name}_{mode}.asm"), "w", encoding="utf-8", newline="\n") as f:
1012 f.write(kept_source(p, mode, None, not args.no_hw_guard)) 1012 f.write(kept_source(p, mode, None, not args.no_hw_guard))
1013 if args.minimize and bad and what.startswith("mismatch"): 1013 if args.minimize and bad and what.startswith("mismatch"):
1014 if mode == "hw": 1014 if mode == "hw":
@@ -1021,7 +1021,7 @@ def main():
1021 print(" minimized:\n\t" + "\n\t".join(o.text + (" ; hypothesis op" if i in hyp_ops else "") 1021 print(" minimized:\n\t" + "\n\t".join(o.text + (" ; hypothesis op" if i in hyp_ops else "")
1022 for i, o in enumerate(ops))) 1022 for i, o in enumerate(ops)))
1023 if args.keep: 1023 if args.keep:
1024 with open(os.path.join(args.keep, f"{p.name}_{mode}_min.asm"), "w", encoding="utf-8") as f: 1024 with open(os.path.join(args.keep, f"{p.name}_{mode}_min.asm"), "w", encoding="utf-8", newline="\n") as f:
1025 f.write(kept_source(p, mode, ops, not args.no_hw_guard)) 1025 f.write(kept_source(p, mode, ops, not args.no_hw_guard))
1026 finally: 1026 finally:
1027 if oracle: 1027 if oracle:
diff --git a/tools/d16_format_probe.py b/tools/d16_format_probe.py
new file mode 100644
index 000000000..23fe49b6c
--- /dev/null
+++ b/tools/d16_format_probe.py
@@ -0,0 +1,341 @@
1r"""How an RDNA2 GPU rounds UNORM/SNORM buffer loads to f16 with d16 (BUILD-161). Standard library only.
2
3docs/design.md ("d16 and f16 format narrowing") narrows every d16 result with integer round to nearest even, but
4for typed buffer loads that rounding was inferred (#489, #711), not measured. This sweep measures it: every value of
5each format below goes through buffer_load_format_d16_x and tbuffer_load_format_d16_x natively on the GPU (through
6tools/hw_oracle/), in wave32 and wave64. Every result is compared with several candidate rules computed from the
7exact quotient (Fraction arithmetic):
8
9 f32_rte x / (2^n - 1) (SNORM: max(s / (2^(n-1) - 1), -1)) rounded to f32 (nearest even), then to f16
10 nearest even: the translator's rule before BUILD-161 (the exact binary32 decode, then Gen.f16_bits)
11 f32_rtz rounded to f32, then to f16 toward zero (v_cvt_pkrtz_f16_f32 of the f32 value; PackHalf2x16 on AMD
12 drivers, the #489 bug)
13 rte the exact quotient rounded once to f16, nearest even (no f32 step): what an RX 6700 does, and the
14 translator's rule since BUILD-161 (Gen.d16_norm_f16)
15 rtz the exact quotient rounded once to f16, toward zero
16 mul_rte the f32 product v * f32(1 / (2^n - 1)) (a reciprocal multiply, not a division), then f16 nearest even
17
18and each rule again with f16 denormal results flushed to zero (UNORM16 and SNORM16 have quotients under 2^-14).
19Only the 16-bit formats tell the f32 step apart: rte and f32_rte differ on UNORM16 0xffaf and 0xffef and on SNORM16
200x7ff7 and 0x8009, and a flush shows on the smallest UNORM16 / SNORM16 values. On UNORM8, SNORM8 and UNORM10 every
21rule but the rtz ones gives the same bits.
22buffer_load_format_x (an f32 result, no d16) runs on the same values against the f32 rules, so the two stages can be
23told apart. Controls that must hold for the sweep to count: every staged input word reads back as written, a
2416_FLOAT d16 load returns its own bits, and d16_x leaves the high half of its VGPR as it was.
25
26The kernels write their own inputs: thread t stores the format's bits for value base + t at dword t of the output
27buffer, waits for the store, builds a GFX10 buffer descriptor (V#) over that buffer and loads its element with glc dlc
28(past the L0 and GL1 caches), then stores the loaded VGPR at dword 1024 + t. GFX10 only (RDNA1 and RDNA2: the
29V# layout, RESOURCE_LEVEL = 1), which is what BUILD-161 asks for; another architecture exits 77.
30
31Usage:
32 python -I tools/d16_format_probe.py [--formats unorm8,snorm16] [--waves 32,64] [--json out.json]
33 python -I tools/d16_format_probe.py --self-test # the models against known counts, no GPU
34
35Exit 0 when the sweep ran (which rule the hardware follows is a finding, not a failure), 1 when wave32 and wave64
36or MUBUF and MTBUF disagree, 2 on a harness error (a control failed, a kernel without its words), 77 when the
37hardware oracle is unavailable or the GPU is not GFX10. Nothing here reads game files.
38"""
39import argparse
40import json
41import os
42import struct
43import sys
44from fractions import Fraction
45
46HERE = os.path.dirname(os.path.abspath(__file__))
47sys.dont_write_bytecode = True
48if HERE not in sys.path:
49 sys.path.insert(0, HERE)
50
51# name: (GFX10 unified buffer format code, kind, bits of the x channel). The codes are the translator's FORMATS
52# table (tools/rdna2spirv.py); 10_10_10_2 (50) holds x in its low 10 bits.
53FORMATS = {
54 "unorm8": (1, "unorm", 8),
55 "snorm8": (2, "snorm", 8),
56 "unorm16": (7, "unorm", 16),
57 "snorm16": (8, "snorm", 16),
58 "unorm10": (50, "unorm", 10),
59 "float16": (13, "f16", 16), # control: d16 of an f16 element is its own bits
60}
61INSTS = ("buffer_d16", "tbuffer_d16", "buffer_f32")
62THREADS = 1024
63WORDS = 2 * THREADS
64HI_SEED = 0xBEEF0000 # the d16_x destination starts as this | 0x1234; the high half must stay
65LO_SEED = 0x1234
66RULES16 = ("f32_rte", "f32_rtz", "rte", "rtz", "mul_rte")
67RULES32 = ("f32_rte", "f32_rtz", "mul_f32")
68
69
70# ---- exact arithmetic ----
71
72def round_frac(x, prec, emin, rtz=False):
73 """x rounded to a binary float with prec significand bits (implicit bit included) and minimum normal exponent
74 emin, denormals kept; nearest even, or toward zero. No overflow: every value here is in [-1, 1]."""
75 if x == 0:
76 return Fraction(0)
77 sign = -1 if x < 0 else 1
78 a = abs(x)
79 e = a.numerator.bit_length() - a.denominator.bit_length()
80 if Fraction(2) ** e > a:
81 e -= 1
82 if Fraction(2) ** (e + 1) <= a:
83 e += 1
84 ulp = Fraction(2) ** (max(e, emin) - prec + 1)
85 q = a / ulp
86 n = q.numerator // q.denominator if rtz else round(q) # round() of a Fraction is half to even
87 return sign * n * ulp
88
89
90def f16_bits(v):
91 return struct.unpack("<H", struct.pack("<e", float(v)))[0]
92
93
94def f32_bits(v):
95 return struct.unpack("<I", struct.pack("<f", float(v)))[0]
96
97
98def to_f16(x, rtz=False):
99 return round_frac(x, 11, -14, rtz)
100
101
102def to_f32(x, rtz=False):
103 return round_frac(x, 24, -126, rtz)
104
105
106def quotient(kind, n, v):
107 """The exact value of raw channel bits v (n bits) for a UNORM or SNORM channel."""
108 if kind == "unorm":
109 return Fraction(v, (1 << n) - 1)
110 s = v - (1 << n) if v >> (n - 1) else v
111 return max(Fraction(s, (1 << (n - 1)) - 1), Fraction(-1))
112
113
114def is_denorm16(h):
115 return (h & 0x7C00) == 0 and (h & 0x3FF) != 0
116
117
118def models16(kind, n, v):
119 """{rule: f16 bits} for one input, plus each rule with a denormal result flushed (rule + '_flush')."""
120 x = quotient(kind, n, v)
121 rcp = to_f32(Fraction(1, (1 << n) - 1) if kind == "unorm" else Fraction(1, (1 << (n - 1)) - 1))
122 s = (v - (1 << n) if v >> (n - 1) else v) if kind == "snorm" else v
123 prod = max(to_f32(s * rcp), Fraction(-1))
124 out = {"rte": f16_bits(to_f16(x)), "rtz": f16_bits(to_f16(x, True)), "f32_rte": f16_bits(to_f16(to_f32(x))),
125 "f32_rtz": f16_bits(to_f16(to_f32(x), True)), "mul_rte": f16_bits(to_f16(prod))}
126 for r in RULES16:
127 out[r + "_flush"] = (out[r] & 0x8000) if is_denorm16(out[r]) else out[r]
128 return out
129
130
131def models32(kind, n, v):
132 x = quotient(kind, n, v)
133 rcp = to_f32(Fraction(1, (1 << n) - 1) if kind == "unorm" else Fraction(1, (1 << (n - 1)) - 1))
134 s = (v - (1 << n) if v >> (n - 1) else v) if kind == "snorm" else v
135 return {"f32_rte": f32_bits(to_f32(x)), "f32_rtz": f32_bits(to_f32(x, True)),
136 "mul_f32": f32_bits(max(to_f32(s * rcp), Fraction(-1)))}
137
138
139# ---- kernels ----
140
141def descriptor_word3(code):
142 """GFX10 V# dword 3: DST_SEL x/y/z/w = X/Y/Z/W (4, 5, 6, 7), FORMAT [18:12], RESOURCE_LEVEL [24] = 1,
143 OOB_SELECT [29:28] = 3 (raw: in bounds while offset < NUM_RECORDS), TYPE [31:30] = 0 (buffer)."""
144 return 4 | 5 << 3 | 6 << 6 | 7 << 9 | code << 12 | 1 << 24 | 3 << 28
145
146
147def kernel_lines(inst, fmt, base):
148 """Thread t: stage format bits (base + t) & mask at dword t, load the element, store the VGPR at dword 1024 + t."""
149 code, kind, n = FORMATS[fmt]
150 mask = (1 << n) - 1
151 load = {"buffer_d16": "buffer_load_format_d16_x v3, v2, s[8:11], 0 offen glc dlc",
152 "tbuffer_d16": f"tbuffer_load_format_d16_x v3, v2, s[8:11], 0 format:{code} offen glc dlc",
153 "buffer_f32": "buffer_load_format_x v3, v2, s[8:11], 0 offen glc dlc"}[inst]
154 return [
155 f"v_add_nc_u32 v1, 0x{base:x}, v0",
156 f"v_and_b32 v1, 0x{mask:x}, v1",
157 "v_lshlrev_b32 v2, 2, v0",
158 "global_store_b32 v2, v1, s[2:3]",
159 "s_waitcnt_vscnt null, 0x0",
160 "s_mov_b32 s8, s2",
161 "s_and_b32 s9, s3, 0xffff", # BASE_ADDRESS[47:32]; STRIDE 0, no swizzle
162 f"s_mov_b32 s10, 0x{4 * THREADS:x}", # NUM_RECORDS: the staged inputs, in bytes
163 f"s_mov_b32 s11, 0x{descriptor_word3(code):x}",
164 f"v_mov_b32 v3, 0x{HI_SEED | LO_SEED:x}",
165 load,
166 "s_waitcnt vmcnt(0)",
167 f"v_add_nc_u32 v4, 0x{4 * THREADS:x}, v2",
168 "global_store_b32 v4, v3, s[2:3]",
169 "s_endpgm",
170 ]
171
172
173def jobs(fmt):
174 """(inst, base) for every kernel a format needs: one per 1024 values."""
175 n = FORMATS[fmt][2]
176 insts = ("buffer_d16", "tbuffer_d16") if FORMATS[fmt][1] == "f16" else INSTS
177 return [(inst, base) for inst in insts for base in range(0, 1 << n, THREADS)]
178
179
180def sweep(oracle, fmt, wave):
181 """{inst: [loaded VGPR word per value]} for every value of the format, or raise RuntimeError."""
182 from hw_oracle import asm
183 n = FORMATS[fmt][2]
184 todo = jobs(fmt)
185 kernels = [asm.Kernel(kernel_lines(inst, fmt, base), wave, THREADS, WORDS, raw=True, vgprs=8, sgprs=16)
186 for inst, base in todo]
187 got = oracle.run(kernels, words=WORDS)
188 out = {}
189 for (inst, base), words in zip(todo, got):
190 if isinstance(words, str) or len(words) != WORDS:
191 raise RuntimeError(f"{fmt} {inst} wave{wave} base {base}: "
192 f"{words if isinstance(words, str) else f'{len(words)} words'}")
193 count = min(THREADS, (1 << n) - base)
194 staged = words[:count]
195 want = [(base + t) & ((1 << n) - 1) for t in range(count)]
196 if staged != want:
197 bad = next(t for t in range(count) if staged[t] != want[t])
198 raise RuntimeError(f"{fmt} {inst} wave{wave}: staged input {want[bad]:#x} read back as {staged[bad]:#x}")
199 out.setdefault(inst, []).extend(words[THREADS:THREADS + count])
200 return out
201
202
203# ---- comparison ----
204
205def classify(fmt, hw):
206 """Counts of inputs each rule predicts exactly, the inputs where the translator's rule (rte for d16, f32_rte for f32) is wrong, and the
207 control failures. hw: {inst: [VGPR word per value]}."""
208 _, kind, n = FORMATS[fmt]
209 res = {"inputs": 1 << n, "insts": {}, "control": []}
210 for inst, words in hw.items():
211 d16 = inst.endswith("d16")
212 if d16:
213 hi_bad = [v for v, w in enumerate(words) if w >> 16 != HI_SEED >> 16]
214 if hi_bad:
215 res["control"].append(f"{inst}: d16_x changed the high half for {len(hi_bad)} values "
216 f"(first {hi_bad[0]:#x}: {words[hi_bad[0]]:#010x})")
217 if kind == "f16":
218 wrong = [v for v, w in enumerate(words) if (w & 0xFFFF) != v and not (
219 (v & 0x7C00) == 0x7C00 and v & 0x3FF and (w & 0x7C00) == 0x7C00 and w & 0x3FF)]
220 if wrong:
221 res["control"].append(f"{inst}: 16_FLOAT came back changed for {len(wrong)} values "
222 f"(first {wrong[0]:#06x} -> {words[wrong[0]] & 0xFFFF:#06x})")
223 res["insts"][inst] = {"own_bits": (1 << n) - len(wrong)}
224 continue
225 rules = (tuple(RULES16) + tuple(r + "_flush" for r in RULES16)) if d16 else RULES32
226 match = dict.fromkeys(rules, 0)
227 off = []
228 for v, w in enumerate(words):
229 got = w & 0xFFFF if d16 else w
230 m = models16(kind, n, v) if d16 else models32(kind, n, v)
231 for r in rules:
232 match[r] += got == m[r]
233 rule = "rte" if d16 else "f32_rte" # the translator's rule (Gen.d16_norm_f16, norm_bits)
234 if got != m[rule]:
235 off.append((v, got, m[rule], m))
236 res["insts"][inst] = {"match": match, "off_rule": len(off),
237 "first_off": [{"value": f"{v:#x}", "hw": f"{g:#x}", "rule": f"{r:#x}",
238 "fits": [k for k in rules if m[k] == g]} for v, g, r, m in off[:8]]}
239 return res
240
241
242def rte_rtz_disagreements(kind, n):
243 """How many inputs the translator's rule and the #489 bug (f32 then RTZ) narrow differently (docs/design.md:
244 123 of 256 UNORM8 and 110 of 256 SNORM8 loaded 1 ulp low)."""
245 return sum(models16(kind, n, v)["f32_rte"] != models16(kind, n, v)["f32_rtz"] for v in range(1 << n))
246
247
248def self_test():
249 assert round_frac(Fraction(1, 3), 11, -14) == Fraction(1365, 4096) # 0x3555
250 assert f16_bits(to_f16(Fraction(1, 255))) == 0x1C04 # 2^-8 * 1.00390625
251 assert f16_bits(to_f16(Fraction(9, 255))) == 0x2885 and f16_bits(to_f16(Fraction(9, 255), True)) == 0x2884
252 assert f16_bits(to_f16(Fraction(1, 65535))) == 0x0100 and is_denorm16(0x0100) # under 2^-14
253 assert f16_bits(to_f16(Fraction(1, 2) + Fraction(1, 4096))) == 0x3800 # a tie: to even
254 assert quotient("snorm", 8, 0x80) == -1 and quotient("snorm", 8, 0x81) == -1 and quotient("snorm", 8, 0x7F) == 1
255 assert models16("unorm", 8, 255)["rte"] == 0x3C00 and models16("snorm", 16, 0x8000)["rte"] == 0xBC00
256 assert models32("unorm", 8, 1)["f32_rte"] == 0x3B808081 # 1/255 in f32
257 assert models16("unorm", 16, 1)["f32_rte_flush"] == 0
258 assert models16("unorm", 16, 0xFFEF)["rte"] == 0x3BFF and models16("unorm", 16, 0xFFEF)["f32_rte"] == 0x3C00
259 assert models16("snorm", 16, 0x8009)["rte"] == 0xBBFF and models16("snorm", 16, 0x8009)["f32_rte"] == 0xBC00
260 assert rte_rtz_disagreements("unorm", 8) == 123
261 assert rte_rtz_disagreements("snorm", 8) == 110
262 w3 = descriptor_word3(7)
263 assert w3 & 0xFFF == 0xFAC and (w3 >> 12) & 0x7F == 7 and (w3 >> 24) & 1 and (w3 >> 28) & 3 == 3
264 lines = kernel_lines("tbuffer_d16", "unorm16", 0x400)
265 assert lines[0] == "v_add_nc_u32 v1, 0x400, v0" and "format:7 offen glc dlc" in lines[10]
266 assert len(jobs("unorm16")) == 3 * 64 and len(jobs("unorm8")) == 3 and len(jobs("float16")) == 2 * 64
267 print("self-test ok")
268 return 0
269
270
271def main(argv=None):
272 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
273 ap.add_argument("--formats", default=",".join(FORMATS))
274 ap.add_argument("--waves", default="32,64")
275 ap.add_argument("--json", help="write the counts and the first differences here")
276 ap.add_argument("--hw-arch")
277 ap.add_argument("--self-test", action="store_true")
278 a = ap.parse_args(argv)
279 if a.self_test:
280 return self_test()
281 fmts = [f for f in a.formats.split(",") if f]
282 waves = [int(w) for w in a.waves.split(",") if w.strip().isdigit()]
283 bad = [f for f in fmts if f not in FORMATS] + [w for w in a.waves.split(",") if w and w not in ("32", "64")]
284 if bad or not fmts or not waves:
285 ap.error("unknown or empty: " + ", ".join(bad or ["--formats/--waves"]))
286 from hw_oracle import asm, runner
287 try:
288 oracle = runner.open_oracle(arch=a.hw_arch)
289 except runner.Unavailable as e:
290 print(f"hardware oracle unavailable: {e}")
291 return 77
292 try:
293 if asm.family(oracle.arch) != "gfx10":
294 print(f"hardware oracle unavailable: {oracle.arch} is not GFX10; the descriptor here is GFX10's (RDNA2)")
295 return 77
296 print(f"hardware oracle: {oracle.device}")
297 report = {"device": str(oracle.device), "arch": oracle.arch, "formats": {}}
298 rc = 0
299 for fmt in fmts:
300 hw = {w: sweep(oracle, fmt, w) for w in waves}
301 first = hw[waves[0]]
302 entry = classify(fmt, first)
303 entry["waves_differ"] = {inst: sum(a_ != b_ for a_, b_ in zip(first[inst], hw[w][inst]))
304 for w in waves[1:] for inst in first}
305 if "tbuffer_d16" in first:
306 entry["mubuf_mtbuf_differ"] = sum((x ^ y) & 0xFFFF != 0
307 for x, y in zip(first["buffer_d16"], first["tbuffer_d16"]))
308 report["formats"][fmt] = entry
309 if entry["control"]:
310 for c in entry["control"]:
311 print(f"harness error: {fmt} {c}")
312 rc = 2
313 if any(entry["waves_differ"].values()) or entry.get("mubuf_mtbuf_differ"):
314 rc = max(rc, 1) if rc != 2 else 2
315 print(f"{fmt} ({entry['inputs']} values): wave32/64 differ {entry['waves_differ'] or 'n/a'}; "
316 f"MUBUF/MTBUF d16 differ {entry.get('mubuf_mtbuf_differ', 'n/a')}")
317 for inst, s in entry["insts"].items():
318 if "own_bits" in s:
319 print(f" {inst}: own bits {s['own_bits']}/{entry['inputs']}")
320 continue
321 print(f" {inst}: " + ", ".join(f"{r} {k}" for r, k in s["match"].items()) +
322 f"; off the rule {s['off_rule']}")
323 for o in s["first_off"][:3]:
324 print(f" value {o['value']}: hw {o['hw']}, rule {o['rule']}, fits {','.join(o['fits']) or '-'}")
325 except RuntimeError as e:
326 print(f"harness error: {e}")
327 return 2
328 finally:
329 oracle.close()
330 if a.json:
331 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
332 json.dump(report, f, indent=1)
333 return rc
334
335
336if __name__ == "__main__":
337 try:
338 sys.stdout.reconfigure(errors="replace")
339 except (AttributeError, ValueError, OSError):
340 pass
341 sys.exit(main())
diff --git a/tools/f16_trans_sweep.py b/tools/f16_trans_sweep.py
index 2b7f377df..96dd542d4 100644
--- a/tools/f16_trans_sweep.py
+++ b/tools/f16_trans_sweep.py
@@ -454,7 +454,7 @@ def main(argv=None):
454 finally: 454 finally:
455 oracle.close() 455 oracle.close()
456 if a.json: 456 if a.json:
457 with open(a.json, "w", encoding="utf-8") as f: 457 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
458 json.dump(report, f, indent=1) 458 json.dump(report, f, indent=1)
459 return rc 459 return rc
460 460
diff --git a/tools/f32_fuzz.py b/tools/f32_fuzz.py
index 7c23a58fd..09d464530 100644
--- a/tools/f32_fuzz.py
+++ b/tools/f32_fuzz.py
@@ -687,7 +687,7 @@ def run_translated(text, name="ps_f32_fuzz"):
687 dis = os.path.join(tmp, "disasm") 687 dis = os.path.join(tmp, "disasm")
688 os.mkdir(dis) 688 os.mkdir(dis)
689 path = os.path.join(dis, name + ".s") 689 path = os.path.join(dis, name + ".s")
690 with open(path, "w", encoding="utf-8") as f: 690 with open(path, "w", encoding="utf-8", newline="\n") as f:
691 f.write(text) 691 f.write(text)
692 with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: 692 with open(os.path.join(tmp, name + ".dxbc"), "wb") as f:
693 f.write(STUB_DXBC) 693 f.write(STUB_DXBC)
@@ -1727,7 +1727,7 @@ def main(argv=None):
1727 if a.keep and rep.mismatches: 1727 if a.keep and rep.mismatches:
1728 os.makedirs(a.keep, exist_ok=True) 1728 os.makedirs(a.keep, exist_ok=True)
1729 for k, (c, _, _) in enumerate(rep.mismatches): 1729 for k, (c, _, _) in enumerate(rep.mismatches):
1730 with open(os.path.join(a.keep, f"{c.group}_{c.index}_{c.op}_{k}.asm"), "w", encoding="utf-8") as f: 1730 with open(os.path.join(a.keep, f"{c.group}_{c.index}_{c.op}_{k}.asm"), "w", encoding="utf-8", newline="\n") as f:
1731 f.write("\n".join(hw_lines(c, oracle.arch, not a.no_hw_guard)) + "\n") 1731 f.write("\n".join(hw_lines(c, oracle.arch, not a.no_hw_guard)) + "\n")
1732 if a.perturb: 1732 if a.perturb:
1733 print(f"perturbed model '{a.perturb}': {n_mis} mismatches" + ("" if n_mis else " -- NOT DETECTED")) 1733 print(f"perturbed model '{a.perturb}': {n_mis} mismatches" + ("" if n_mis else " -- NOT DETECTED"))
diff --git a/tools/feature_scan.py b/tools/feature_scan.py
index 622a0bf8e..f2e28bf2d 100644
--- a/tools/feature_scan.py
+++ b/tools/feature_scan.py
@@ -1,4 +1,4 @@
1"""Scan the shader corpus for features the D3D12 -> Vulkan layer may need (docs/d3d12_vulkan.md §8.2 #10 and #14). 1"""Scan the shader corpus for features the D3D12 -> Vulkan layer may need (docs/d3d12_vulkan.md §8.2 #10, #14, #16).
2 2
3 python -I tools/feature_scan.py <work>/shaders [--out feature_scan.json] 3 python -I tools/feature_scan.py <work>/shaders [--out feature_scan.json]
4 4
@@ -7,9 +7,12 @@ Reads what the shaders stage of make_game.py leaves in <work>/shaders, and print
7- dxbc/index.json and the .dxbc files: the DXIL program kind of every shader (hull, domain and amplification 7- dxbc/index.json and the .dxbc files: the DXIL program kind of every shader (hull, domain and amplification
8 stages would show up here), the SFI0 feature flags (D3D_SHADER_REQUIRES_* from the Windows SDK's d3d12shader.h, 8 stages would show up here), the SFI0 feature flags (D3D_SHADER_REQUIRES_* from the Windows SDK's d3d12shader.h,
9 among them WAVE_MMA and SHADING_RATE), and the output-signature (OSG1) stream index of every element: stream 9 among them WAVE_MMA and SHADING_RATE), and the output-signature (OSG1) stream index of every element: stream
10 output to a stream other than 0 needs a geometry shader writing that stream. 10 output to a stream other than 0 needs a geometry shader writing that stream. The PSV0 resource bindings: structured
11 UAVs with a counter (append/consume buffers) and typed buffer SRVs/UAVs (#16).
11- dxbc/disasm/*.s (shader_disasm.py): the native RDNA2 instructions that mean wave MMA (v_mfma*, v_wmma*, 12- dxbc/disasm/*.s (shader_disasm.py): the native RDNA2 instructions that mean wave MMA (v_mfma*, v_wmma*,
12 v_smfmac*) or GDS / ordered-count traffic (the hardware path NGG stream output uses on RDNA2). 13 v_smfmac*) or GDS / ordered-count traffic (the hardware path NGG stream output uses on RDNA2). Typed buffer
14 accesses (#16): the MTBUF instruction formats, and for MUBUF where V# word 3 (the format) comes from, each checked
15 against the translator's typed-buffer table (rdna2spirv.Gen.FORMATS).
13- spirv/index.json (rdna2spirv.py): uses_code_base per stage. A graphics PSO can only need two code bases 16- spirv/index.json (rdna2spirv.py): uses_code_base per stage. A graphics PSO can only need two code bases
14 (§5.2) if two of its stages use one; this gives the per-stage counts. Which stages are paired in one PSO is in 17 (§5.2) if two of its stages use one; this gives the per-stage counts. Which stages are paired in one PSO is in
15 the executable, not in shaders.rpf. 18 the executable, not in shaders.rpf.
@@ -80,6 +83,61 @@ def streams(sig: bytes) -> set:
80 return {struct.unpack_from("<I", sig, first + 32 * i)[0] for i in range(count)} 83 return {struct.unpack_from("<I", sig, first + 32 * i)[0] for i in range(count)}
81 84
82 85
86# DXC include/dxc/DxilContainer/DxilPipelineStateValidation.h (PSVResourceType) and DxilConstants.h
87# (DXIL::ResourceKind), by value.
88PSV_RES_TYPES = ("Invalid", "Sampler", "CBV", "SRVTyped", "SRVRaw", "SRVStructured", "UAVTyped", "UAVRaw",
89 "UAVStructured", "UAVStructuredWithCounter")
90PSV_RES_KINDS = ("Invalid", "Texture1D", "Texture2D", "Texture2DMS", "Texture3D", "TextureCube", "Texture1DArray",
91 "Texture2DArray", "Texture2DMSArray", "TextureCubeArray", "TypedBuffer", "RawBuffer",
92 "StructuredBuffer", "CBuffer", "Sampler", "TBuffer", "RTAccelerationStructure", "FeedbackTexture2D",
93 "FeedbackTexture2DArray")
94
95
96def psv0_bindings(psv: bytes) -> list:
97 """(resource type, resource kind) of every PSV0 resource binding record.
98
99 The part is: u32 runtime-info size, the runtime info, u32 resource count and, when that is not 0, u32 record
100 size and the records. A record is PSVResourceBindInfo0 (type, space, lower and upper bound: 16 bytes) or
101 PSVResourceBindInfo1 (plus resource kind and flags: 24 bytes); a 16-byte record has kind "?". Raises ValueError
102 when the table does not fit in the part."""
103 if len(psv) < 4:
104 raise ValueError("PSV0 shorter than its runtime-info size")
105 pos = 4 + struct.unpack_from("<I", psv, 0)[0]
106 if pos + 4 > len(psv):
107 raise ValueError("PSV0 truncated before the resource count")
108 count = struct.unpack_from("<I", psv, pos)[0]
109 pos += 4
110 if not count:
111 return []
112 if pos + 4 > len(psv):
113 raise ValueError("PSV0 truncated before the record size")
114 size = struct.unpack_from("<I", psv, pos)[0]
115 pos += 4
116 if size < 16 or pos + size * count > len(psv):
117 raise ValueError("PSV0 resource records do not fit")
118 out = []
119 for i in range(count):
120 at = pos + i * size
121 t = struct.unpack_from("<I", psv, at)[0]
122 k = struct.unpack_from("<I", psv, at + 16)[0] if size >= 20 else None
123 out.append((PSV_RES_TYPES[t] if t < len(PSV_RES_TYPES) else f"type{t}",
124 "?" if k is None else PSV_RES_KINDS[k] if k < len(PSV_RES_KINDS) else f"kind{k}"))
125 return out
126
127
128# §8.2 #16: append/consume buffers are the structured UAVs with a counter; typed buffers are typed SRVs/UAVs of
129# kind TypedBuffer (a typed SRV/UAV of a texture kind is an image, not a buffer).
130WATCHED_BINDINGS = ("uav_with_counter", "typed_buffer_srv", "typed_buffer_uav")
131
132
133def watched_binding(res_type: str, kind: str):
134 if res_type == "UAVStructuredWithCounter":
135 return "uav_with_counter"
136 if kind == "TypedBuffer" and res_type in ("SRVTyped", "UAVTyped"):
137 return "typed_buffer_srv" if res_type == "SRVTyped" else "typed_buffer_uav"
138 return None
139
140
83def stage_name(row: dict) -> str: 141def stage_name(row: dict) -> str:
84 stage = row.get("stage") 142 stage = row.get("stage")
85 return stage if isinstance(stage, str) and stage else "?" 143 return stage if isinstance(stage, str) and stage else "?"
@@ -90,6 +148,8 @@ def scan_dxbc(dxbc_dir: str, index: list) -> dict:
90 flags = defaultdict(Counter) # flag -> stage -> shaders 148 flags = defaultdict(Counter) # flag -> stage -> shaders
91 gs_streams = Counter() 149 gs_streams = Counter()
92 non_zero_stream = Counter() # stage -> shaders with an output element on a stream other than 0 150 non_zero_stream = Counter() # stage -> shaders with an output element on a stream other than 0
151 records, shaders_with = Counter(), Counter() # PSV0: (type, kind) -> records; watched class -> shaders
152 psv_bad = 0
93 missing = 0 153 missing = 0
94 for e in index: 154 for e in index:
95 if not isinstance(e, dict): 155 if not isinstance(e, dict):
@@ -113,14 +173,33 @@ def scan_dxbc(dxbc_dir: str, index: list) -> dict:
113 for bit, name in SFI0_FLAGS.items(): 173 for bit, name in SFI0_FLAGS.items():
114 if mask & bit: 174 if mask & bit:
115 flags[name][stage] += 1 175 flags[name][stage] += 1
176 try:
177 binds = psv0_bindings(p["PSV0"]) if "PSV0" in p else None
178 except ValueError:
179 binds = None
180 if binds is None:
181 psv_bad += 1
182 else:
183 records.update(binds)
184 for cls in {watched_binding(t, k) for t, k in binds} - {None}:
185 shaders_with[cls] += 1
116 out = streams(p.get("OSG1", b"")) 186 out = streams(p.get("OSG1", b""))
117 if stage == "gs": 187 if stage == "gs":
118 gs_streams[len(out)] += 1 188 gs_streams[len(out)] += 1
119 if out - {0}: 189 if out - {0}:
120 non_zero_stream[stage] += 1 190 non_zero_stream[stage] += 1
191 by_type = Counter()
192 for (t, _), n in records.items():
193 by_type[t] += n
121 return {"stages": {s: stages.get(s, 0) for s in ALL_STAGES} | {k: v for k, v in stages.items() if k not in ALL_STAGES}, 194 return {"stages": {s: stages.get(s, 0) for s in ALL_STAGES} | {k: v for k, v in stages.items() if k not in ALL_STAGES},
122 "sfi0": {n: dict(flags[n]) for n in sorted(flags)}, 195 "sfi0": {n: dict(flags[n]) for n in sorted(flags)},
123 "gs_output_stream_count": dict(gs_streams), "output_on_stream_other_than_0": dict(non_zero_stream), 196 "gs_output_stream_count": dict(gs_streams), "output_on_stream_other_than_0": dict(non_zero_stream),
197 "psv0": {"records": sum(records.values()),
198 "by_type": dict(by_type),
199 "shaders": {c: shaders_with.get(c, 0) for c in WATCHED_BINDINGS},
200 "records_of": {c: sum(n for (t, k), n in records.items() if watched_binding(t, k) == c)
201 for c in WATCHED_BINDINGS},
202 "unreadable": psv_bad},
124 "unreadable": missing} 203 "unreadable": missing}
125 204
126 205
@@ -251,6 +330,139 @@ def scan_disasm(disasm_dir: str, stage_of: dict) -> dict:
251 }} 330 }}
252 331
253 332
333# Scalar ops whose first operand is a source, not an SGPR they write.
334NO_SDST = ("s_cmp", "s_bitcmp", "s_cbranch", "s_branch", "s_waitcnt", "s_endpgm", "s_store", "s_buffer_store",
335 "s_scratch_store", "s_setpc", "s_sendmsg", "s_nop", "s_barrier", "s_dcache", "s_icache", "s_gl1_inv",
336 "s_setprio", "s_sleep", "s_ttrace", "s_set_gpr_idx", "s_setreg", "s_inst_prefetch", "s_round_mode",
337 "s_denorm_mode", "s_clause", "s_trap", "s_wakeup", "s_code_end", "s_atc_probe", "s_setkill", "s_incperflevel",
338 "s_decperflevel", "s_version")
339BRANCH_OPS = frozenset(("s_branch", "s_cbranch_scc0", "s_cbranch_scc1", "s_cbranch_vccz", "s_cbranch_vccnz",
340 "s_cbranch_execz", "s_cbranch_execnz"))
341TYPED_MUBUF = re.compile(r"^buffer_(load|store)_format_(d16_)?(x|xy|xyz|xyzw)$")
342TYPED_MTBUF = re.compile(r"^tbuffer_(load|store)_format_(d16_)?(x|xy|xyz|xyzw)$")
343
344
345def translator_formats():
346 """(codes the translator models, GFX10 code -> format name), read from rdna2spirv itself so the scan follows the
347 table as it changes. Modelled: the typed-buffer table and INVALID (0), an unbound descriptor, which reads 0 on the
348 hardware and in the translator."""
349 import rdna2spirv
350 return frozenset(rdna2spirv.Gen.FORMATS) | {0}, {c: n.replace("GFX10_FORMAT_", "") for c, n in
351 rdna2spirv.GFX10_FORMATS.items()}
352
353
354def sgpr_writes(ins: dict) -> range:
355 """The SGPRs an instruction writes (as far as a V# word can be written: scalar destinations, v_readlane and
356 v_readfirstlane, the SGPR mask of a VOP3 compare and the carry of a VOP3b add)."""
357 op, args = ins["op"], ins["args"]
358 dst = None
359 if op.startswith("s_") and not op.startswith(NO_SDST):
360 dst = args[0] if args else None
361 elif op.startswith(("v_readlane", "v_readfirstlane")) or (op.startswith("v_cmp") and not op.startswith("v_cmpx")
362 and op.endswith("_e64")):
363 dst = args[0] if args else None
364 elif op.startswith("v_") and len(args) > 1 and ("_co_" in op or op.startswith("v_div_scale")):
365 dst = args[1]
366 if dst and dst.get("k") == "sgpr":
367 return range(dst["r"], dst["r"] + dst.get("n", 1))
368 return range(0)
369
370
371def branch_target(ins: dict):
372 """Byte pc a branch goes to (simm16 dwords after the branch), or None without an encoding."""
373 imm = next((x for x in ins["args"] if x.get("k") == "imm"), None)
374 if imm is None or not ins.get("enc"):
375 return None
376 v = imm["v"] & 0xFFFF
377 return ins["pc"] + len(ins["enc"]) // 2 + 4 * (v - 0x10000 if v & 0x8000 else v)
378
379
380def typed_buffer_ops(insns: list, table: frozenset, names: dict) -> Counter:
381 """Count the typed buffer accesses of one listing (§8.2 #16).
382
383 MTBUF (tbuffer_*) carries its format in the instruction; LLVM leaves `format:` out for GFX10's default, 8_UNORM.
384 MUBUF (buffer_*_format_*) takes it from V# word 3 bits 18:12, and the result says where that word comes from in the
385 basic block of the access (blocks start at branch targets and after branches, as rdna2spirv.translate splits
386 them): an s_mov_b32 literal (the only form the translator folds, so the format is known when translating), a
387 scalar load (a descriptor from memory), or any other instruction (computed). A word 3 not written in the block is
388 "earlier_" + the class of the last write before it in listing order, or "shader_input" when nothing before it
389 writes the register (a user or system SGPR: the root signature's descriptor).
390
391 Keys: ("mtbuf", load|store, format), ("mubuf", load|store, class) and, for a literal word 3 (in the block or
392 earlier), ("mubuf_literal", load|store, format). A format the translator's table lacks gets a "!" in front."""
393 leaders = {insns[0]["pc"]} if insns else set()
394 for ins in insns:
395 if ins["op"] in BRANCH_OPS:
396 t = branch_target(ins)
397 if t is not None:
398 leaders.add(t)
399 if ins.get("enc"):
400 leaders.add(ins["pc"] + len(ins["enc"]) // 2)
401 out = Counter()
402 block, last = {}, {} # SGPR -> (class, literal or None): written in this block / last write so far
403 for ins in insns:
404 if ins["pc"] in leaders:
405 block = {}
406 op = ins["op"]
407 m = TYPED_MTBUF.match(op) or TYPED_MUBUF.match(op)
408 if m:
409 kind = m.group(1)
410 if op.startswith("t"):
411 fm = next((x for x in ins["mods"] if x.startswith("format:")), "format:[BUF_FMT_8_UNORM]")
412 name = fm.split("BUF_FMT_")[-1].rstrip("]")
413 code = next((c for c, n in names.items() if n == name), None)
414 out[("mtbuf", kind, ("" if code in table else "!") + name)] += 1
415 elif len(ins["args"]) > 2 and ins["args"][2].get("k") == "sgpr":
416 w3 = ins["args"][2]["r"] + 3
417 if w3 in block:
418 cls, lit = block[w3]
419 elif w3 in last:
420 cls, lit = "earlier_" + last[w3][0], last[w3][1]
421 else:
422 cls, lit = "shader_input", None
423 out[("mubuf", kind, cls)] += 1
424 if lit is not None:
425 code = (lit >> 12) & 0x7F
426 out[("mubuf_literal", kind, ("" if code in table else "!") + names.get(code, f"code{code}"))] += 1
427 regs = sgpr_writes(ins)
428 if regs:
429 if op == "s_mov_b32" and len(ins["args"]) > 1 and ins["args"][1].get("k") == "imm":
430 state = ("literal", ins["args"][1]["v"] & 0xFFFFFFFF)
431 elif op.startswith(("s_load", "s_buffer_load")):
432 state = ("memory", None)
433 else:
434 state = ("computed", None)
435 for r in regs:
436 block[r] = last[r] = state
437 return out
438
439
440def scan_typed_buffers(disasm_dir: str, stage_of: dict) -> dict:
441 """§8.2 #16 over every listing: typed buffer access counts (typed_buffer_ops) summed, and shaders per stage."""
442 import shader_ir
443 table, names = translator_formats()
444 total, shaders = Counter(), defaultdict(Counter)
445 for fn in sorted(os.listdir(disasm_dir)):
446 if not fn.endswith(".s"):
447 continue
448 path = os.path.join(disasm_dir, fn)
449 with open(path, encoding="utf-8", errors="replace") as f:
450 if "_format_" not in f.read(): # no typed buffer op: skip the slower full parse
451 continue
452 stage = stage_of.get(fn[:-2], "?")
453 c = typed_buffer_ops(shader_ir.parse_file(path)["insns"], table, names)
454 total.update(c)
455 for what in {k[0] for k in c}:
456 shaders[what][stage] += 1
457 if any(k[0] == "mubuf" and k[2] not in ("literal", "earlier_literal") for k in c):
458 shaders["mubuf_runtime_format"][stage] += 1
459 group = lambda what: {f"{k[1]} {k[2].lstrip('!')}": n for k, n in sorted(total.items()) if k[0] == what}
460 return {"mtbuf": group("mtbuf"), "mubuf_word3": group("mubuf"), "mubuf_literal_formats": group("mubuf_literal"),
461 "not_in_translator": {f"{k[0]} {k[1]} {k[2][1:]}": n for k, n in sorted(total.items())
462 if k[0] != "mubuf" and k[2].startswith("!")},
463 "shaders": {w: dict(s) for w, s in sorted(shaders.items())}}
464
465
254def scan_spirv(spirv_index: str) -> dict: 466def scan_spirv(spirv_index: str) -> dict:
255 with open(spirv_index, encoding="utf-8") as f: 467 with open(spirv_index, encoding="utf-8") as f:
256 idx = json.load(f) 468 idx = json.load(f)
@@ -336,6 +548,7 @@ def main() -> int:
336 disasm = os.path.join(dxbc_dir, "disasm") 548 disasm = os.path.join(dxbc_dir, "disasm")
337 if os.path.isdir(disasm): 549 if os.path.isdir(disasm):
338 result["disasm"] = scan_disasm(disasm, stage_of) 550 result["disasm"] = scan_disasm(disasm, stage_of)
551 result["typed_buffers"] = scan_typed_buffers(disasm, stage_of)
339 spirv = os.path.join(a.shaders, "spirv", "index.json") 552 spirv = os.path.join(a.shaders, "spirv", "index.json")
340 if os.path.isfile(spirv): 553 if os.path.isfile(spirv):
341 try: 554 try:
@@ -352,6 +565,10 @@ def main() -> int:
352 print("SFI0, every flag set anywhere:", {n: sum(v.values()) for n, v in d["sfi0"].items()}) 565 print("SFI0, every flag set anywhere:", {n: sum(v.values()) for n, v in d["sfi0"].items()})
353 print("GS output-signature stream counts:", d["gs_output_stream_count"], 566 print("GS output-signature stream counts:", d["gs_output_stream_count"],
354 "| shaders with an output on a stream other than 0:", d["output_on_stream_other_than_0"] or 0) 567 "| shaders with an output on a stream other than 0:", d["output_on_stream_other_than_0"] or 0)
568 pv = d["psv0"]
569 print(f"PSV0 bindings: {pv['records']} records | shaders with "
570 + ", ".join(f"{c} {pv['shaders'][c]} ({pv['records_of'][c]} records)" for c in WATCHED_BINDINGS)
571 + (f" | {pv['unreadable']} unreadable PSV0" if pv["unreadable"] else ""))
355 if "disasm" in result: 572 if "disasm" in result:
356 s = result["disasm"] 573 s = result["disasm"]
357 print(f"disasm: {s['files']} files | wave MMA shaders {s['wave_mma_shaders'] or 0} | ordered-count/GWS shaders " 574 print(f"disasm: {s['files']} files | wave MMA shaders {s['wave_mma_shaders'] or 0} | ordered-count/GWS shaders "
@@ -362,6 +579,12 @@ def main() -> int:
362 f"(imm {vp['immediate']}, const_reg {vp['const_reg']}, unresolved {vp['unresolved']}) | " 579 f"(imm {vp['immediate']}, const_reg {vp['const_reg']}, unresolved {vp['unresolved']}) | "
363 f"selectors 8-11: {vp['sign_extend_8_11_shaders']} shaders / {vp['sign_extend_8_11_insns']} insns | " 580 f"selectors 8-11: {vp['sign_extend_8_11_shaders']} shaders / {vp['sign_extend_8_11_insns']} insns | "
364 f"bytes {vp['selector_classes']}") 581 f"bytes {vp['selector_classes']}")
582 tb = result["typed_buffers"]
583 print("typed buffers, MTBUF formats (instruction):", tb["mtbuf"] or 0)
584 print("typed buffers, MUBUF V# word 3 source:", tb["mubuf_word3"] or 0, "| literal formats:",
585 tb["mubuf_literal_formats"] or 0)
586 print("typed buffers, formats the translator's table lacks:", tb["not_in_translator"] or 0,
587 "| shaders:", tb["shaders"] or 0)
365 else: 588 else:
366 print("disasm: not there yet (run the shaders stage)") 589 print("disasm: not there yet (run the shaders stage)")
367 if "spirv" in result: 590 if "spirv" in result:
@@ -375,7 +598,7 @@ def main() -> int:
375 folder = os.path.dirname(a.out) # --out into a folder that does not exist yet, as awc_manifest.py does 598 folder = os.path.dirname(a.out) # --out into a folder that does not exist yet, as awc_manifest.py does
376 if folder: 599 if folder:
377 os.makedirs(folder, exist_ok=True) 600 os.makedirs(folder, exist_ok=True)
378 with open(a.out, "w", encoding="utf-8") as f: 601 with open(a.out, "w", encoding="utf-8", newline="\n") as f:
379 json.dump(result, f, indent=1) 602 json.dump(result, f, indent=1)
380 return 0 603 return 0
381 604
diff --git a/tools/fma_mix_probe.py b/tools/fma_mix_probe.py
index 23cf1f8d6..7a77fe486 100644
--- a/tools/fma_mix_probe.py
+++ b/tools/fma_mix_probe.py
@@ -179,7 +179,7 @@ def verdict(results):
179def _translate(work, name, text, fssm=None): 179def _translate(work, name, text, fssm=None):
180 os.makedirs(os.path.join(work, "disasm"), exist_ok=True) 180 os.makedirs(os.path.join(work, "disasm"), exist_ok=True)
181 src = os.path.join(work, "disasm", name + ".s") 181 src = os.path.join(work, "disasm", name + ".s")
182 with open(src, "w", encoding="utf-8") as f: 182 with open(src, "w", encoding="utf-8", newline="\n") as f:
183 f.write(text) 183 f.write(text)
184 with open(os.path.join(work, name + ".dxbc"), "wb") as f: 184 with open(os.path.join(work, name + ".dxbc"), "wb") as f:
185 f.write(STUB_DXBC) 185 f.write(STUB_DXBC)
@@ -264,7 +264,7 @@ def run_vulkan(build, cases=CASES):
264 with tempfile.TemporaryDirectory(prefix="fma_mix_probe_") as work: 264 with tempfile.TemporaryDirectory(prefix="fma_mix_probe_") as work:
265 text = translate_cs(work, cases) 265 text = translate_cs(work, cases)
266 sa, sv = os.path.join(work, "cs.spvasm"), os.path.join(work, "cs.spv") 266 sa, sv = os.path.join(work, "cs.spvasm"), os.path.join(work, "cs.spv")
267 with open(sa, "w", encoding="utf-8") as f: 267 with open(sa, "w", encoding="utf-8", newline="\n") as f:
268 f.write(text) 268 f.write(text)
269 try: 269 try:
270 r = subprocess.run(["spirv-as", sa, "-o", sv, "--target-env", "vulkan1.2"], capture_output=True, text=True) 270 r = subprocess.run(["spirv-as", sa, "-o", sv, "--target-env", "vulkan1.2"], capture_output=True, text=True)
diff --git a/tools/fspx_unpack.py b/tools/fspx_unpack.py
index ea79e8001..3d002d0d6 100644
--- a/tools/fspx_unpack.py
+++ b/tools/fspx_unpack.py
@@ -178,6 +178,7 @@ def main(argv=None) -> int:
178 disasm = shader_disasm 178 disasm = shader_disasm
179 os.makedirs(os.path.join(a.out, "disasm"), exist_ok=True) 179 os.makedirs(os.path.join(a.out, "disasm"), exist_ok=True)
180 index, bad = [], 0 180 index, bad = [], 0
181 used_names = set()
181 for path in a.files: 182 for path in a.files:
182 with open(path, "rb") as f: 183 with open(path, "rb") as f:
183 data = f.read() 184 data = f.read()
@@ -197,29 +198,39 @@ def main(argv=None) -> int:
197 print(f"{name}: FSPX status {status}", file=sys.stderr) 198 print(f"{name}: FSPX status {status}", file=sys.stderr)
198 bad += 1 199 bad += 1
199 continue 200 continue
201 base_name = name
202 number = 1
203 while name.casefold() in used_names:
204 number += 1
205 name = f"{base_name}_{number}"
206 used_names.add(name.casefold())
200 meta, blob = got 207 meta, blob = got
201 stage = psv_stage(dxbc_parts(container)) if container else None 208 stage = psv_stage(dxbc_parts(container)) if container else None
202 meta["source"] = {"file": os.path.basename(path), "offset": off} 209 meta["source"] = {"file": os.path.basename(path), "offset": off}
203 entry = {"file": name + ".dxbc", "stage": "cs" if stage in (None, STAGE_COMPUTE) else f"psv{stage}", 210 entry = {"file": name + ".dxbc", "stage": "cs" if stage in (None, STAGE_COMPUTE) else f"psv{stage}",
204 "source_offset": off, "threads": meta["threads"], "wave32": meta["wave32"]} 211 "source_offset": off}
212 if "threads" in meta:
213 entry["threads"] = meta["threads"]
214 if "wave32" in meta:
215 entry["wave32"] = meta["wave32"]
205 if container: 216 if container:
206 with open(os.path.join(a.out, name + ".dxbc"), "wb") as f: 217 with open(os.path.join(a.out, name + ".dxbc"), "wb") as f:
207 f.write(container) 218 f.write(container)
208 with open(os.path.join(a.out, "fspx", name + ".code"), "wb") as f: 219 with open(os.path.join(a.out, "fspx", name + ".code"), "wb") as f:
209 f.write(blob[6]) 220 f.write(blob[6])
210 with open(os.path.join(a.out, "fspx", name + ".json"), "w", encoding="utf-8") as f: 221 with open(os.path.join(a.out, "fspx", name + ".json"), "w", encoding="utf-8", newline="\n") as f:
211 json.dump(meta, f, indent=1) 222 json.dump(meta, f, indent=1)
212 if disasm and meta["code"]["end"]: 223 if disasm and meta["code"]["end"]:
213 start, end = meta["code"]["start"], meta["code"]["end"] 224 start, end = meta["code"]["start"], meta["code"]["end"]
214 asm, invalid, err = disasm.disasm(blob[6][start:end], a.mcpu) 225 asm, invalid, err = disasm.disasm(blob[6][start:end], a.mcpu)
215 entry["invalid_words"] = invalid 226 entry["invalid_words"] = invalid
216 with open(os.path.join(a.out, "disasm", name + ".s"), "w", encoding="utf-8") as f: 227 with open(os.path.join(a.out, "disasm", name + ".s"), "w", encoding="utf-8", newline="\n") as f:
217 f.write(f"; {name} code 0x{start:x}..0x{end:x} (fspx), {a.mcpu}, {invalid} invalid words\n") 228 f.write(f"; {name} code 0x{start:x}..0x{end:x} (fspx), {a.mcpu}, {invalid} invalid words\n")
218 f.write(asm) 229 f.write(asm)
219 if err.strip(): 230 if err.strip():
220 f.write("\n; --- llvm-mc messages ---\n; " + err.strip().replace("\n", "\n; ") + "\n") 231 f.write("\n; --- llvm-mc messages ---\n; " + err.strip().replace("\n", "\n; ") + "\n")
221 index.append(entry) 232 index.append(entry)
222 with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8") as f: 233 with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8", newline="\n") as f:
223 json.dump(index, f, indent=1) 234 json.dump(index, f, indent=1)
224 print(f"{len(index)} FSPX program(s) unpacked to {a.out}" + (f", {bad} input(s) failed" if bad else "")) 235 print(f"{len(index)} FSPX program(s) unpacked to {a.out}" + (f", {bad} input(s) failed" if bad else ""))
225 return 1 if bad else 0 236 return 1 if bad else 0
diff --git a/tools/fssm_unpack.py b/tools/fssm_unpack.py
index a463465b9..1a462144c 100644
--- a/tools/fssm_unpack.py
+++ b/tools/fssm_unpack.py
@@ -153,7 +153,7 @@ def main(argv=None) -> int:
153 "game version.", file=sys.stderr) 153 "game version.", file=sys.stderr)
154 return 1 154 return 1
155 tmp = os.path.join(src, "fssm_index.json.tmp") # written last and renamed in, so a stopped run leaves none 155 tmp = os.path.join(src, "fssm_index.json.tmp") # written last and renamed in, so a stopped run leaves none
156 with open(tmp, "w", encoding="utf-8") as f: 156 with open(tmp, "w", encoding="utf-8", newline="\n") as f:
157 json.dump(rows, f) 157 json.dump(rows, f)
158 f.flush() 158 f.flush()
159 os.fsync(f.fileno()) 159 os.fsync(f.fileno())
diff --git a/tools/gamedata_graph.py b/tools/gamedata_graph.py
index ec1126ade..507aac4a9 100644
--- a/tools/gamedata_graph.py
+++ b/tools/gamedata_graph.py
@@ -624,7 +624,7 @@ def main() -> int:
624 print_summary(graph) 624 print_summary(graph)
625 if args.json: 625 if args.json:
626 try: 626 try:
627 with open(args.json, "w", encoding="utf-8") as f: 627 with open(args.json, "w", encoding="utf-8", newline="\n") as f:
628 json.dump(graph, f, indent=1) 628 json.dump(graph, f, indent=1)
629 except OSError as exc: 629 except OSError as exc:
630 print(f"cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr) 630 print(f"cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr)
diff --git a/tools/gamedata_index.py b/tools/gamedata_index.py
index 732ff0d30..5464cdfe4 100644
--- a/tools/gamedata_index.py
+++ b/tools/gamedata_index.py
@@ -41,6 +41,10 @@ XML_CLOSE_TAIL = re.compile(rb"</([A-Za-z_][\w.:-]*)>\s*$")
41# Tag-like text inside these cannot open or close an element. 41# Tag-like text inside these cannot open or close an element.
42XML_NON_TAG = re.compile(rb"<!--.*?-->|<!\[CDATA\[.*?\]\]>|<\?.*?\?>", re.S) 42XML_NON_TAG = re.compile(rb"<!--.*?-->|<!\[CDATA\[.*?\]\]>|<\?.*?\?>", re.S)
43MAGIC = {b"MHIU": "MHIU", b"PAMH": "PAMH", b"SPS1Z": "SPS1Z", b"RBF0": "RBF0", b"PSIN": "PSIN"} 43MAGIC = {b"MHIU": "MHIU", b"PAMH": "PAMH", b"SPS1Z": "SPS1Z", b"RBF0": "RBF0", b"PSIN": "PSIN"}
44# A resource whose page directory starts the stream carries "0DRP" at +16 (docs/animation.md, "0DRP page marker").
45# Its first 4 KiB can be over 95% printable, so without this check such a stream reads as text, and as XML when it
46# holds a "<": data.rpf has 337 of them and no XML at all (docs/gamedata.md, "Relationship to data.rpf").
47PAGE_MARKER, PAGE_MARKER_AT = b"0DRP", 16
44 48
45 49
46def printable(data: bytes) -> float: 50def printable(data: bytes) -> float:
@@ -123,6 +127,8 @@ def stream_kind(data: bytes, row: dict) -> str:
123 for magic in MAGIC: 127 for magic in MAGIC:
124 if data.startswith(magic): 128 if data.startswith(magic):
125 return "other" 129 return "other"
130 if data[PAGE_MARKER_AT:PAGE_MARKER_AT + len(PAGE_MARKER)] == PAGE_MARKER:
131 return "other"
126 if printable(data) > 0.95: 132 if printable(data) > 0.95:
127 return "text" 133 return "text"
128 return "binary" 134 return "binary"
@@ -132,6 +138,8 @@ def magic_name(data: bytes) -> str:
132 for magic, name in MAGIC.items(): 138 for magic, name in MAGIC.items():
133 if data.startswith(magic): 139 if data.startswith(magic):
134 return name 140 return name
141 if data[PAGE_MARKER_AT:PAGE_MARKER_AT + len(PAGE_MARKER)] == PAGE_MARKER:
142 return PAGE_MARKER.decode()
135 return "" 143 return ""
136 144
137 145
@@ -435,7 +443,7 @@ def main() -> int:
435 write_csv(a.csv, rows) 443 write_csv(a.csv, rows)
436 if a.json: 444 if a.json:
437 _make_parent(a.json) 445 _make_parent(a.json)
438 with open(a.json, "w", encoding="utf-8") as f: 446 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
439 json.dump({"summary": summary, "rows": rows}, f, indent=1) 447 json.dump({"summary": summary, "rows": rows}, f, indent=1)
440 448
441 print(f'{summary["streams"]} streams, {summary["stored"]:,} stored, ' 449 print(f'{summary["streams"]} streams, {summary["stored"]:,} stored, '
diff --git a/tools/gamedata_maps.py b/tools/gamedata_maps.py
index d3d465f0e..56fa68ca0 100644
--- a/tools/gamedata_maps.py
+++ b/tools/gamedata_maps.py
@@ -385,7 +385,7 @@ def main() -> int:
385 if census: 385 if census:
386 out["pamh_census"] = census 386 out["pamh_census"] = census
387 try: 387 try:
388 with open(a.json, "w", encoding="utf-8") as f: 388 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
389 json.dump(out, f, indent=1) 389 json.dump(out, f, indent=1)
390 except OSError as e: 390 except OSError as e:
391 print(f"error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) 391 print(f"error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr)
diff --git a/tools/gamedata_xml.py b/tools/gamedata_xml.py
index 02cea8dee..e869dc234 100644
--- a/tools/gamedata_xml.py
+++ b/tools/gamedata_xml.py
@@ -635,7 +635,7 @@ def main() -> int:
635 if args.json: 635 if args.json:
636 public_rows = [{key: value for key, value in row.items() if key != "_scan"} for row in rows] 636 public_rows = [{key: value for key, value in row.items() if key != "_scan"} for row in rows]
637 _make_parent(args.json) 637 _make_parent(args.json)
638 with open(args.json, "w", encoding="utf-8") as f: 638 with open(args.json, "w", encoding="utf-8", newline="\n") as f:
639 json.dump({"summary": summary, "roots": agg["roots"], "rows": public_rows}, f, indent=1) 639 json.dump({"summary": summary, "roots": agg["roots"], "rows": public_rows}, f, indent=1)
640 print("wrote", args.json) 640 print("wrote", args.json)
641 return 0 if clean else 1 641 return 0 if clean else 1
diff --git a/tools/glb_writer.py b/tools/glb_writer.py
index 0fa942c51..c6900bfef 100644
--- a/tools/glb_writer.py
+++ b/tools/glb_writer.py
@@ -453,10 +453,19 @@ def parse_obj(
453 first_vertex.setdefault(corner[0], vertex) 453 first_vertex.setdefault(corner[0], vertex)
454 for corner, vertex in builder["vert_map"].items() 454 for corner, vertex in builder["vert_map"].items()
455 ] 455 ]
456 computed = _compute_smooth_normals(positions, (normal_vertices[i] for i in indices)) 456 raw_normals = builder["normals"]
457 index_iter = iter(indices)
458 # Fully explicit triangles should not smooth neighboring generated normals.
459 normal_indices = (
460 normal_vertices[i]
461 for a, b, c in zip(index_iter, index_iter, index_iter)
462 if None in (raw_normals[a], raw_normals[b], raw_normals[c])
463 for i in (a, b, c)
464 )
465 computed = _compute_smooth_normals(positions, normal_indices)
457 normals = [ 466 normals = [
458 normal if normal is not None else computed[normal_vertex] 467 normal if normal is not None else computed[normal_vertex]
459 for normal, normal_vertex in zip(builder["normals"], normal_vertices) 468 for normal, normal_vertex in zip(raw_normals, normal_vertices)
460 ] 469 ]
461 else: 470 else:
462 normals = builder["normals"] 471 normals = builder["normals"]
diff --git a/tools/hashdict.py b/tools/hashdict.py
index cc8da2ace..f75fee68f 100644
--- a/tools/hashdict.py
+++ b/tools/hashdict.py
@@ -6,6 +6,7 @@ When multiple names share a hash, the dictionary keeps the lexicographically fir
6 6
7Usage: 7Usage:
8 python -I hashdict.py <carve dir> --out hashes.json [--archives a,b] [--extra f1 f2 ...] [--min 3] 8 python -I hashdict.py <carve dir> --out hashes.json [--archives a,b] [--extra f1 f2 ...] [--min 3]
9 <carve dir> holds one folder per archive (<work>/carve), or is one archive's folder (<work>/carve/common).
9 python -I hashdict.py --lookup <hashes.json> 0x28cca8df ... 10 python -I hashdict.py --lookup <hashes.json> 0x28cca8df ...
10""" 11"""
11import argparse 12import argparse
@@ -91,11 +92,17 @@ def main():
91 what = "is not a folder" if os.path.exists(a.carve) else "does not exist" 92 what = "is not a folder" if os.path.exists(a.carve) else "does not exist"
92 print(f"ERROR: the carve folder {a.carve} {what}", file=sys.stderr) 93 print(f"ERROR: the carve folder {a.carve} {what}", file=sys.stderr)
93 return 2 94 return 2
95 # A folder with its own index.json is one archive's carve (<work>\carve\common, the folder the gamedata_*
96 # tools take): harvest it as that archive. Otherwise each subfolder with an index.json is one archive.
97 if os.path.isfile(os.path.join(a.carve, "index.json")):
98 archives = [(os.path.basename(os.path.normpath(os.path.abspath(a.carve))), a.carve)]
99 else:
100 archives = [(d, os.path.join(a.carve, d)) for d in sorted(os.listdir(a.carve))]
94 # The dictionary is written after the harvest: an --out naming one of the inputs would replace it. 101 # The dictionary is written after the harvest: an --out naming one of the inputs would replace it.
95 # samefile also catches a case-only difference on Windows and macOS's default volume. 102 # samefile also catches a case-only difference on Windows and macOS's default volume.
96 if os.path.exists(a.out): 103 if os.path.exists(a.out):
97 inputs = [x for x in a.extra if os.path.isfile(x)] 104 inputs = [x for x in a.extra if os.path.isfile(x)]
98 inputs += [os.path.join(a.carve, d, "index.json") for d in os.listdir(a.carve)] 105 inputs += [os.path.join(d, "index.json") for _, d in archives]
99 for x in inputs: 106 for x in inputs:
100 try: 107 try:
101 same = os.path.isfile(x) and os.path.samefile(a.out, x) 108 same = os.path.isfile(x) and os.path.samefile(a.out, x)
@@ -108,8 +115,8 @@ def main():
108 strings = set() 115 strings = set()
109 full = set(a.archives.split(",")) 116 full = set(a.archives.split(","))
110 missing = [] # carved blobs an index.json lists that can't be read: skipped, reported 117 missing = [] # carved blobs an index.json lists that can't be read: skipped, reported
111 for arch in sorted(os.listdir(a.carve)): 118 for arch, arch_dir in archives:
112 p = os.path.join(a.carve, arch, "index.json") 119 p = os.path.join(arch_dir, "index.json")
113 if not os.path.isfile(p): 120 if not os.path.isfile(p):
114 continue 121 continue
115 try: 122 try:
@@ -126,7 +133,7 @@ def main():
126 continue 133 continue
127 meta = r["head"].startswith("5053494e") or r["head"].startswith("52424630") 134 meta = r["head"].startswith("5053494e") or r["head"].startswith("52424630")
128 if arch in full or meta: 135 if arch in full or meta:
129 blob = os.path.join(a.carve, arch, f"{r['off']:012x}.bin") 136 blob = os.path.join(arch_dir, f"{r['off']:012x}.bin")
130 try: 137 try:
131 with open(blob, "rb") as f: 138 with open(blob, "rb") as f:
132 data = f.read() 139 data = f.read()
@@ -152,7 +159,7 @@ def main():
152 # Other tools create the output parent too: a long harvest must not be lost to a missing folder. 159 # Other tools create the output parent too: a long harvest must not be lost to a missing folder.
153 try: 160 try:
154 os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) 161 os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
155 with open(a.out, "w", encoding="utf-8") as f: 162 with open(a.out, "w", encoding="utf-8", newline="\n") as f:
156 json.dump(d, f) 163 json.dump(d, f)
157 except OSError as e: 164 except OSError as e:
158 print(f"ERROR: cannot write {a.out}: {e}", file=sys.stderr) 165 print(f"ERROR: cannot write {a.out}: {e}", file=sys.stderr)
diff --git a/tools/hw_oracle/runner.py b/tools/hw_oracle/runner.py
index bd19f0667..a89f42817 100644
--- a/tools/hw_oracle/runner.py
+++ b/tools/hw_oracle/runner.py
@@ -136,7 +136,7 @@ def build_command(kind, cc, src, out, workdir):
136 installer = os.path.join(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"), 136 installer = os.path.join(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"),
137 "Microsoft Visual Studio", "Installer") 137 "Microsoft Visual Studio", "Installer")
138 script = os.path.join(workdir, "build_hw_oracle.cmd") 138 script = os.path.join(workdir, "build_hw_oracle.cmd")
139 with open(script, "w", encoding="ascii") as f: 139 with open(script, "w", encoding="ascii", newline="\n") as f:
140 f.write(f'@echo off\r\nset "PATH={installer};%PATH%"\r\ncall "{cc}" >nul || exit /b 1\r\n' 140 f.write(f'@echo off\r\nset "PATH={installer};%PATH%"\r\ncall "{cc}" >nul || exit /b 1\r\n'
141 + subprocess.list2cmdline(cl) + "\r\n") 141 + subprocess.list2cmdline(cl) + "\r\n")
142 return ["cmd.exe", "/d", "/c", script] 142 return ["cmd.exe", "/d", "/c", script]
diff --git a/tools/image_fuzz.py b/tools/image_fuzz.py
index 2fb857732..709ffa595 100644
--- a/tools/image_fuzz.py
+++ b/tools/image_fuzz.py
@@ -88,7 +88,7 @@ def assemble(asm: str, name: str, work: str) -> None:
88 if not line.lstrip().startswith(".")) 88 if not line.lstrip().startswith("."))
89 disasm = os.path.join(work, "disasm") 89 disasm = os.path.join(work, "disasm")
90 os.makedirs(disasm, exist_ok=True) 90 os.makedirs(disasm, exist_ok=True)
91 with open(os.path.join(disasm, name + ".s"), "w", encoding="utf-8") as f: 91 with open(os.path.join(disasm, name + ".s"), "w", encoding="utf-8", newline="\n") as f:
92 f.write(f"; {name} generated by tools/image_fuzz.py\n{code}") 92 f.write(f"; {name} generated by tools/image_fuzz.py\n{code}")
93 with open(os.path.join(work, name + ".dxbc"), "wb") as f: 93 with open(os.path.join(work, name + ".dxbc"), "wb") as f:
94 f.write(bytes(32)) # chunk count 0: no signatures, the stage comes from the name 94 f.write(bytes(32)) # chunk count 0: no signatures, the stage comes from the name
@@ -268,7 +268,7 @@ def run_case(fmt_name, width, height, rng, work, build, keep, show, dmask=0xf, d
268 with open(texels_path, "wb") as f: 268 with open(texels_path, "wb") as f:
269 f.write(texels) 269 f.write(texels)
270 spec_path = os.path.join(work, "spec.txt") 270 spec_path = os.path.join(work, "spec.txt")
271 with open(spec_path, "w", encoding="utf-8") as f: 271 with open(spec_path, "w", encoding="utf-8", newline="\n") as f:
272 f.write(f"width={width}\nheight={height}\nformat={vk_format}\ntexels={texels_path}\n" 272 f.write(f"width={width}\nheight={height}\nformat={vk_format}\ntexels={texels_path}\n"
273 f"tsharp={','.join(hex(w) for w in tsharp)}\n") 273 f"tsharp={','.join(hex(w) for w in tsharp)}\n")
274 out_path = os.path.join(work, "out.raw") 274 out_path = os.path.join(work, "out.raw")
diff --git a/tools/imhex/psin.hexpat b/tools/imhex/psin.hexpat
new file mode 100644
index 000000000..c3dc014d9
--- /dev/null
+++ b/tools/imhex/psin.hexpat
@@ -0,0 +1,193 @@
1// ImHex pattern for a PSIN metadata container (docs/psin.md; tools/psin_index.py and tools/psin_data.py read it).
2//
3// Layout, as measured in docs/psin.md:
4// 0x00 "PSIN"
5// 0x04 big-endian absolute offset of the first section
6// 0x08 instance-data block table: rows of {u32 block type, u32 data size, aa x 8}, ended by "pppppppp" 8 bytes
7// short of a 16-byte boundary. The blocks follow in table order, each padded to 16 bytes, numbered from 1;
8// the last one ends at the first section. Their contents are shown as raw bytes: decoding them needs the
9// schema walk that psin_data.py does.
10// sections from the first-section offset to EOF: ASCII tag, big-endian total size (header included)
11// LSCH struct headers (32 bytes) then all members (16 bytes); the header count is not stored, it is the one
12// count whose headers and members fill the payload exactly
13// LENM enum headers (24 bytes) then all values (16 bytes); same rule
14// LSNS u32 block count, {u32 kind, u32 byte count} per block, then the blocks: opaque 16-byte records
15// LRSC "0DRP", u32 version, ...; the u32 at +0x10 is the root block number
16// CHKS big-endian file size and a 32-bit value (not verified here)
17// LGID empty
18// Little-endian everywhere except the first-section offset and the section sizes. A truncated container shows what
19// is whole and the rest as raw bytes.
20
21#pragma description PSIN metadata container: block table, LSCH/LENM schema, LSNS, LRSC, CHKS (docs/psin.md)
22#pragma endian little
23#pragma magic [ 50 53 49 4E ] @ 0x00
24#pragma array_limit 1048576
25#pragma pattern_limit 8388608
26
27import std.mem;
28import std.core;
29
30// ---- header and instance-data block table ---------------------------------------------------------------------
31
32struct Header {
33 char magic[4];
34 be u32 first_section [[comment("big-endian absolute offset of the first section")]];
35};
36
37Header header @ 0x00;
38
39fn count_rows(u128 limit) {
40 u128 p = 0x08;
41 u32 n = 0;
42 while (p + 16 <= limit && std::mem::read_unsigned(p, 8) != 0x7070707070707070) {
43 p += 16;
44 n += 1;
45 }
46 return n;
47};
48
49u128 g_limit = header.first_section < std::mem::size() ? header.first_section : std::mem::size();
50u32 g_rows = count_rows(g_limit);
51
52struct BlockRow {
53 u32 type [[comment("struct name hash from LSCH, a member type code below 0x100, or 0x100 + n")]];
54 u32 size [[comment("data size in bytes")]];
55 u8 fill[8] [[comment("aa x 8")]];
56};
57
58struct Block {
59 u32 i = std::core::array_index();
60 u8 data[rows[i].size] [[comment("block number i + 1; raw: see psin_data.py")]];
61 u8 pad[(16 - rows[i].size % 16) % 16];
62};
63
64BlockRow rows[g_rows] @ 0x08;
65char table_end[8] @ 0x08 + 16 * g_rows [[comment("\"pppppppp\"")]];
66Block blocks[g_rows] @ 0x08 + 16 * g_rows + 8;
67
68// ---- sections ---------------------------------------------------------------------------------------------------
69
70fn header_count(u128 payload, u128 length, u32 header_size, u32 element_size, u32 count_at, u32 count_size) {
71 if (length == 0) return 0;
72 u32 elements = 0;
73 u32 k = 1;
74 while (header_size * k <= length) {
75 elements += std::mem::read_unsigned(payload + header_size * (k - 1) + count_at, count_size);
76 if (header_size * k + element_size * elements == length) return k;
77 k += 1;
78 }
79 return 0xFFFFFFFF; // no count fits: shown as raw bytes
80};
81
82fn sum_counts(u128 payload, u32 k, u32 header_size, u32 count_at, u32 count_size) {
83 u32 total = 0;
84 for (u32 i = 0, i < k, i += 1) {
85 total += std::mem::read_unsigned(payload + header_size * i + count_at, count_size);
86 }
87 return total;
88};
89
90struct StructHeader {
91 u32 name_hash;
92 u32 signature [[comment("layout signature")]];
93 u8 flags;
94 u8 align_log2;
95 u16 zero_0a;
96 u32 zero_0c;
97 u8 fill[8] [[comment("aa x 8")]];
98 u32 size [[comment("byte size of the struct")]];
99 u16 zero_1c;
100 u16 member_count;
101};
102
103struct Member {
104 u32 name_hash [[comment("0x100 = array element descriptor")]];
105 u32 offset;
106 u8 type;
107 u8 sub;
108 u16 index [[comment("for type 0x5c: position of its 0x100 element descriptor in this struct's members")]];
109 u32 ref_hash [[comment("struct or enum name hash for the referring types, else 0")]];
110};
111
112struct EnumHeader {
113 u32 name_hash;
114 u32 signature;
115 u8 fill[8] [[comment("ee x 8")]];
116 u32 value_count;
117 u32 zero_14;
118};
119
120struct EnumValue {
121 s64 value;
122 u64 name_hash [[comment("case-sensitive joaat in the low half")]];
123};
124
125struct LsnsDesc {
126 u32 kind;
127 u32 bytes;
128};
129
130struct LsnsRecord {
131 u8 bytes[16] [[comment("opaque")]];
132};
133
134struct LsnsBlock {
135 u32 i = std::core::array_index();
136 LsnsRecord records[parent.descs[i].bytes / 16];
137};
138
139bool g_bad = false;
140
141struct Section {
142 char tag[4];
143 be u32 size [[comment("big-endian total size, header included")]];
144 u128 payload = $;
145 if (size < 8 || addressof(tag) + size > std::mem::size()) {
146 g_bad = true;
147 u8 truncated[std::mem::size() - $] [[comment("section runs past the end of the file")]];
148 } else {
149 u32 length = size - 8;
150 if (tag == "LSCH") {
151 u32 k = header_count(payload, length, 32, 16, 30, 2);
152 if (k == 0xFFFFFFFF) {
153 u8 raw[length] [[comment("no struct count fills the payload")]];
154 } else {
155 StructHeader structs[k];
156 Member members[sum_counts(payload, k, 32, 30, 2)];
157 }
158 } else if (tag == "LENM") {
159 u32 k = header_count(payload, length, 24, 16, 16, 4);
160 if (k == 0xFFFFFFFF) {
161 u8 raw[length] [[comment("no enum count fills the payload")]];
162 } else {
163 EnumHeader enums[k];
164 EnumValue values[sum_counts(payload, k, 24, 16, 4)];
165 }
166 } else if (tag == "LSNS" && length >= 4) {
167 u32 block_count;
168 if (4 + 8 * block_count <= length) {
169 LsnsDesc descs[block_count];
170 LsnsBlock lsns_blocks[block_count];
171 }
172 if ($ < payload + length) {
173 u8 rest[payload + length - $] [[comment("does not fit the block table")]];
174 }
175 } else if (tag == "LRSC" && length >= 0x14 && std::mem::read_string(payload, 4) == "0DRP") {
176 char rsc_magic[4];
177 u32 rsc_version;
178 u32 u32_08;
179 u32 u32_0c;
180 u32 root_block [[comment("block number of the root struct")]];
181 u8 rest[length - 0x14];
182 } else if (tag == "CHKS" && length >= 8) {
183 be u32 checksum_size [[comment("big-endian file size")]];
184 u8 checksum[4] [[comment("32-bit value, not verified")]];
185 u8 rest[length - 8];
186 } else {
187 u8 raw[length];
188 }
189 }
190};
191
192Section sections[while(!g_bad && header.first_section + 8 <= std::mem::size() && std::mem::size() - $ >= 8)]
193 @ header.first_section;
diff --git a/tools/imhex/rbf0.hexpat b/tools/imhex/rbf0.hexpat
new file mode 100644
index 000000000..8d311e099
--- /dev/null
+++ b/tools/imhex/rbf0.hexpat
@@ -0,0 +1,96 @@
1// ImHex pattern for one RBF0 resource: RAGE's binary form of an XML data file.
2//
3// The grammar is the one measured in docs/rbf0.md (section 3) and parsed by tools/rbf0_index.py (parse_rbf0):
4//
5// 0x00 "RBF0"
6// 0x04 FB FF 01 00 optional prologue. With it, integers and floats are 8 bytes ("wide"); without it they are
7// 4 bytes ("narrow") and the records start at 0x04. What the four bytes mean is not established;
8// the width follows them in every measured resource (docs/rbf0.md).
9// records, each a u8 descriptor index and a u8 type:
10// FF FF close the open element
11// FD FF text for the open element: u32 length, then that many bytes
12// index == descriptors so far a new descriptor: u16 name length, then the UTF-8 name, before the payload
13// type 0x00 open an element: u16 0, u16 0, u16 attribute count
14// type 0x10 integer 0x20 true 0x30 false 0x40 float 0x50 three floats
15// type 0x60 string: u16 length, then UTF-8 bytes
16// The stream has no length field and no section table: it ends where the root element closes, and the pattern
17// stops there.
18//
19// Open an inflated, joined resource, not the archive. A resource larger than 64 KiB is split over several zlib
20// streams, with no header on the continuations (docs/rbf0.md section 2); tools/rbf0_index.py joins them.
21
22#pragma description RBF0 record stream (binary XML, docs/rbf0.md)
23#pragma endian little
24#pragma magic [ 52 42 46 30 ] @ 0x00
25// The largest measured resource has 68,398 elements and about twice as many records.
26#pragma array_limit 4194304
27#pragma pattern_limit 33554432
28
29import std.mem;
30import std.io;
31
32bool g_wide = std::mem::size() >= 8 && std::mem::read_unsigned(0x04, 4) == 0x0001FFFB;
33u32 g_descriptors = 0;
34u32 g_depth = 0;
35bool g_done = false;
36
37struct Header {
38 char magic[4];
39 if (g_wide) {
40 u8 prologue[4] [[comment("FB FF 01 00: 8-byte integers and floats follow")]];
41 }
42};
43
44struct Record {
45 u8 index;
46 u8 type;
47 if (index == 0xFF) {
48 if (g_depth > 0) g_depth -= 1;
49 if (g_depth == 0) g_done = true;
50 } else if (index == 0xFD) {
51 u32 text_length;
52 char text[text_length];
53 } else {
54 if (index == g_descriptors) {
55 u16 name_length;
56 char name[name_length] [[comment("new descriptor")]];
57 g_descriptors += 1;
58 }
59 if (type == 0x00) {
60 u16 word0;
61 u16 word1;
62 u16 attribute_count;
63 g_depth += 1;
64 } else if (type == 0x10) {
65 if (g_wide) {
66 u64 value_int;
67 } else {
68 u32 value_int;
69 }
70 } else if (type == 0x40) {
71 if (g_wide) {
72 double value_float;
73 } else {
74 float value_float;
75 }
76 } else if (type == 0x50) {
77 if (g_wide) {
78 double value_vec3[3];
79 } else {
80 float value_vec3[3];
81 }
82 } else if (type == 0x60) {
83 u16 string_length;
84 char value_string[string_length];
85 }
86 }
87} [[format("format_record")]];
88
89fn format_record(Record r) {
90 if (r.index == 0xFF) return "close";
91 if (r.index == 0xFD) return "text";
92 return std::format("descriptor {} type 0x{:02X}", r.index, r.type);
93};
94
95Header header @ 0x00;
96Record records[while(!g_done && !std::mem::eof())] @ sizeof(header);
diff --git a/tools/imhex/rpf9.hexpat b/tools/imhex/rpf9.hexpat
new file mode 100644
index 000000000..0fbc1e450
--- /dev/null
+++ b/tools/imhex/rpf9.hexpat
@@ -0,0 +1,32 @@
1// ImHex pattern for the header of an RPF9 archive.
2//
3// Only measured fields are named (docs/rpf.md "What is readable"; docs/story.md "Signatures actually observed"):
4// 0x00 "9FPR" RPF9 stored little-endian
5// 0x04 data offset u32, where the data area (zlib streams laid end to end) starts
6// 0x08 u32 present in every header; meaning not established
7// 0x0C u32 present in every header; meaning not established
8// Everything from 0x10 to the data offset is the rest of the header and the table of contents. The TOC is
9// encrypted/packed: this pattern shows that range as opaque bytes and decodes nothing in it (no keys, no decryption).
10//
11// This describes the archive's own header at offset 0. Nested RPF9 headers occur inside the data area
12// (docs/story.md); their offsets are not covered here.
13
14#pragma description RPF9 archive header, opaque TOC and data area start (docs/rpf.md)
15#pragma endian little
16#pragma magic [ 39 46 50 52 ] @ 0x00
17
18import std.mem;
19import std.sys;
20
21struct Rpf9Header {
22 char magic[4] [[comment("\"9FPR\": RPF9 stored little-endian")]];
23 u32 data_offset [[comment("start of the data area (docs/rpf.md)")]];
24 u32 u32_08 [[comment("meaning not established")]];
25 u32 u32_0c [[comment("meaning not established")]];
26};
27
28Rpf9Header header @ 0x00;
29std::assert(header.data_offset >= sizeof(header) && header.data_offset <= std::mem::size(),
30 "the data offset is outside the file");
31u8 header_rest_and_toc[header.data_offset - sizeof(header)] @ sizeof(header)
32 [[comment("rest of the header and the table of contents: encrypted/packed, not decoded")]];
diff --git a/tools/instance_lists.py b/tools/instance_lists.py
index 988f35563..bc7fedd96 100644
--- a/tools/instance_lists.py
+++ b/tools/instance_lists.py
@@ -357,7 +357,7 @@ def main(argv=None):
357 if args.json: 357 if args.json:
358 try: 358 try:
359 os.makedirs(os.path.dirname(os.path.abspath(args.json)), exist_ok=True) 359 os.makedirs(os.path.dirname(os.path.abspath(args.json)), exist_ok=True)
360 with open(args.json, "w", encoding="utf-8") as fh: 360 with open(args.json, "w", encoding="utf-8", newline="\n") as fh:
361 json.dump(T, fh, indent=1, sort_keys=True) 361 json.dump(T, fh, indent=1, sort_keys=True)
362 except OSError as exc: 362 except OSError as exc:
363 print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr) 363 print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr)
diff --git a/tools/int_hw_probe.py b/tools/int_hw_probe.py
new file mode 100644
index 000000000..9ebd50d9d
--- /dev/null
+++ b/tools/int_hw_probe.py
@@ -0,0 +1,743 @@
1r"""SHADER-137: RDNA2 hardware probe for the integer contract rows checked only on the CPU.
2
3Runs small, self-contained RDNA2 instruction sequences natively on an AMD GPU through tools/hw_oracle (wave32 and
4wave64) and compares every output word with Leonida's live translator (tools/rdna2spirv.py ->
5tests/semantic/spirv_mini_interp.py). Standard library only; no game files.
6
7Groups covered (each references its contract row in docs/design.md):
8 salu_absdiff_mulhi s_absdiff_i32, s_mul_hi_i32, s_mul_hi_u32 (SCC written vs kept)
9 salu_lshl_add s_lshl1..4_add_u32 (64-bit carry / shift-out into SCC)
10 salu_sext_flbit s_sext_i32_i8, s_sext_i32_i16, s_flbit_i32 (SCC kept)
11 salu_cmov_pack s_cmov_b32, s_cmovk_i32, s_pack_ll/lh/hh_b32_b16 (SCC kept)
12 salu_bfe_past31 s_bfe_u32, s_bfe_i32 with offset + width > 32 and width 0
13 salu_64_data s_brev_b64, s_bfe_u64/i64, s_bitset0/1_b64, s_flbit_i32_b64/i64
14 salu_quad_bitrep s_quadmask_b32/b64, s_bitreplicate_b64_b32
15 salu_64_bitwise s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64 on scalar data
16 salu_movrels s_movrels_b32, s_movrels_b64 (M0 indexing, SCC kept)
17 valu_add_nc_clamp v_add/sub/subrev_nc_u32, v_add/sub_nc_i32, v_add/sub_nc_u16 with clamp
18 valu_add_co_clamp v_add/sub/subrev_co[_ci]_u32 with clamp (saturation + carry)
19 valu_mad64 v_mad_u64_u32, v_mad_i64_i32 (sdst bit 64 and inactive EXEC lane)
20 valu_sad_lerp v_sad_u8, v_sad_hi_u8, v_sad_u16, v_sad_u32, v_msad_u8, v_lerp_u8
21 valu_qsad_mqsad v_qsad_pk_u16_u8, v_mqsad_pk_u16_u8, v_mqsad_u32_u8
22 valu_mul24_sh64 v_mul_hi_u32_u24, v_mul_hi_i32_i24, v_lshrrev_b64, v_ashrrev_i64
23 valu_mad16 v_mad_u16, v_mad_i16 (clamp, op_sel, kept half)
24 valu_cvt_16 v_cvt_f16_u16/i16, v_cvt_u16/i16_f16 (kept half, op_sel, NaN, inf)
25 valu_cvt_flr_rpi v_cvt_flr_i32_f32, v_cvt_rpi_i32_f32 (exact floor(x+0.5), signed NaN)
26 valu_cvt_pknorm v_cvt_pknorm_i16_f32, v_cvt_pknorm_u16_f32 (ties, saturation, NaN)
27
28Usage:
29 python -I tools/int_hw_probe.py # translator side only (CPU)
30 python -I tools/int_hw_probe.py --oracle hw # native AMD GPU only (wave32 + wave64)
31 python -I tools/int_hw_probe.py --oracle both # compare hardware vs translator
32 python -I tools/int_hw_probe.py --oracle both --strict # fail on known translator divergences too
33 python -I tools/int_hw_probe.py --self-test
34
35Exit codes:
36 0 all unexpected comparisons match (and wave32 == wave64 on hardware)
37 1 at least one unexpected mismatch, wave32/64 diff, or known divergence under --strict
38 2 bad CLI arguments or harness error
39 77 hardware oracle requested but unavailable on this machine
40"""
41import argparse
42import json
43import os
44import struct
45import sys
46import tempfile
47import warnings
48
49HERE = os.path.dirname(os.path.abspath(__file__))
50ROOT = os.path.dirname(HERE)
51sys.dont_write_bytecode = True
52for p in (HERE, os.path.join(ROOT, "tests", "semantic")):
53 if p not in sys.path:
54 sys.path.insert(0, p)
55
56import rdna2spirv # noqa: E402
57import spirv_mini_interp # noqa: E402
58
59STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
60SENTINEL = 0x5A5A5A5A
61
62# Live translator divergences confirmed on AMD Radeon 680M (gfx1035, RDNA2, wave32 & wave64).
63# Each entry maps case.name -> (tag, expected_hw_words, reason). Empty: the five measured on gfx1035 (VOP3 clamp
64# on the carry-out add/sub ops, v_cvt_rpi_i32_f32's exact floor(x + 0.5), and v_cvt_flr/rpi's NaN saturation by
65# sign) are translated as the hardware does since #1831 and #1856.
66KNOWN_DIVERGENCES = {}
67
68
69class Case:
70 """One self-contained 4-word probe. `body` leaves results in v8..v11 and must not clobber s[0:3] or v0.
71 For wave-size-dependent mask instructions, `{vcc}`, `{exec}`, `{smov}`, `{stmp}` expand to wave32/wave64 forms."""
72
73 __slots__ = ("group", "name", "body", "note")
74
75 def __init__(self, group, name, body, note=""):
76 self.group = group
77 self.name = name
78 self.body = tuple(body)
79 self.note = note
80
81 def lines(self, wave=32):
82 vcc = "vcc_lo" if wave == 32 else "vcc"
83 exc = "exec_lo" if wave == 32 else "exec"
84 smov = "s_mov_b32" if wave == 32 else "s_mov_b64"
85 stmp = "s14" if wave == 32 else "s[14:15]"
86 return [ln.format(vcc=vcc, exec=exc, smov=smov, stmp=stmp) for ln in self.body]
87
88
89def _scc_seed(val):
90 return "s_cmp_eq_u32 0, 0" if val else "s_cmp_eq_u32 0, 1"
91
92
93def _salu32_pair(group, name, setup, op_line, note=""):
94 """Run one 32-bit scalar op twice: once with SCC preset to 0 (v8=D, v9=SCC) and once with SCC preset to 1
95 (v10=D, v11=SCC), so 'SCC kept' and 'SCC written' are both directly observed."""
96 body = [
97 *setup, _scc_seed(0), op_line,
98 "s_cselect_b32 s30, 1, 0", "v_mov_b32 v8, s6", "v_mov_b32 v9, s30",
99 *setup, _scc_seed(1), op_line,
100 "s_cselect_b32 s30, 1, 0", "v_mov_b32 v10, s6", "v_mov_b32 v11, s30",
101 ]
102 return Case(group, name, body, note)
103
104
105def _salu64_case(group, name, setup, op_line, scc_in, note=""):
106 """Run one 64-bit scalar op with SCC preset to scc_in; output v8=s6 (lo), v9=s7 (hi), v10=SCC, v11=0."""
107 body = [
108 *setup, _scc_seed(scc_in), op_line,
109 "s_cselect_b32 s30, 1, 0",
110 "v_mov_b32 v8, s6", "v_mov_b32 v9, s7", "v_mov_b32 v10, s30", "v_mov_b32 v11, 0",
111 ]
112 return Case(group, name, body, note)
113
114
115def _valu4_case(group, name, body, note=""):
116 return Case(group, name, body, note)
117
118
119def build_cases():
120 cases = []
121
122 # 1. s_absdiff_i32, s_mul_hi_i32, s_mul_hi_u32 (docs/design.md)
123 cases += [
124 _salu32_pair("salu_absdiff_mulhi", "s_absdiff_basic",
125 ["s_mov_b32 s4, 10", "s_mov_b32 s5, 25"],
126 "s_absdiff_i32 s6, s4, s5", "|10 - 25| = 15, SCC=1"),
127 _salu32_pair("salu_absdiff_mulhi", "s_absdiff_equal",
128 ["s_mov_b32 s4, 0x80000000", "s_mov_b32 s5, 0x80000000"],
129 "s_absdiff_i32 s6, s4, s5", "equal -> 0, SCC=0"),
130 _salu32_pair("salu_absdiff_mulhi", "s_absdiff_wrap_max_min",
131 ["s_mov_b32 s4, 0x7fffffff", "s_mov_b32 s5, 0x80000000"],
132 "s_absdiff_i32 s6, s4, s5", "0x7fffffff - 0x80000000 wraps to -1 -> abs 1, SCC=1"),
133 _salu32_pair("salu_absdiff_mulhi", "s_absdiff_int_min",
134 ["s_mov_b32 s4, 0x80000000", "s_mov_b32 s5, 0"],
135 "s_absdiff_i32 s6, s4, s5", "diff = INT_MIN stays 0x80000000, SCC=1"),
136 _salu32_pair("salu_absdiff_mulhi", "s_mul_hi_i32_min_min",
137 ["s_mov_b32 s4, 0x80000000", "s_mov_b32 s5, 0x80000000"],
138 "s_mul_hi_i32 s6, s4, s5", "(-2^31)*(-2^31) >> 32 = 0x40000000, SCC kept"),
139 _salu32_pair("salu_absdiff_mulhi", "s_mul_hi_i32_neg_pos",
140 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 2"],
141 "s_mul_hi_i32 s6, s4, s5", "(-1)*2 >> 32 = 0xffffffff, SCC kept"),
142 _salu32_pair("salu_absdiff_mulhi", "s_mul_hi_u32_max_max",
143 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0xffffffff"],
144 "s_mul_hi_u32 s6, s4, s5", "(2^32-1)^2 >> 32 = 0xfffffffe, SCC kept"),
145 ]
146
147 # 2. s_lshl1..4_add_u32 (64-bit shift-out + add carry into SCC)
148 for shift in (1, 2, 3, 4):
149 op = f"s_lshl{shift}_add_u32"
150 high_bit = 1 << (32 - shift)
151 cases += [
152 _salu32_pair("salu_lshl_add", f"{op}_no_carry",
153 ["s_mov_b32 s4, 0x00010000", "s_mov_b32 s5, 5"],
154 f"{op} s6, s4, s5", "no shift-out, no add carry -> SCC=0"),
155 _salu32_pair("salu_lshl_add", f"{op}_shift_out_only",
156 [f"s_mov_b32 s4, 0x{high_bit:08x}", "s_mov_b32 s5, 0"],
157 f"{op} s6, s4, s5", "bit shifted out of S0 with S1=0 -> D=0, SCC=1"),
158 _salu32_pair("salu_lshl_add", f"{op}_add_carry_only",
159 ["s_mov_b32 s4, 1", "s_mov_b32 s5, 0xffffffff"],
160 f"{op} s6, s4, s5", "add carry without shift-out -> SCC=1"),
161 ]
162
163 # 3. s_sext_i32_i8, s_sext_i32_i16, s_flbit_i32
164 cases += [
165 _salu32_pair("salu_sext_flbit", "s_sext_i8_neg",
166 ["s_mov_b32 s4, 0x12345680"], "s_sext_i32_i8 s6, s4", "0x80 -> 0xffffff80, SCC kept"),
167 _salu32_pair("salu_sext_flbit", "s_sext_i8_pos",
168 ["s_mov_b32 s4, 0xffffff7f"], "s_sext_i32_i8 s6, s4", "0x7f -> 0x0000007f, SCC kept"),
169 _salu32_pair("salu_sext_flbit", "s_sext_i16_neg",
170 ["s_mov_b32 s4, 0x00008001"], "s_sext_i32_i16 s6, s4", "0x8001 -> 0xffff8001, SCC kept"),
171 _salu32_pair("salu_sext_flbit", "s_sext_i16_pos",
172 ["s_mov_b32 s4, 0xffff7fff"], "s_sext_i32_i16 s6, s4", "0x7fff -> 0x00007fff, SCC kept"),
173 _salu32_pair("salu_sext_flbit", "s_flbit_i32_zero",
174 ["s_mov_b32 s4, 0"], "s_flbit_i32 s6, s4", "0 -> 0xffffffff, SCC kept"),
175 _salu32_pair("salu_sext_flbit", "s_flbit_i32_neg1",
176 ["s_mov_b32 s4, 0xffffffff"], "s_flbit_i32 s6, s4", "-1 -> 0xffffffff, SCC kept"),
177 _salu32_pair("salu_sext_flbit", "s_flbit_i32_pos1",
178 ["s_mov_b32 s4, 1"], "s_flbit_i32 s6, s4", "1 -> 30, SCC kept"),
179 _salu32_pair("salu_sext_flbit", "s_flbit_i32_neg16",
180 ["s_mov_b32 s4, 0xfffffff0"], "s_flbit_i32 s6, s4", "-16 -> 27, SCC kept"),
181 _salu32_pair("salu_sext_flbit", "s_flbit_i32_int_min",
182 ["s_mov_b32 s4, 0x80000000"], "s_flbit_i32 s6, s4", "INT_MIN -> 0, SCC kept"),
183 ]
184
185 # 4. s_cmov_b32, s_cmovk_i32, s_pack_ll/lh/hh_b32_b16
186 cases += [
187 _salu32_pair("salu_cmov_pack", "s_cmov_b32",
188 ["s_mov_b32 s4, 0x11223344", "s_mov_b32 s6, 0xaabbccdd"],
189 "s_cmov_b32 s6, s4", "SCC=0 keeps D, SCC=1 takes S0, SCC kept"),
190 _salu32_pair("salu_cmov_pack", "s_cmovk_i32_neg",
191 ["s_mov_b32 s6, 0x12345678"],
192 "s_cmovk_i32 s6, -300", "SCC=0 keeps D, SCC=1 sign-extends imm16, SCC kept"),
193 _salu32_pair("salu_cmov_pack", "s_pack_ll",
194 ["s_mov_b32 s4, 0x11112222", "s_mov_b32 s5, 0x33334444"],
195 "s_pack_ll_b32_b16 s6, s4, s5", "{S1.lo, S0.lo} = 0x44442222, SCC kept"),
196 _salu32_pair("salu_cmov_pack", "s_pack_lh",
197 ["s_mov_b32 s4, 0x11112222", "s_mov_b32 s5, 0x33334444"],
198 "s_pack_lh_b32_b16 s6, s4, s5", "{S1.hi, S0.lo} = 0x33332222, SCC kept"),
199 _salu32_pair("salu_cmov_pack", "s_pack_hh",
200 ["s_mov_b32 s4, 0x11112222", "s_mov_b32 s5, 0x33334444"],
201 "s_pack_hh_b32_b16 s6, s4, s5", "{S1.hi, S0.hi} = 0x33331111, SCC kept"),
202 ]
203
204 # 5. s_bfe_u32 / s_bfe_i32 past bit 31
205 cases += [
206 _salu32_pair("salu_bfe_past31", "s_bfe_i32_past31",
207 ["s_mov_b32 s4, 0xd2f90159", "s_mov_b32 s5, 0x7f001c"],
208 "s_bfe_i32 s6, s4, s5", "off=28 width=127 stops at bit 31 -> 0xfffffffd, SCC=1"),
209 _salu32_pair("salu_bfe_past31", "s_bfe_u32_past31",
210 ["s_mov_b32 s4, 0xd2f90159", "s_mov_b32 s5, 0xff7f001c"],
211 "s_bfe_u32 s6, s4, s5", "upper bits ignored, stops at bit 31 -> 0x0000000d, SCC=1"),
212 _salu32_pair("salu_bfe_past31", "s_bfe_i32_width0",
213 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0x00000005"],
214 "s_bfe_i32 s6, s4, s5", "width=0 -> 0, SCC=0"),
215 ]
216
217 # 6. 64-bit scalar data ops (s_brev_b64, s_bfe_u64/i64, s_bitset0/1_b64, s_flbit_i32_b64/i64)
218 cases += [
219 _salu64_case("salu_64_data", "s_brev_b64_scc1",
220 ["s_mov_b32 s4, 0x80000001", "s_mov_b32 s5, 0x12345678"],
221 "s_brev_b64 s[6:7], s[4:5]", 1, "bit-reverse 64-bit pair, SCC kept"),
222 _salu64_case("salu_64_data", "s_bfe_u64_cross_past63",
223 ["s_mov_b32 s4, 0x12345678", "s_mov_b32 s5, 0xd2f90159", "s_mov_b32 s8, 0x7f003c"],
224 "s_bfe_u64 s[6:7], s[4:5], s8", 0, "off=60 width=127 stops at bit 63 -> 0xd, SCC=1"),
225 _salu64_case("salu_64_data", "s_bfe_i64_past63",
226 ["s_mov_b32 s4, 0x12345678", "s_mov_b32 s5, 0xd2f90159", "s_mov_b32 s8, 0x7f003c"],
227 "s_bfe_i64 s[6:7], s[4:5], s8", 0, "off=60 width=127 sign-extends 0xd -> -3, SCC=1"),
228 _salu64_case("salu_64_data", "s_bfe_u64_width0",
229 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0xffffffff", "s_mov_b32 s8, 0x00000010"],
230 "s_bfe_u64 s[6:7], s[4:5], s8", 1, "width=0 -> 0, SCC=0"),
231 _salu64_case("salu_64_data", "s_bitset0_b64_hi",
232 ["s_mov_b32 s6, 0xffffffff", "s_mov_b32 s7, 0xffffffff", "s_mov_b32 s8, 63"],
233 "s_bitset0_b64 s[6:7], s8", 1, "clear bit 63, SCC kept"),
234 _salu64_case("salu_64_data", "s_bitset1_b64_mod64",
235 ["s_mov_b32 s6, 0", "s_mov_b32 s7, 0", "s_mov_b32 s8, 97"],
236 "s_bitset1_b64 s[6:7], s8", 0, "set bit 97 & 63 = 33 (hi bit 1), SCC kept"),
237 _salu32_pair("salu_64_data", "s_flbit_i32_b64_zero",
238 ["s_mov_b32 s4, 0", "s_mov_b32 s5, 0"],
239 "s_flbit_i32_b64 s6, s[4:5]", "0 -> -1, SCC kept"),
240 _salu32_pair("salu_64_data", "s_flbit_i32_b64_lo",
241 ["s_mov_b32 s4, 0x00010000", "s_mov_b32 s5, 0"],
242 "s_flbit_i32_b64 s6, s[4:5]", "bit 16 -> 47 leading zeros, SCC kept"),
243 _salu32_pair("salu_64_data", "s_flbit_i32_i64_neg",
244 ["s_mov_b32 s4, 0xfffffff0", "s_mov_b32 s5, 0xffffffff"],
245 "s_flbit_i32_i64 s6, s[4:5]", "-16 -> 59 sign bits, SCC kept"),
246 _salu32_pair("salu_64_data", "s_flbit_i32_i64_neg1",
247 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0xffffffff"],
248 "s_flbit_i32_i64 s6, s[4:5]", "-1 -> -1, SCC kept"),
249 ]
250
251 # 7. s_quadmask_b32/b64, s_bitreplicate_b64_b32
252 cases += [
253 _salu32_pair("salu_quad_bitrep", "s_quadmask_b32_nz",
254 ["s_mov_b32 s4, 0x10080041"],
255 "s_quadmask_b32 s6, s4", "quads 0,1,4,7 set -> 0x93, SCC=1"),
256 _salu32_pair("salu_quad_bitrep", "s_quadmask_b32_zero",
257 ["s_mov_b32 s4, 0"],
258 "s_quadmask_b32 s6, s4", "0 -> 0, SCC=0"),
259 _salu64_case("salu_quad_bitrep", "s_quadmask_b64_hi",
260 ["s_mov_b32 s4, 0x00000000", "s_mov_b32 s5, 0x80000001"],
261 "s_quadmask_b64 s[6:7], s[4:5]", 0, "quads 8,15 -> lo=0x8100 hi=0, SCC=1"),
262 _salu64_case("salu_quad_bitrep", "s_bitreplicate_b64_b32",
263 ["s_mov_b32 s4, 0x80010005"],
264 "s_bitreplicate_b64_b32 s[6:7], s4", 1, "each bit doubled, SCC kept"),
265 ]
266
267 # 8. 64-bit scalar bitwise ops on scalar data
268 for op in ("s_and_b64", "s_or_b64", "s_xor_b64", "s_andn2_b64", "s_orn2_b64",
269 "s_nand_b64", "s_nor_b64", "s_xnor_b64"):
270 cases.append(_salu64_case(
271 "salu_64_bitwise", f"{op}_data",
272 ["s_mov_b32 s4, 0xf0f000ff", "s_mov_b32 s5, 0x12345678",
273 "s_mov_b32 s8, 0x0ff0ff00", "s_mov_b32 s9, 0x87654321"],
274 f"{op} s[6:7], s[4:5], s[8:9]", 0, f"{op} on 64-bit scalar data + SCC",
275 ))
276 cases.append(_salu64_case(
277 "salu_64_bitwise", "s_not_b64_all_ones",
278 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0xffffffff"],
279 "s_not_b64 s[6:7], s[4:5]", 1, "~(-1) = 0, SCC=0",
280 ))
281
282 # 9. s_movrels_b32 / s_movrels_b64
283 cases += [
284 _salu32_pair("salu_movrels", "s_movrels_b32_m0_2",
285 ["s_mov_b32 s10, 0x11111111", "s_mov_b32 s11, 0x22222222",
286 "s_mov_b32 s12, 0x33333333", "s_mov_b32 m0, 2"],
287 "s_movrels_b32 s6, s10", "SGPR[10+2] = 0x33333333, SCC kept"),
288 _salu64_case("salu_movrels", "s_movrels_b64_m0_2",
289 ["s_mov_b32 s10, 0x11111111", "s_mov_b32 s11, 0x22222222",
290 "s_mov_b32 s12, 0x33333333", "s_mov_b32 s13, 0x44444444", "s_mov_b32 m0, 2"],
291 "s_movrels_b64 s[6:7], s[10:11]", 1, "SGPR[12:13], SCC kept"),
292 ]
293
294 # 10. Integer clamp on v_add/sub/subrev_nc_u32, v_add/sub_nc_i32, v_add/sub_nc_u16
295 cases += [
296 _valu4_case("valu_add_nc_clamp", "v_add_sub_nc_u32_clamp", [
297 "v_mov_b32 v1, 0xfffffff0", "v_mov_b32 v2, 0x30",
298 "v_add_nc_u32_e64 v8, v1, v2 clamp", # saturates to 0xffffffff
299 "v_sub_nc_u32_e64 v9, v2, v1 clamp", # saturates to 0
300 "v_subrev_nc_u32_e64 v10, v1, v2 clamp", # v2 - v1 -> saturates to 0
301 "v_subrev_nc_u32_e64 v11, v2, v1 clamp", # v1 - v2 = 0xffffffc0
302 ], "u32 nc add/sub/subrev with clamp"),
303 _valu4_case("valu_add_nc_clamp", "v_add_sub_nc_i32_clamp", [
304 "v_mov_b32 v1, 0x7ffffff0", "v_mov_b32 v2, 0x30",
305 "v_mov_b32 v3, 0x80000010", "v_mov_b32 v4, 0x30",
306 "v_add_nc_i32_e64 v8, v1, v2 clamp", # +overflow -> 0x7fffffff
307 "v_sub_nc_i32_e64 v9, v3, v4 clamp", # -overflow -> 0x80000000
308 "v_add_nc_i32_e64 v10, v3, v3 clamp", # neg+neg overflow -> 0x80000000
309 "v_sub_nc_i32_e64 v11, v1, v3 clamp", # pos-neg overflow -> 0x7fffffff
310 ], "i32 nc add/sub with clamp"),
311 _valu4_case("valu_add_nc_clamp", "v_add_sub_nc_u16_clamp", [
312 "v_mov_b32 v1, 0x1234fff0", "v_mov_b32 v2, 0x56780030",
313 f"v_mov_b32 v8, 0x{SENTINEL:08x}",
314 f"v_mov_b32 v9, 0x{SENTINEL:08x}",
315 f"v_mov_b32 v10, 0x{SENTINEL:08x}",
316 f"v_mov_b32 v11, 0x{SENTINEL:08x}",
317 "v_add_nc_u16_e64 v8, v1, v2 clamp", # lo saturates 0xffff, hi kept
318 "v_sub_nc_u16_e64 v9, v2, v1 clamp", # lo saturates 0x0000, hi kept
319 "v_add_nc_u16_e64 v10, v1, v2 op_sel:[0,0,1] clamp", # write hi saturates 0xffff, lo kept
320 "v_sub_nc_u16_e64 v11, v1, v2 op_sel:[1,1,0] clamp", # 0x1234 - 0x5678 -> 0x0000, hi kept
321 ], "u16 nc add/sub with clamp and op_sel (untouched half kept)"),
322 ]
323
324 # 11. v_add/sub/subrev_co[_ci]_u32 with clamp (known divergence: translator ignores clamp)
325 cases += [
326 _valu4_case("valu_add_co_clamp", "v_add_co_u32_clamp", [
327 "v_mov_b32 v1, 0xffffffff", "v_mov_b32 v2, 0xffffffff",
328 "v_add_co_u32 v8, {vcc}, v1, v2 clamp",
329 "v_cndmask_b32_e64 v9, 0, 1, {vcc}",
330 "v_mov_b32 v3, 5", "v_mov_b32 v4, 10",
331 "v_sub_co_u32 v10, {vcc}, v3, v4 clamp",
332 "v_cndmask_b32_e64 v11, 0, 1, {vcc}",
333 ], "v_add_co_u32 / v_sub_co_u32 clamp: hardware saturates D and reports real carry/borrow"),
334 _valu4_case("valu_add_co_clamp", "v_subrev_co_u32_clamp", [
335 "v_mov_b32 v1, 10", "v_mov_b32 v2, 5",
336 "v_subrev_co_u32 v8, {vcc}, v1, v2 clamp",
337 "v_cndmask_b32_e64 v9, 0, 1, {vcc}",
338 "v_mov_b32 v3, 0", "v_mov_b32 v4, 0",
339 "{smov} {vcc}, -1",
340 "v_subrev_co_ci_u32_e64 v10, {vcc}, v3, v4, {vcc} clamp",
341 "v_cndmask_b32_e64 v11, 0, 1, {vcc}",
342 ], "v_subrev_co_u32 / v_subrev_co_ci_u32 clamp: hardware saturates D to 0 and reports borrow=1"),
343 _valu4_case("valu_add_co_clamp", "v_add_co_ci_u32_clamp", [
344 "v_mov_b32 v1, 0xffffffff", "v_mov_b32 v2, 0",
345 "{smov} {vcc}, -1",
346 "v_add_co_ci_u32_e64 v8, {vcc}, v1, v2, {vcc} clamp",
347 "v_cndmask_b32_e64 v9, 0, 1, {vcc}",
348 "v_mov_b32 v3, 0", "v_mov_b32 v4, 0",
349 "{smov} {vcc}, -1",
350 "v_sub_co_ci_u32_e64 v10, {vcc}, v3, v4, {vcc} clamp",
351 "v_cndmask_b32_e64 v11, 0, 1, {vcc}",
352 ], "v_add_co_ci_u32 / v_sub_co_ci_u32 clamp: carry-in overflow saturates D and sets carry-out"),
353 ]
354
355 # 12. v_mad_u64_u32, v_mad_i64_i32 (sdst bit 64 and EXEC masking)
356 cases += [
357 _valu4_case("valu_mad64", "v_mad_u64_u32_carry", [
358 "v_mov_b32 v1, 0xffffffff", "v_mov_b32 v2, 0xffffffff",
359 "v_mov_b32 v4, 0xffffffff", "v_mov_b32 v5, 0xffffffff",
360 "v_mad_u64_u32 v[8:9], {vcc}, v1, v2, v[4:5]",
361 "v_cndmask_b32_e64 v10, 0, 1, {vcc}",
362 "v_mov_b32 v11, 0",
363 ], "u64 max*max + max64 -> carry=1"),
364 _valu4_case("valu_mad64", "v_mad_i64_i32_pos_overflow", [
365 "v_mov_b32 v1, 0x80000000", "v_mov_b32 v2, 0x80000000",
366 "v_mov_b32 v4, 0xffffffff", "v_mov_b32 v5, 0x7fffffff",
367 "v_mad_i64_i32 v[8:9], {vcc}, v1, v2, v[4:5]",
368 "v_cndmask_b32_e64 v10, 0, 1, {vcc}",
369 "v_mov_b32 v11, 0",
370 ], "(-2^31)^2 + INT64_MAX > 0 (signed overflow, positive exact sum -> sdst=0)"),
371 _valu4_case("valu_mad64", "v_mad_i64_i32_neg_sum", [
372 "v_mov_b32 v1, 0xfffffffe", "v_mov_b32 v2, 3",
373 "v_mov_b32 v4, 0", "v_mov_b32 v5, 0",
374 "v_mad_i64_i32 v[8:9], {vcc}, v1, v2, v[4:5]",
375 "v_cndmask_b32_e64 v10, 0, 1, {vcc}",
376 "v_mov_b32 v11, 0",
377 ], "(-2)*3 + 0 = -6 -> sdst=1 (bit 64 sign of exact 65-bit sum)"),
378 _valu4_case("valu_mad64", "v_mad_u64_u32_inactive_lane", [
379 "v_mov_b32 v1, 0xffffffff", "v_mov_b32 v2, 0xffffffff",
380 "v_mov_b32 v4, 0xffffffff", "v_mov_b32 v5, 0xffffffff",
381 "v_mov_b32 v8, 0x11111111", "v_mov_b32 v9, 0x22222222",
382 "{smov} {vcc}, -1",
383 "{smov} {stmp}, {exec}",
384 "{smov} {exec}, 0",
385 "v_mad_u64_u32 v[8:9], {vcc}, v1, v2, v[4:5]",
386 "{smov} {exec}, {stmp}",
387 "v_cndmask_b32_e64 v10, 0, 1, {vcc}",
388 "v_mov_b32 v11, 0",
389 ], "inactive EXEC lane: D untouched and sdst bit cleared to 0"),
390 ]
391
392 # 13. v_sad_u8, v_sad_hi_u8, v_sad_u16, v_sad_u32, v_msad_u8, v_lerp_u8
393 cases += [
394 _valu4_case("valu_sad_lerp", "v_sad_ops", [
395 "v_mov_b32 v1, 0xff801001", "v_mov_b32 v2, 0x0080f002", "v_mov_b32 v3, 0xffffff00",
396 "v_sad_u8 v8, v1, v2, v3", # wraps 32-bit
397 "v_sad_hi_u8 v9, v1, v2, v3", # (byte_sad << 16) + S2
398 "v_sad_u16 v10, v1, v2, v3", # 2x16-bit SAD + S2
399 "v_sad_u32 v11, v1, v2, v3", # |v1 - v2| + S2
400 ], "v_sad_u8 / v_sad_hi_u8 / v_sad_u16 / v_sad_u32 with 32-bit wrap"),
401 _valu4_case("valu_sad_lerp", "v_msad_and_lerp", [
402 "v_mov_b32 v1, 0xff801001", "v_mov_b32 v2, 0x00800005", "v_mov_b32 v3, 100",
403 "v_msad_u8 v8, v1, v2, v3", # skips bytes 1 and 3 where S1 byte == 0
404 "v_mov_b32 v4, 0xff030200", "v_mov_b32 v5, 0xff040301", "v_mov_b32 v6, 0x01000100",
405 "v_lerp_u8 v9, v4, v5, v6", # per-byte (a+b+(c&1))>>1
406 "v_mov_b32 v7, 0x00feffff",
407 "v_lerp_u8 v10, v4, v5, v7", # upper bits of S2 bytes ignored
408 "v_mov_b32 v11, 0",
409 ], "v_msad_u8 zero-byte mask and v_lerp_u8 rounding/no-carry"),
410 ]
411
412 # 14. v_qsad_pk_u16_u8, v_mqsad_pk_u16_u8, v_mqsad_u32_u8
413 cases += [
414 _valu4_case("valu_qsad_mqsad", "v_qsad_mqsad_pk_u16", [
415 "v_mov_b32 v2, 0x40302010", "v_mov_b32 v3, 0x80706050",
416 "v_mov_b32 v4, 0x00150025", # S1 has two zero bytes for mqsad
417 "v_mov_b32 v6, 0xfffe0005", "v_mov_b32 v7, 0xfff00100",
418 "v_qsad_pk_u16_u8 v[8:9], v[2:3], v4, v[6:7]",
419 "v_mqsad_pk_u16_u8 v[10:11], v[2:3], v4, v[6:7]",
420 ], "v_qsad_pk_u16_u8 and v_mqsad_pk_u16_u8 with 16-bit wrap and zero S1 bytes"),
421 _valu4_case("valu_qsad_mqsad", "v_mqsad_u32_u8", [
422 "v_mov_b32 v2, 0x40302010", "v_mov_b32 v3, 0x80706050",
423 "v_mov_b32 v4, 0x00150025",
424 "v_mov_b32 v12, 0xfffffffe", "v_mov_b32 v13, 10",
425 "v_mov_b32 v14, 20", "v_mov_b32 v15, 0xffffffff",
426 "v_mqsad_u32_u8 v[8:11], v[2:3], v4, v[12:15]",
427 ], "v_mqsad_u32_u8 four 32-bit accumulators with wrap"),
428 ]
429
430 # 15. v_mul_hi_u32_u24, v_mul_hi_i32_i24, v_lshrrev_b64, v_ashrrev_i64
431 cases += [
432 _valu4_case("valu_mul24_sh64", "v_mul_hi_24", [
433 "v_mov_b32 v1, 0xabffffff", "v_mov_b32 v2, 0xcdffffff",
434 "v_mul_hi_u32_u24 v8, v1, v2", # upper 8 bits ignored
435 "v_mul_hi_i32_i24 v9, v1, v2", # (-1)*(-1) >> 32 = 0
436 "v_mov_b32 v3, 0x12800000", "v_mov_b32 v4, 0x347fffff",
437 "v_mul_hi_i32_i24 v10, v3, v4", # (-2^23)*(2^23-1) >> 32
438 "v_mul_hi_u32_u24 v11, v3, v4",
439 ], "v_mul_hi_u32_u24 and v_mul_hi_i32_i24 (upper 8 bits ignored)"),
440 _valu4_case("valu_mul24_sh64", "v_lshr_ashr_64", [
441 "v_mov_b32 v2, 0x12345678", "v_mov_b32 v3, 0x87654321",
442 "v_mov_b32 v1, 36",
443 "v_lshrrev_b64 v[8:9], v1, v[2:3]",
444 "v_ashrrev_i64 v[10:11], v1, v[2:3]",
445 ], "v_lshrrev_b64 and v_ashrrev_i64 shift=36"),
446 _valu4_case("valu_mul24_sh64", "v_lshr_ashr_64_mod64", [
447 "v_mov_b32 v2, 0x12345678", "v_mov_b32 v3, 0x87654321",
448 "v_mov_b32 v1, 68", # 68 & 63 = 4
449 "v_lshrrev_b64 v[8:9], v1, v[2:3]",
450 "v_ashrrev_i64 v[10:11], v1, v[2:3]",
451 ], "v_lshrrev_b64 and v_ashrrev_i64 shift masked to 6 bits"),
452 ]
453
454 # 16. v_mad_u16 / v_mad_i16 (clamp, op_sel, kept half)
455 cases += [
456 _valu4_case("valu_mad16", "v_mad_u16_i16_clamp_opsel", [
457 "v_mov_b32 v1, 0x80000300", "v_mov_b32 v2, 0x00020200", "v_mov_b32 v3, 0x00010010",
458 f"v_mov_b32 v8, 0x{SENTINEL:08x}",
459 f"v_mov_b32 v9, 0x{SENTINEL:08x}",
460 f"v_mov_b32 v10, 0x{SENTINEL:08x}",
461 f"v_mov_b32 v11, 0x{SENTINEL:08x}",
462 "v_mad_u16 v8, v1, v2, v3 clamp", # 0x300*0x200+0x10 = 0x60010 -> 0xffff
463 "v_mad_u16 v9, v1, v2, v3", # wraps to 0x0010, hi kept
464 "v_mad_i16 v10, v1, v2, v3 op_sel:[1,1,1,0] clamp", # (-32768)*2 + 1 = -65535 -> 0x8000
465 "v_mad_i16 v11, v1, v2, v3 op_sel:[0,0,0,1] clamp", # 0x300*0x200+0x10 -> 0x7fff in hi, lo kept
466 ], "v_mad_u16 / v_mad_i16 clamp, op_sel and untouched destination half"),
467 ]
468
469 # 17. v_cvt_f16_u16 / v_cvt_f16_i16 / v_cvt_u16_f16 / v_cvt_i16_f16 (kept half, NaN, inf)
470 cases += [
471 _valu4_case("valu_cvt_16", "v_cvt_u16_i16_f16_e64_nan_inf", [
472 "v_mov_b32 v1, 0x00007e00", # +qNaN
473 "v_mov_b32 v2, 0x0000fe00", # -qNaN
474 "v_mov_b32 v3, 0x00007c00", # +inf
475 "v_mov_b32 v4, 0x0000fc00", # -inf
476 f"v_mov_b32 v8, 0x{SENTINEL:08x}",
477 f"v_mov_b32 v9, 0x{SENTINEL:08x}",
478 f"v_mov_b32 v10, 0x{SENTINEL:08x}",
479 f"v_mov_b32 v11, 0x{SENTINEL:08x}",
480 "v_cvt_u16_f16_e64 v8, v1", # +qNaN -> 0, check high half
481 "v_cvt_i16_f16_e64 v9, v2", # -qNaN -> 0, check high half
482 "v_cvt_u16_f16_e64 v10, v3", # +inf -> 0xffff, check high half
483 "v_cvt_i16_f16_e64 v11, v4", # -inf -> 0x8000, check high half
484 ], "v_cvt_u16/i16_f16_e64 on +-qNaN and +-inf (high half behavior)"),
485 _valu4_case("valu_cvt_16", "v_cvt_f16_u16_i16_e64_keep", [
486 "v_mov_b32 v1, 0x0000fff0", # 65520 -> +inf (0x7c00)
487 "v_mov_b32 v2, 0x00008000", # -32768 -> -32768.0 (0xf800)
488 "v_mov_b32 v3, 0x0000002a", # 42 -> 42.0 (0x5140)
489 "v_mov_b32 v4, 0x00007fff", # 32767 -> 32768.0 (0x7800)
490 f"v_mov_b32 v8, 0x{SENTINEL:08x}",
491 f"v_mov_b32 v9, 0x{SENTINEL:08x}",
492 f"v_mov_b32 v10, 0x{SENTINEL:08x}",
493 f"v_mov_b32 v11, 0x{SENTINEL:08x}",
494 "v_cvt_f16_u16_e64 v8, v1",
495 "v_cvt_f16_i16_e64 v9, v2",
496 "v_cvt_f16_u16_e64 v10, v3",
497 "v_cvt_f16_i16_e64 v11, v4",
498 ], "v_cvt_f16_u16/i16_e64 overflow to +inf and high half behavior"),
499 ]
500
501 # 18. v_cvt_flr_i32_f32 / v_cvt_rpi_i32_f32 (exact floor(x+0.5) + signed NaN; v_cvt_i32_f32 control)
502 cases += [
503 _valu4_case("valu_cvt_flr_rpi", "v_cvt_rpi_precision", [
504 "v_mov_b32 v1, 0x3effffff", # 0.49999997 (f32(x+0.5)==1.0, exact floor(x+0.5)==0)
505 "v_mov_b32 v2, 0x4b000001", # 8388609.0 (f32(x+0.5)==8388610.0, exact==8388609)
506 "v_mov_b32 v3, 0x4b7fffff", # 16777215.0 (f32(x+0.5)==16777216.0, exact==16777215)
507 "v_mov_b32 v4, 0xbf000000", # -0.5 -> floor(-0.5 + 0.5) = 0
508 "v_cvt_rpi_i32_f32 v8, v1",
509 "v_cvt_rpi_i32_f32 v9, v2",
510 "v_cvt_rpi_i32_f32 v10, v3",
511 "v_cvt_rpi_i32_f32 v11, v4",
512 ], "v_cvt_rpi_i32_f32 exact floor(x+0.5) vs binary32 x+0.5"),
513 _valu4_case("valu_cvt_flr_rpi", "v_cvt_flr_rpi_nan_inf", [
514 "v_mov_b32 v1, 0x7fc00000", # +qNaN
515 "v_mov_b32 v2, 0xffc00000", # -qNaN
516 "v_cvt_flr_i32_f32 v8, v1",
517 "v_cvt_flr_i32_f32 v9, v2",
518 "v_cvt_rpi_i32_f32 v10, v1",
519 "v_cvt_rpi_i32_f32 v11, v2",
520 ], "v_cvt_flr_i32_f32 / v_cvt_rpi_i32_f32 on +qNaN and -qNaN"),
521 _valu4_case("valu_cvt_flr_rpi", "v_cvt_i32_f32_nan_control", [
522 "v_mov_b32 v1, 0x7fc00000", # +qNaN
523 "v_mov_b32 v2, 0xffc00000", # -qNaN
524 "v_mov_b32 v3, 0x7f800001", # +sNaN
525 "v_mov_b32 v4, 0xff800001", # -sNaN
526 "v_cvt_i32_f32 v8, v1",
527 "v_cvt_i32_f32 v9, v2",
528 "v_cvt_i32_f32 v10, v3",
529 "v_cvt_i32_f32 v11, v4",
530 ], "control: v_cvt_i32_f32 returns 0 for every NaN"),
531 _valu4_case("valu_cvt_flr_rpi", "v_cvt_flr_edges", [
532 "v_mov_b32 v1, 0xbf800001", # -1.0000001 -> -2
533 "v_mov_b32 v2, 0x7f800000", # +inf -> INT_MAX
534 "v_mov_b32 v3, 0xff800000", # -inf -> INT_MIN
535 "v_mov_b32 v4, 0x4f000000", # +2^31 -> INT_MAX
536 "v_cvt_flr_i32_f32 v8, v1",
537 "v_cvt_flr_i32_f32 v9, v2",
538 "v_cvt_flr_i32_f32 v10, v3",
539 "v_cvt_flr_i32_f32 v11, v4",
540 ], "v_cvt_flr_i32_f32 negative fraction, infinities and 2^31 saturation"),
541 ]
542
543 # 19. v_cvt_pknorm_i16_f32 / v_cvt_pknorm_u16_f32 (NaN, inf, out-of-range, ties)
544 cases += [
545 _valu4_case("valu_cvt_pknorm", "v_cvt_pknorm_nan_inf", [
546 "v_mov_b32 v1, 0x7fc00000", # +qNaN
547 "v_mov_b32 v2, 0xffc00000", # -qNaN
548 "v_mov_b32 v3, 0x7f800000", # +inf
549 "v_mov_b32 v4, 0xff800000", # -inf
550 "v_cvt_pknorm_i16_f32 v8, v1, v2",
551 "v_cvt_pknorm_u16_f32 v9, v1, v2",
552 "v_cvt_pknorm_i16_f32 v10, v3, v4",
553 "v_cvt_pknorm_u16_f32 v11, v3, v4",
554 ], "v_cvt_pknorm_i16/u16_f32 on +-qNaN and +-inf"),
555 _valu4_case("valu_cvt_pknorm", "v_cvt_pknorm_ties", [
556 "v_mov_b32 v1, 0x3f000000", # 0.5 -> 0.5*32767 = 16383.5 (RNE=16384), 0.5*65535 = 32767.5 (RNE=32768)
557 "v_mov_b32 v2, 0xbf000000", # -0.5 -> -16383.5 (RNE=-16384), u16 -> 0
558 "v_mov_b32 v3, 0x3f800000", # 1.0 -> 32767 / 65535
559 "v_mov_b32 v4, 0xbf800000", # -1.0 -> -32767 (0x8001) / 0
560 "v_cvt_pknorm_i16_f32 v8, v1, v2",
561 "v_cvt_pknorm_u16_f32 v9, v1, v2",
562 "v_cvt_pknorm_i16_f32 v10, v3, v4",
563 "v_cvt_pknorm_u16_f32 v11, v3, v4",
564 ], "v_cvt_pknorm_i16/u16_f32 ties at +-0.5 and +-1.0 endpoints"),
565 ]
566
567 return cases
568
569
570def _translate_case(work, case):
571 os.makedirs(os.path.join(work, "disasm"), exist_ok=True)
572 name = f"ps_int_hw_{case.name}"
573 src = os.path.join(work, "disasm", name + ".s")
574 body = case.lines(wave=32) + ["exp mrt0 v8, v9, v10, v11 done vm", "s_endpgm"]
575 with open(src, "w", encoding="utf-8", newline="\n") as f:
576 f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in body))
577 with open(os.path.join(work, name + ".dxbc"), "wb") as f:
578 f.write(STUB_DXBC)
579 with warnings.catch_warnings():
580 warnings.simplefilter("ignore", ResourceWarning)
581 spv = rdna2spirv.translate(src)
582 return list(spirv_mini_interp.run_fragment(spv)["%out_mrt0"])
583
584
585def run_translator(cases):
586 out = {}
587 with tempfile.TemporaryDirectory(prefix="int_hw_probe_") as work:
588 for case in cases:
589 try:
590 out[case.name] = _translate_case(work, case)
591 except Exception as e:
592 out[case.name] = f"error: {type(e).__name__}: {e}"
593 return out
594
595
596def run_hw(cases, arch=None, waves=(32, 64)):
597 from hw_oracle import asm, runner # noqa: E402
598 oracle = runner.open_oracle(arch=arch)
599 try:
600 device = oracle.device
601 per_wave = {}
602 for wave in waves:
603 kernels = [asm.Kernel(case.lines(wave=wave), wave=wave, threads=1, words=4) for case in cases]
604 res = oracle.run(kernels, words=4)
605 per_wave[wave] = {case.name: r for case, r in zip(cases, res)}
606 return device, per_wave
607 finally:
608 oracle.close()
609
610
611def _fmt_words(w):
612 if isinstance(w, list):
613 return " ".join(f"0x{x:08x}" for x in w)
614 return str(w)
615
616
617def self_test():
618 cases = build_cases()
619 names = [c.name for c in cases]
620 assert len(names) == len(set(names)), "duplicate case names"
621 for name in KNOWN_DIVERGENCES:
622 assert name in names, f"unknown KNOWN_DIVERGENCES key: {name}"
623 res = run_translator(cases)
624 errors = {k: v for k, v in res.items() if not isinstance(v, list)}
625 assert not errors, f"translator errors: {errors}"
626 print(f"self-test: {len(cases)} cases across {len({c.group for c in cases})} groups translated and ran on CPU OK")
627 return 0
628
629
630def main(argv=None):
631 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
632 ap.add_argument("--oracle", choices=("translator", "hw", "both"), default="translator")
633 ap.add_argument("--wave", choices=("32", "64", "both"), default="both")
634 ap.add_argument("--group", action="append", default=[], help="run only named group(s)")
635 ap.add_argument("--hw-arch", default=None, help="override GPU architecture for hw_oracle")
636 ap.add_argument("--list-groups", action="store_true")
637 ap.add_argument("--strict", action="store_true", help="treat known translator divergences as failures")
638 ap.add_argument("--json", dest="json_out", default=None, help="write raw results to a JSON file")
639 ap.add_argument("--self-test", action="store_true")
640 args = ap.parse_args(argv)
641
642 if args.self_test:
643 return self_test()
644
645 cases = build_cases()
646 groups = []
647 for c in cases:
648 if c.group not in groups:
649 groups.append(c.group)
650 if args.list_groups:
651 for g in groups:
652 n = sum(1 for c in cases if c.group == g)
653 print(f"{g:<22} ({n} cases)")
654 return 0
655
656 if args.group:
657 unknown = [g for g in args.group if g not in groups]
658 if unknown:
659 print(f"unknown group(s): {', '.join(unknown)}", file=sys.stderr)
660 return 2
661 want = set(args.group)
662 cases = [c for c in cases if c.group in want]
663
664 waves = (32, 64) if args.wave == "both" else (int(args.wave),)
665 tr_res = run_translator(cases) if args.oracle in ("translator", "both") else None
666 hw_device, hw_res = None, None
667 if args.oracle in ("hw", "both"):
668 from hw_oracle import runner # noqa: E402
669 try:
670 hw_device, hw_res = run_hw(cases, arch=args.hw_arch, waves=waves)
671 except runner.Unavailable as e:
672 print(f"hardware oracle unavailable: {e}", file=sys.stderr)
673 return 77
674 print(f"hardware oracle: {hw_device} (waves: {','.join(str(w) for w in waves)})")
675
676 mismatches = 0
677 known_diffs = 0
678 wave_diffs = 0
679 records = []
680 for c in cases:
681 tr = tr_res[c.name] if tr_res is not None else None
682 h32 = hw_res[32][c.name] if hw_res and 32 in hw_res else None
683 h64 = hw_res[64][c.name] if hw_res and 64 in hw_res else None
684 hw_ref = h32 if h32 is not None else h64
685 status = "OK"
686 tag = None
687 if h32 is not None and h64 is not None and h32 != h64:
688 status = "WAVE_DIFF"
689 wave_diffs += 1
690 elif (tr is not None and not isinstance(tr, list)) or (hw_ref is not None and not isinstance(hw_ref, list)):
691 status = "ERROR"
692 mismatches += 1
693 elif tr is not None and hw_ref is not None and tr != hw_ref:
694 known = KNOWN_DIVERGENCES.get(c.name)
695 if known and hw_ref == known[1]:
696 status = "KNOWN_DIFF"
697 tag = known[0]
698 known_diffs += 1
699 else:
700 status = "MISMATCH"
701 mismatches += 1
702 records.append({
703 "group": c.group, "name": c.name, "note": c.note, "status": status, "known_tag": tag,
704 "translator": tr, "hw_w32": h32, "hw_w64": h64,
705 })
706 if status != "OK" or args.oracle != "both":
707 label = f"{status}:{tag}" if tag else status
708 print(f"[{label:<22}] {c.group}/{c.name}: {c.note}")
709 if h32 is not None:
710 print(f" hw_w32: {_fmt_words(h32)}")
711 if h64 is not None and h64 != h32:
712 print(f" hw_w64: {_fmt_words(h64)}")
713 if tr is not None:
714 print(f" transl: {_fmt_words(tr)}")
715
716 total = len(cases)
717 matched = total - mismatches - known_diffs - wave_diffs
718 print(f"summary: {total} cases: {matched} match, {known_diffs} known divergence, "
719 f"{mismatches} unexpected mismatch, {wave_diffs} wave32/64 diff")
720
721 if args.json_out:
722 out_path = os.path.abspath(args.json_out)
723 if os.path.isdir(out_path):
724 print(f"ERROR: --json path is a directory: {out_path}", file=sys.stderr)
725 return 2
726 parent = os.path.dirname(out_path)
727 if parent:
728 os.makedirs(parent, exist_ok=True)
729 with open(out_path, "w", encoding="utf-8", newline="\n") as f:
730 json.dump({"device": hw_device, "waves": list(waves), "cases": records}, f, indent=2)
731 f.write("\n")
732
733 if mismatches or wave_diffs or (args.strict and known_diffs):
734 return 1
735 return 0
736
737
738if __name__ == "__main__":
739 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
740 sys.stdout.reconfigure(errors="replace")
741 except (AttributeError, ValueError, OSError):
742 pass
743 sys.exit(main())
diff --git a/tools/lds_fuzz.py b/tools/lds_fuzz.py
index 6b3bb4ca8..e2be8b9b2 100644
--- a/tools/lds_fuzz.py
+++ b/tools/lds_fuzz.py
@@ -108,6 +108,7 @@ PERTURBATIONS = {
108 "swizzle_quad_reversed": ("swizzle", "the quad-permute selectors are taken in reverse lane order"), 108 "swizzle_quad_reversed": ("swizzle", "the quad-permute selectors are taken in reverse lane order"),
109 "swizzle_or_xor_swapped": ("swizzle", "the bit-mask or and xor fields are swapped"), 109 "swizzle_or_xor_swapped": ("swizzle", "the bit-mask or and xor fields are swapped"),
110 "permute_no_zero": ("permute", "ds_permute_b32 leaves an unwritten lane's register alone instead of writing 0"), 110 "permute_no_zero": ("permute", "ds_permute_b32 leaves an unwritten lane's register alone instead of writing 0"),
111 "permute_lowest_wins": ("permute", "ds_permute_b32 lets the lowest active source lane win a collision"),
111} 112}
112PERTURB = set() 113PERTURB = set()
113 114
@@ -382,13 +383,13 @@ class Program:
382 "offset": rng.choice([0, 0, 4 * rng.randrange(0, 64)]), "src": rng.choice(POOL), 383 "offset": rng.choice([0, 0, 4 * rng.randrange(0, 64)]), "src": rng.choice(POOL),
383 "dst": rng.choice(POOL), "exec": self.exec_mask()} 384 "dst": rng.choice(POOL), "exec": self.exec_mask()}
384 if kind == "permute": 385 if kind == "permute":
385 # an odd multiplier makes the lane -> lane map a bijection in a 32- and in a 64-lane group, so no two 386 # allow both odd (bijective) and even (colliding) multipliers; RDNA2 hw (gfx1030, SHADER-133) and gfx1150
386 # lanes send to the same lane and the result doesn't depend on which write wins 387 # confirm the highest active source lane wins a collision, unaddressed active lanes get 0, halves separate
387 return {"kind": kind, "mul": rng.randrange(1, 64, 2), "add": rng.randrange(0, 64), 388 return {"kind": kind, "mul": rng.randrange(0, 64), "add": rng.randrange(0, 64),
388 "offset": rng.choice([0, 0, 4 * rng.randrange(0, 64)]), "src": rng.choice(POOL), 389 "offset": rng.choice([0, 0, 4 * rng.randrange(0, 64)]), "src": rng.choice(POOL),
389 "dst": rng.choice(POOL), "exec": self.exec_mask(), 390 "dst": rng.choice(POOL), "exec": self.exec_mask(),
390 "hyp": "the ISA text: only active lanes send, a lane nobody sends to gets 0, each 32-lane half " 391 "hyp": "only active lanes send, highest active sender wins collisions, a lane nobody sends to "
391 "is separate"} 392 "gets 0, each 32-lane half is separate (measured on gfx1030 SHADER-133 and gfx1150)"}
392 raise ValueError(kind) 393 raise ValueError(kind)
393 394
394 # ---- the program text ---- 395 # ---- the program text ----
@@ -681,11 +682,12 @@ class Program:
681 for t, v in new.items(): 682 for t, v in new.items():
682 regs[t][op["dst"]] = v 683 regs[t][op["dst"]] = v
683 elif k == "permute": 684 elif k == "permute":
684 # forward permute: an active lane sends its data to lane (addr + offset) / 4 of its 32-lane group, an 685 # forward scatter within each 32-lane half: active lanes send to lane (addr + offset) / 4 of their 32-lane
685 # active lane gets what was sent to it, or 0 686 # group; highest-numbered active source wins collisions; active destination lanes nobody targets get 0
686 src = [regs[t][op["src"]] for t in range(T)] 687 src = [regs[t][op["src"]] for t in range(T)]
687 sent = {} 688 sent = {}
688 for t in range(T): 689 lanes = range(T - 1, -1, -1) if "permute_lowest_wins" in PERTURB else range(T)
690 for t in lanes:
689 if act[t]: 691 if act[t]:
690 word = ((t * op["mul"] + op["add"]) * 4 + op["offset"]) >> 2 692 word = ((t * op["mul"] + op["add"]) * 4 + op["offset"]) >> 2
691 sent[(t & ~31) | (word & 31)] = src[t] 693 sent[(t & ~31) | (word & 31)] = src[t]
@@ -739,7 +741,7 @@ def translate(progs, work, emulate):
739 for p in progs: 741 for p in progs:
740 text = p.asm() 742 text = p.asm()
741 asm_path = work / (p.name + ".asm") 743 asm_path = work / (p.name + ".asm")
742 asm_path.write_text(text, encoding="utf-8") 744 asm_path.write_text(text, encoding="utf-8", newline="\n")
743 cmd = mc + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-show-encoding"] 745 cmd = mc + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-show-encoding"]
744 if p.wave == 64: 746 if p.wave == 64:
745 cmd.append("-mattr=+wavefrontsize64,-wavefrontsize32") 747 cmd.append("-mattr=+wavefrontsize64,-wavefrontsize32")
@@ -747,7 +749,7 @@ def translate(progs, work, emulate):
747 if r.returncode or "error:" in r.stderr: 749 if r.returncode or "error:" in r.stderr:
748 raise RuntimeError(f"{p.name} did not assemble:\n{r.stderr}") 750 raise RuntimeError(f"{p.name} did not assemble:\n{r.stderr}")
749 code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith(".")) 751 code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith("."))
750 (disasm / (p.name + ".s")).write_text(f"; {p.name}\n{code}", encoding="utf-8") 752 (disasm / (p.name + ".s")).write_text(f"; {p.name}\n{code}", encoding="utf-8", newline="\n")
751 (fssm / (p.name + ".fssm")).write_bytes(compute_header(asm_path)) 753 (fssm / (p.name + ".fssm")).write_bytes(compute_header(asm_path))
752 cmd = [sys.executable, "-I", os.path.join(HERE, "rdna2spirv.py"), str(disasm), "--out", str(spirv)] 754 cmd = [sys.executable, "-I", os.path.join(HERE, "rdna2spirv.py"), str(disasm), "--out", str(spirv)]
753 if emulate: 755 if emulate:
@@ -943,7 +945,7 @@ def run_hw(oracle, progs, a, tally, results):
943 print(f" {ops[i]}" + (" ; hypothesis op" if ops[i].get("hyp") else "")) 945 print(f" {ops[i]}" + (" ; hypothesis op" if ops[i].get("hyp") else ""))
944 if a.keep: 946 if a.keep:
945 os.makedirs(a.keep, exist_ok=True) 947 os.makedirs(a.keep, exist_ok=True)
946 Path(a.keep, f"{p.name}_hw.s").write_text("\n".join(p.hw_lines(oracle.arch)) + "\n", encoding="utf-8") 948 Path(a.keep, f"{p.name}_hw.s").write_text("\n".join(p.hw_lines(oracle.arch)) + "\n", encoding="utf-8", newline="\n")
947 print("hardware summary:") 949 print("hardware summary:")
948 for key, st in sorted(stats.items()): 950 for key, st in sorted(stats.items()):
949 print(f" {key}: " + ", ".join(f"{k} {v}" for k, v in st.items())) 951 print(f" {key}: " + ", ".join(f"{k} {v}" for k, v in st.items()))
diff --git a/tools/manifest.py b/tools/manifest.py
index 9c39d9030..7ffa41c10 100644
--- a/tools/manifest.py
+++ b/tools/manifest.py
@@ -22,7 +22,7 @@ DEFAULT = os.path.join(os.path.dirname(__file__), "..", "reports", "manifest.jso
22 22
23 23
24class ManifestError(Exception): 24class ManifestError(Exception):
25 """A manifest that isn't valid JSON or doesn't have the layout create() writes.""" 25 """An input or manifest error that the CLI reports without a traceback."""
26 26
27 27
28def default_jobs() -> int: 28def default_jobs() -> int:
@@ -52,12 +52,32 @@ def below_normal() -> None:
52 k32.SetPriorityClass(k32.GetCurrentProcess(), 0x00004000) # BELOW_NORMAL_PRIORITY_CLASS 52 k32.SetPriorityClass(k32.GetCurrentProcess(), 0x00004000) # BELOW_NORMAL_PRIORITY_CLASS
53 53
54 54
55def sha256(path: str) -> str: 55def _file_stamp(st: os.stat_result) -> tuple[int, int, int]:
56 return st.st_size, st.st_mtime_ns, st.st_ctime_ns
57
58
59def _hash_file(path: str, *, expected_size: int | None = None) -> tuple[int, str]:
60 """Return the size and digest of the same open file, or fail if it changes."""
56 h = hashlib.sha256() 61 h = hashlib.sha256()
57 with open(path, "rb", buffering=0) as f: 62 with open(path, "rb", buffering=0) as f:
58 while chunk := f.read(CHUNK): 63 before = os.fstat(f.fileno())
64 size = before.st_size
65 if expected_size is not None and size != expected_size:
66 raise ManifestError(f"{path}: file size changed before hashing")
67 remaining = size
68 while remaining and (chunk := f.read(min(CHUNK, remaining))):
59 h.update(chunk) 69 h.update(chunk)
60 return h.hexdigest() 70 remaining -= len(chunk)
71 # Compare timestamps from the same handle. Windows can report different times by path.
72 # Compare the path by identity so a replacement of the open file is detected too.
73 if (remaining or _file_stamp(os.fstat(f.fileno())) != _file_stamp(before)
74 or not os.path.samestat(before, os.stat(path))):
75 raise ManifestError(f"{path}: file changed while hashing")
76 return size, h.hexdigest()
77
78
79def sha256(path: str) -> str:
80 return _hash_file(path)[1]
61 81
62 82
63def same_output_path(first: str, second: str) -> bool: 83def same_output_path(first: str, second: str) -> bool:
@@ -114,7 +134,8 @@ def create(game_dir: str, out: str, jobs: int = 1) -> int:
114 if same_output_path(out, path): 134 if same_output_path(out, path):
115 raise ManifestError(f"--out would overwrite the input {path}; " 135 raise ManifestError(f"--out would overwrite the input {path}; "
116 "choose a manifest path that is not one of the hashed files") 136 "choose a manifest path that is not one of the hashed files")
117 total = sum(os.path.getsize(p) for _, p in files) 137 sizes = {path: os.path.getsize(path) for _, path in files}
138 total = sum(sizes.values())
118 entries = {} 139 entries = {}
119 done = count = 0 140 done = count = 0
120 t0 = time.time() 141 t0 = time.time()
@@ -131,7 +152,8 @@ def create(game_dir: str, out: str, jobs: int = 1) -> int:
131 print(f"[{pct:6.1%}] {count}/{len(files)} files {rate:7.0f} MiB/s", flush=True) 152 print(f"[{pct:6.1%}] {count}/{len(files)} files {rate:7.0f} MiB/s", flush=True)
132 153
133 def work(rel: str, path: str) -> tuple[str, int, str]: 154 def work(rel: str, path: str) -> tuple[str, int, str]:
134 return rel, os.path.getsize(path), sha256(path) 155 size, digest = _hash_file(path, expected_size=sizes[path])
156 return rel, size, digest
135 157
136 if jobs == 1: 158 if jobs == 1:
137 for rel, p in files: 159 for rel, p in files:
@@ -148,7 +170,7 @@ def create(game_dir: str, out: str, jobs: int = 1) -> int:
148 os.makedirs(out_dir, exist_ok=True) 170 os.makedirs(out_dir, exist_ok=True)
149 with tempfile.TemporaryDirectory(dir=out_dir) as staging: 171 with tempfile.TemporaryDirectory(dir=out_dir) as staging:
150 staged = os.path.join(staging, "manifest.json") 172 staged = os.path.join(staging, "manifest.json")
151 with open(staged, "w", encoding="utf-8") as f: 173 with open(staged, "w", encoding="utf-8", newline="\n") as f:
152 json.dump({"created": time.strftime("%Y-%m-%d %H:%M:%S"), "files": entries}, f, indent=1) 174 json.dump({"created": time.strftime("%Y-%m-%d %H:%M:%S"), "files": entries}, f, indent=1)
153 os.replace(staged, out) 175 os.replace(staged, out)
154 print(f"{len(entries)} files, {total / 2**30:.1f} GiB -> {out}") 176 print(f"{len(entries)} files, {total / 2**30:.1f} GiB -> {out}")
diff --git a/tools/mem_diff.py b/tools/mem_diff.py
index 2be12e8bd..ebee3554e 100644
--- a/tools/mem_diff.py
+++ b/tools/mem_diff.py
@@ -640,7 +640,7 @@ def run_one(name, prog):
640 dis = os.path.join(tmp, "disasm") 640 dis = os.path.join(tmp, "disasm")
641 os.mkdir(dis) 641 os.mkdir(dis)
642 path = os.path.join(dis, name + ".s") 642 path = os.path.join(dis, name + ".s")
643 with open(path, "w", encoding="utf-8") as f: 643 with open(path, "w", encoding="utf-8", newline="\n") as f:
644 f.write(_listing(prog.lines)) 644 f.write(_listing(prog.lines))
645 with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: 645 with open(os.path.join(tmp, name + ".dxbc"), "wb") as f:
646 f.write(STUB_DXBC) 646 f.write(STUB_DXBC)
diff --git a/tools/meshlet_page.py b/tools/meshlet_page.py
index a2f8508ae..febba1dab 100644
--- a/tools/meshlet_page.py
+++ b/tools/meshlet_page.py
@@ -487,7 +487,7 @@ def main(argv=None):
487 report = json.dumps({"bindings": rows}, indent=2) 487 report = json.dumps({"bindings": rows}, indent=2)
488 if args.json: 488 if args.json:
489 try: 489 try:
490 with open(args.json, "w", encoding="utf-8") as out: 490 with open(args.json, "w", encoding="utf-8", newline="\n") as out:
491 out.write(report + "\n") 491 out.write(report + "\n")
492 except OSError as exc: 492 except OSError as exc:
493 print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr) 493 print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr)
@@ -514,7 +514,7 @@ def main(argv=None):
514 print(json.dumps(total, indent=1)) 514 print(json.dumps(total, indent=1))
515 if args.json: 515 if args.json:
516 try: 516 try:
517 with open(args.json, "w", encoding="utf-8") as fh: 517 with open(args.json, "w", encoding="utf-8", newline="\n") as fh:
518 json.dump({"totals": total, "pages": pages}, fh, indent=1) 518 json.dump({"totals": total, "pages": pages}, fh, indent=1)
519 except OSError as exc: 519 except OSError as exc:
520 print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr) 520 print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr)
diff --git a/tools/mission_tables.py b/tools/mission_tables.py
new file mode 100644
index 000000000..d2da85a93
--- /dev/null
+++ b/tools/mission_tables.py
@@ -0,0 +1,524 @@
1"""Read mission-state tables: 32-byte state records and the 64-byte pool elements they point at.
2
3`docs/mission_logic.md` describes the tables that carry mission structure in the PSIN streams of the script
4archives. This tool is the reader for them. It takes inflated PSIN files (a directory of carved `.bin`
5streams works too) and prints, per file, the number of records, the distinct state keys, the distinct
6archetype and link hashes, and every entity it could resolve to a world transform.
7
8Record, 32 bytes:
9
10 +0 u32 key joaat of the state name, lower-cased first
11 +4 u32 0
12 +8 u32 colB an ascending band-like column; 1 on every record measured here
13 +12 u32 0
14 +16 u32 (u16 kind at the low half, u16 offset at the high half)
15 +20 u32 band an ascending band counter, not always zero (0, 0, 1, 2, 2, ...)
16 +24 u32 (u16 n, u16 n) the entity count, stored twice
17 +28 u32 0
18
19The offset is a byte offset. It is stored in the **high half** of the dword at +16, which is the big end of
20the little-endian word; the low half is `kind`. The two u16s are not byte-swapped: the measured bytes
21`03 00 80 07` resolve kind 3 and offset 0x780, not 0x8007. A record whose offset is outside the file is
22still a record; it simply resolves to no entity.
23
24Pool element, 64 bytes, 16 dwords:
25
26 +0x00 u32 archetype/state hash
27 +0x04 u32 0
28 +0x08 u32 0
29 +0x0C u32 0
30 +0x10 f32 pos.x, pos.y, pos.z (world coordinates in RAGE space, Z up)
31 +0x1C f32 pos.x the first position component, duplicated
32 +0x20 f32 rot.x, rot.y, rot.z
33 +0x2C f32 rot.x the first rotation component, duplicated
34 +0x30 u32 hash repeats the archetype hash on most elements
35 +0x34 u32 linkHash joaat of the lower-cased linked name (a character, for example)
36 +0x38 u32 0 a second hash on some elements, otherwise zero
37 +0x3C u32 0 zero on every element measured here
38
39The duplicated first component is the cheap structural test that separates a real element from a random
4064-byte window. This tool requires it for both the position and the rotation, and finite values in a
41plausible world range. The last two dwords are not required to be zero: a measured minority of elements
42carries a second link hash in the third-last dword. Requiring `+0x38 == +0x3C == 0` would silently drop
43those entities, so the reader keeps them and reports the extra hash as `extra`.
44
45Resolution is two-step, because the measured streams prove two encodings:
46
471. **File-absolute** (the common case): the record's offset is the byte address of the element.
482. **Linked pool** (the family documented as the "next even-tagged pool chunk" rule): inside a PSIN
49 container, a block of records is followed by the block that holds its elements. The record offset is
50 then a 16-byte-unit offset into that pool block: `element = pool_block_base + (offset >> 4)`. The
51 measured family uses offsets such as 0x0, 0xC00, 0x1800, ... while its elements sit 0xC0 bytes apart.
52
53Both addresses are scored when they exist: the one that validates more of the record's `n` slots wins, and
54a tie keeps the file-absolute reading. A slot that fails the duplicated-component test is counted as
55skipped, never reported as an entity. The scoring matters on the pool-relative family, where an offset
56such as 0x3000 can also name an unrelated element elsewhere in the file.
57
58Detection is structural rather than schema-driven so a bare `.bin` works as well as a PSIN container. A
59record chunk is a run of at least two consecutive 32-byte records with the same `kind`; a lone record is
60kept when it has a hash-sized key, a small `colB`, and an offset that already names an element. For PSIN
61input the block table is used to find the linked pool block (skip sub-64-byte blocks and other record
62blocks, then take the first block that starts with a valid element). Bytes outside a record chunk and a
63resolved entity are counted as skipped.
64
65Usage:
66 python -I mission_tables.py <file-or-dir> [--json] [--limit N]
67
68Text output prints one line per file and one line per entity; `--json` writes `{files, summary}` with the
69same numbers and the entity list (hashes as eight lowercase hex digits).
70"""
71import argparse
72import collections
73import json
74import math
75import os
76import struct
77import sys
78
79sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
80try:
81 import psin_index # noqa: E402
82except ImportError: # a bare checkout without the sibling readers: scan raw bytes only
83 psin_index = None
84try:
85 import psin_data # noqa: E402
86except ImportError:
87 psin_data = None
88
89RECORD_SIZE = 32
90ELEMENT_SIZE = 64
91MAX_ENTITIES = 4096 # a sane upper bound for the duplicated u16 count
92MAX_WORLD = 1e7 # positions and rotations outside this are not world transforms
93RECORD_KEY_MIN = 0x10000 # below this a u32 is a small field, not a joaat state key
94POOL_SHIFT = 4 # linked-pool offsets are in 16-byte units
95
96
97def joaat(text):
98 """joaat32 of a lower-cased name (Jenkins one-at-a-time, seed 0)."""
99 h = 0
100 for byte in text.lower().encode("latin-1", "replace"):
101 h = (h + byte) & 0xFFFFFFFF
102 h = (h + (h << 10)) & 0xFFFFFFFF
103 h ^= h >> 6
104 h = (h + (h << 3)) & 0xFFFFFFFF
105 h ^= h >> 11
106 return (h + (h << 15)) & 0xFFFFFFFF
107
108
109def decode_record(blob, at):
110 """Decode the 32-byte record at `at`, or None when the bytes are not a record.
111
112 The only zero fields are +4, +12 and +28; `band` is deliberately not required to be zero (it is an
113 ascending band counter, not a reserved word).
114 """
115 if at < 0 or at + RECORD_SIZE > len(blob):
116 return None
117 key, zero_a, col_b, zero_b, kind_offset, band, duplicated, zero_c = struct.unpack_from("<8I", blob, at)
118 kind = kind_offset & 0xFFFF
119 offset = kind_offset >> 16
120 count_a, count_b = duplicated >> 16, duplicated & 0xFFFF
121 if key < RECORD_KEY_MIN or zero_a or zero_b or zero_c:
122 return None
123 if count_a != count_b or count_a > MAX_ENTITIES:
124 return None
125 return {
126 "offset": at,
127 "key": key,
128 "colB": col_b,
129 "kind": kind,
130 "poolOffset": offset,
131 "band": band,
132 "count": count_a,
133 }
134
135
136def decode_element(blob, at):
137 """Decode the 64-byte pool element at `at`, or None when the layout does not hold."""
138 if at < 0 or at + ELEMENT_SIZE > len(blob):
139 return None
140 words = struct.unpack_from("<16I", blob, at)
141 if words[0] == 0 or words[1] or words[2] or words[3]:
142 return None
143 if words[4] != words[7] or words[8] != words[11]:
144 return None
145 values = struct.unpack_from("<8f", blob, at + 16)
146 if not all(math.isfinite(v) and abs(v) <= MAX_WORLD for v in values):
147 return None
148 return {
149 "offset": at,
150 "archetype": words[0],
151 "pos": list(values[0:3]),
152 "rot": list(values[4:7]),
153 "hash": words[12],
154 "link": words[13],
155 "extra": words[14],
156 }
157
158
159def scan_elements(blob, end):
160 """Every valid pool element that starts in [0, end), keyed by its byte address."""
161 found = {}
162 for at in range(0, max(0, end - ELEMENT_SIZE + 1), 4):
163 element = decode_element(blob, at)
164 if element is not None:
165 found[at] = element
166 return found
167
168
169def find_chunks(blob, end, elements):
170 """Maximal record runs. Returns [{offset, records}] in file order.
171
172 A run is two or more consecutive 32-byte records of the same kind. A lone record survives only when
173 its file-absolute offset already names a valid element, which keeps a synthetic one-record table
174 readable without turning every aligned window in a schema into a table.
175 """
176 covered = bytearray(end)
177 chunks = []
178 at = 0
179 while at + RECORD_SIZE <= end:
180 if covered[at]:
181 at += 4
182 continue
183 first = decode_record(blob, at)
184 if first is None:
185 at += 4
186 continue
187 run = [(at, first)]
188 nxt = at + RECORD_SIZE
189 while nxt + RECORD_SIZE <= end:
190 following = decode_record(blob, nxt)
191 if following is None or following["kind"] != first["kind"]:
192 break
193 run.append((nxt, following))
194 nxt += RECORD_SIZE
195 if len(run) >= 2 or (first["key"] >= 0x1000000 and first["colB"] <= 4
196 and first["poolOffset"] in elements):
197 chunks.append({"offset": at, "records": run})
198 for record_at, _ in run:
199 covered[record_at:record_at + RECORD_SIZE] = b"\x01" * RECORD_SIZE
200 at = nxt
201 else:
202 at += RECORD_SIZE
203 return chunks
204
205
206def record_blocks(blob, blocks):
207 """The indices of blocks that are a whole table of same-kind records."""
208 out = []
209 for index, (_kind, base, size) in enumerate(blocks):
210 if size < RECORD_SIZE * 2 or size % RECORD_SIZE:
211 continue
212 first = decode_record(blob, base)
213 if first is None:
214 continue
215 rows = [decode_record(blob, base + at) for at in range(0, size, RECORD_SIZE)]
216 if all(row is not None and row["kind"] == first["kind"] for row in rows):
217 out.append(index)
218 return out
219
220
221def linked_pool(blob, blocks, block_indices, chunk_at, elements):
222 """The base of the pool block linked to the record block that holds `chunk_at`, or None.
223
224 The element block follows the record block. Sub-64-byte metadata blocks are stepped over; another
225 record block is skipped (its own pool follows it). The first other block must start with a valid
226 element, otherwise this chunk belongs to a pool family this reader does not decode.
227 """
228 if not blocks:
229 return None
230 owner = None
231 for index, (_kind, base, size) in enumerate(blocks):
232 if base <= chunk_at < base + size:
233 owner = index
234 break
235 if owner is None or owner not in block_indices:
236 return None
237 for index in range(owner + 1, len(blocks)):
238 _kind, base, size = blocks[index]
239 if size < ELEMENT_SIZE:
240 continue
241 if index in block_indices:
242 continue
243 return base if base in elements else None
244 return None
245
246
247def resolve(record, elements, pool_base):
248 """Resolve one record to [(address, element)].
249
250 Both the file-absolute address and the linked-pool address are tried when they exist. The one that
251 validates more of the record's `n` slots wins; a tie keeps the file-absolute reading. This matters on
252 the pool-relative family, where an offset such as 0x3000 can also land on an unrelated element in the
253 file and would otherwise shadow the correct pool slot.
254
255 Returns (entities, mode, skipped_slots). mode is "absolute", "pool", "empty" or "unresolved".
256 """
257 count = record["count"]
258 if count == 0:
259 return [], "empty", 0
260 candidates = []
261 if record["poolOffset"] in elements:
262 candidates.append((record["poolOffset"], "absolute"))
263 if pool_base is not None:
264 address = pool_base + (record["poolOffset"] >> POOL_SHIFT)
265 if address in elements:
266 candidates.append((address, "pool"))
267 if not candidates:
268 return [], "unresolved", count
269 best = None
270 for base, mode in candidates:
271 entities = []
272 skipped = 0
273 for slot in range(count):
274 address = base + slot * ELEMENT_SIZE
275 element = elements.get(address)
276 if element is None:
277 skipped += 1
278 else:
279 entities.append((address, element))
280 if best is None or len(entities) > len(best[0]):
281 best = (entities, mode, skipped)
282 entities, mode, skipped = best
283 if not entities:
284 return [], "unresolved", skipped
285 return entities, mode, skipped
286
287
288def parse_blob(blob, name="<memory>"):
289 """Parse one inflated stream (PSIN or bare bytes) into the tool's per-file record."""
290 first_section = len(blob)
291 blocks = []
292 if psin_index is not None and blob[:4] == b"PSIN":
293 parsed = psin_index.parse(blob)
294 if parsed is not None:
295 first_section = min(max(parsed["first_section"], 0), len(blob))
296 if psin_data is not None:
297 try:
298 blocks, _fill = psin_data.block_table(blob, first_section)
299 except (ValueError, struct.error):
300 blocks = []
301 end = first_section if first_section >= RECORD_SIZE else len(blob)
302 elements = scan_elements(blob, end)
303 chunks = find_chunks(blob, end, elements)
304 table_blocks = record_blocks(blob, blocks) if blocks else []
305 if table_blocks:
306 known = {at for chunk in chunks for at, _record in chunk["records"]}
307 for index in table_blocks:
308 _kind, base, size = blocks[index]
309 addresses = list(range(base, base + size, RECORD_SIZE))
310 if any(address in known for address in addresses):
311 continue
312 rows = [(address, decode_record(blob, address)) for address in addresses]
313 if all(row is not None for _address, row in rows):
314 chunks.append({"offset": base, "records": rows})
315 known.update(addresses)
316 chunks.sort(key=lambda chunk: chunk["offset"])
317
318 records = []
319 entity_by_address = {}
320 states = collections.defaultdict(lambda: {"key": 0, "records": 0, "slots": 0, "entities": 0})
321 skipped_slots = 0
322 unresolved = 0
323 for chunk in chunks:
324 pool_base = linked_pool(blob, blocks, table_blocks, chunk["offset"], elements)
325 for _at, record in chunk["records"]:
326 records.append(record)
327 state = states[record["key"]]
328 state["key"] = record["key"]
329 state["records"] += 1
330 found, _mode, skipped = resolve(record, elements, pool_base)
331 skipped_slots += skipped
332 if not found and record["count"]:
333 unresolved += 1
334 for address, element in found:
335 state["slots"] += 1
336 entity_by_address.setdefault(address, element)
337 for state in states.values():
338 state["entities"] = state["slots"]
339
340 entities = [entity_by_address[address] for address in sorted(entity_by_address)]
341 covered = bytearray(end)
342 for chunk in chunks:
343 for at, _record in chunk["records"]:
344 covered[at:at + RECORD_SIZE] = b"\x01" * RECORD_SIZE
345 for address in entity_by_address:
346 covered[address:address + ELEMENT_SIZE] = b"\x01" * ELEMENT_SIZE
347 skipped_bytes = end - sum(covered)
348 trailing = end
349 while trailing > 0 and not covered[trailing - 1]:
350 trailing -= 1
351 trailing_bytes = end - trailing
352
353 return {
354 "file": name,
355 "size": len(blob),
356 "scan_bytes": end,
357 "records": len(records),
358 "chunks": len(chunks),
359 "record_blocks": len(table_blocks),
360 "state_keys": len(states),
361 "entities": len(entities),
362 "entity_slots": sum(state["slots"] for state in states.values()),
363 "unresolved_records": unresolved,
364 "skipped_slots": skipped_slots,
365 "skipped_bytes": skipped_bytes,
366 "trailing_bytes": trailing_bytes,
367 "distinct_archetypes": len({entity["archetype"] for entity in entities}),
368 "distinct_links": len({entity["link"] for entity in entities}),
369 "states": [
370 {
371 "key": state["key"],
372 "records": state["records"],
373 "entities": state["entities"],
374 }
375 for _key, state in sorted(states.items())
376 ],
377 "entity_list": [
378 {
379 "archetype": entity["archetype"],
380 "link": entity["link"],
381 "hash": entity["hash"],
382 "extra": entity["extra"],
383 "pos": entity["pos"],
384 "rot": entity["rot"],
385 "offset": entity["offset"],
386 }
387 for entity in entities
388 ],
389 }
390
391
392def parse_file(path):
393 with open(path, "rb") as handle:
394 blob = handle.read()
395 return parse_blob(blob, os.path.basename(path))
396
397
398def files_in(src):
399 """(path, name) pairs, sorted by name for a directory; one pair for a file."""
400 if os.path.isfile(src):
401 yield src, os.path.basename(src)
402 return
403 for name in sorted(os.listdir(src)):
404 if not name.endswith(".bin"):
405 continue
406 path = os.path.join(src, name)
407 if os.path.isfile(path):
408 yield path, name
409
410
411def collect(src, limit=None):
412 files = []
413 for path, name in files_in(src):
414 record = parse_file(path)
415 record["file"] = name
416 files.append(record)
417 if limit and len(files) >= limit:
418 break
419 return files
420
421
422def summarize(files):
423 """Totals over files; the distinct hash counts are over the union, not a sum of per-file counts."""
424 archetypes = set()
425 links = set()
426 states = set()
427 for record in files:
428 states.update(state["key"] for state in record["states"])
429 archetypes.update(entity["archetype"] for entity in record["entity_list"])
430 links.update(entity["link"] for entity in record["entity_list"])
431 return {
432 "files": len(files),
433 "records": sum(record["records"] for record in files),
434 "chunks": sum(record["chunks"] for record in files),
435 "state_keys": len(states),
436 "entities": sum(record["entities"] for record in files),
437 "entity_slots": sum(record["entity_slots"] for record in files),
438 "distinct_archetypes": len(archetypes),
439 "distinct_links": len(links),
440 "unresolved_records": sum(record["unresolved_records"] for record in files),
441 "skipped_slots": sum(record["skipped_slots"] for record in files),
442 "skipped_bytes": sum(record["skipped_bytes"] for record in files),
443 }
444
445
446def _hex(value):
447 return f"{value:08x}"
448
449
450def _json_record(record):
451 """The same record with hashes formatted as eight hex digits."""
452 out = dict(record)
453 out["states"] = [dict(state, key=_hex(state["key"])) for state in record["states"]]
454 out["entity_list"] = [
455 {
456 "archetype": _hex(entity["archetype"]),
457 "link": _hex(entity["link"]),
458 "hash": _hex(entity["hash"]),
459 "extra": _hex(entity["extra"]),
460 "pos": [round(value, 6) for value in entity["pos"]],
461 "rot": [round(value, 6) for value in entity["rot"]],
462 "offset": entity["offset"],
463 }
464 for entity in record["entity_list"]
465 ]
466 return out
467
468
469def count(text):
470 """--limit: a positive file count."""
471 try:
472 value = int(text)
473 except ValueError:
474 raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None
475 if value < 1:
476 raise argparse.ArgumentTypeError("must be at least 1")
477 return value
478
479
480def main(argv=None):
481 ap = argparse.ArgumentParser(description="Read mission-state tables from inflated PSIN streams.")
482 ap.add_argument("src", help="PSIN file or directory of carved .bin streams")
483 ap.add_argument("--json", action="store_true", help="write the files and summary as JSON")
484 ap.add_argument("--limit", type=count, help="stop after this many files")
485 args = ap.parse_args(argv)
486 if not os.path.exists(args.src):
487 print(f"ERROR: {args.src}: no such file or folder", file=sys.stderr)
488 return 2
489 try:
490 files = collect(args.src, args.limit)
491 except OSError as error:
492 print(f"ERROR: {args.src}: {error}", file=sys.stderr)
493 return 2
494 summary = summarize(files)
495 if args.json:
496 json.dump({"files": [_json_record(record) for record in files], "summary": summary},
497 sys.stdout, indent=1)
498 sys.stdout.write("\n")
499 return 0
500 for record in files:
501 print(f"{record['file']} size={record['size']} records={record['records']} "
502 f"chunks={record['chunks']} states={record['state_keys']} "
503 f"entities={record['entities']} archetypes={record['distinct_archetypes']} "
504 f"links={record['distinct_links']} unresolved={record['unresolved_records']} "
505 f"skipped_slots={record['skipped_slots']} skipped_bytes={record['skipped_bytes']}")
506 for entity in record["entity_list"]:
507 pos = ", ".join(f"{value:.3f}" for value in entity["pos"])
508 rot = ", ".join(f"{value:.3f}" for value in entity["rot"])
509 print(f" entity {_hex(entity['archetype'])} {_hex(entity['link'])} "
510 f"pos=({pos}) rot=({rot}) +0x{entity['offset']:x}")
511 print(f"{summary['files']} files, {summary['records']} records in {summary['chunks']} chunks; "
512 f"{summary['state_keys']} distinct state keys; {summary['entities']} entities "
513 f"({summary['entity_slots']} slots), {summary['distinct_archetypes']} archetypes, "
514 f"{summary['distinct_links']} links; unresolved {summary['unresolved_records']}, "
515 f"skipped slots {summary['skipped_slots']}, skipped bytes {summary['skipped_bytes']}")
516 return 0
517
518
519if __name__ == "__main__":
520 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
521 sys.stdout.reconfigure(errors="replace")
522 except (AttributeError, ValueError, OSError):
523 pass
524 sys.exit(main())
diff --git a/tools/navmesh_decode.py b/tools/navmesh_decode.py
index 7571c2ae9..3b01bc381 100644
--- a/tools/navmesh_decode.py
+++ b/tools/navmesh_decode.py
@@ -1011,7 +1011,7 @@ def main(argv=None):
1011 print("error: %s" % exc, file=sys.stderr) 1011 print("error: %s" % exc, file=sys.stderr)
1012 return 2 1012 return 2
1013 _make_parent(out) 1013 _make_parent(out)
1014 with open(out, "w", encoding="utf-8") as f: 1014 with open(out, "w", encoding="utf-8", newline="\n") as f:
1015 json.dump(summary, f, indent=1, allow_nan=False) 1015 json.dump(summary, f, indent=1, allow_nan=False)
1016 if a.csv: 1016 if a.csv:
1017 write_csv(a.csv, rows) 1017 write_csv(a.csv, rows)
diff --git a/tools/navmesh_index.py b/tools/navmesh_index.py
index 0fa6c7f83..7ad5e0a2d 100644
--- a/tools/navmesh_index.py
+++ b/tools/navmesh_index.py
@@ -198,7 +198,7 @@ def _make_parent(path):
198 198
199def write_outputs(rows, summary, out_path, csv_path): 199def write_outputs(rows, summary, out_path, csv_path):
200 _make_parent(out_path) 200 _make_parent(out_path)
201 with open(out_path, "w", encoding="utf-8") as f: 201 with open(out_path, "w", encoding="utf-8", newline="\n") as f:
202 json.dump({"summary": summary, "pages": rows}, f, indent=1) 202 json.dump({"summary": summary, "pages": rows}, f, indent=1)
203 written = [] 203 written = []
204 if csv_path: 204 if csv_path:
diff --git a/tools/opus_tags.py b/tools/opus_tags.py
index a1395e6ef..4b29c9328 100644
--- a/tools/opus_tags.py
+++ b/tools/opus_tags.py
@@ -4,8 +4,9 @@ awc_opus.py writes <out>/<bank>/<stream id>.ogg with an empty OpusTags header. T
4from two local work products: 4from two local work products:
5 5
6``--names`` awc_names.py CSV (source, bank, stream_id, name, rule). A file is matched by its stream id (the file 6``--names`` awc_names.py CSV (source, bank, stream_id, name, rule). A file is matched by its stream id (the file
7 name) and its bank (the folder path below the Opus folder; if that has no match, the path with its 7 name; awc_opus.py's ``<id>~2.ogg`` for a second stream with the same id gets the same name) and its
8 leading folders removed one at a time, so the Opus folder may hold several archives' outputs). 8 bank (the folder path below the Opus folder; if that has no match, the path with its leading folders
9 removed one at a time, so the Opus folder may hold several archives' outputs).
9``--dialogue`` text_tables.py dialogue CSV (wave, key, label, speaker, text_<lang> ...). A named stream whose name is 10``--dialogue`` text_tables.py dialogue CSV (wave, key, label, speaker, text_<lang> ...). A named stream whose name is
10 a dialogue wave gets that line's label, speaker and subtitles. 11 a dialogue wave gets that line's label, speaker and subtitles.
11 12
@@ -40,7 +41,7 @@ from awc_opus import ogg_page, write_file # noqa: E402
40VENDOR = b"leonida " 41VENDOR = b"leonida "
41MARKUP = re.compile(r"~[^~]*~") 42MARKUP = re.compile(r"~[^~]*~")
42SPACES = re.compile(r"\s+") 43SPACES = re.compile(r"\s+")
43STREAM_FILE = re.compile(r"^([0-9A-Fa-f]{8})\.ogg$") 44STREAM_FILE = re.compile(r"^([0-9A-Fa-f]{8})(?:~\d+)?\.ogg$") # <id>~2 ...: a later stream with the same id
44MAX_PACKET = 255 * 255 - 1 # lacing values of one page: 254 full segments and a final short one 45MAX_PACKET = 255 * 255 - 1 # lacing values of one page: 254 full segments and a final short one
45 46
46 47
diff --git a/tools/page_index.py b/tools/page_index.py
index 41d9f3783..059f4d91f 100644
--- a/tools/page_index.py
+++ b/tools/page_index.py
@@ -316,7 +316,7 @@ def summarise(pages, mode, source):
316 316
317 317
318def write_json(path, pages, summary): 318def write_json(path, pages, summary):
319 with open(path, "w", encoding="utf-8") as f: 319 with open(path, "w", encoding="utf-8", newline="\n") as f:
320 json.dump({"summary": summary, "pages": pages}, f, indent=1) 320 json.dump({"summary": summary, "pages": pages}, f, indent=1)
321 321
322 322
diff --git a/tools/pe_inspect.py b/tools/pe_inspect.py
index 148318c15..aabb42765 100644
--- a/tools/pe_inspect.py
+++ b/tools/pe_inspect.py
@@ -78,7 +78,9 @@ class PeImage:
78 magic = struct.unpack_from("<H", data, opt)[0] 78 magic = struct.unpack_from("<H", data, opt)[0]
79 if magic not in (0x10B, 0x20B): 79 if magic not in (0x10B, 0x20B):
80 raise PeFormatError(f"unknown optional header magic 0x{magic:x}") 80 raise PeFormatError(f"unknown optional header magic 0x{magic:x}")
81 if opt + 72 > len(data): # the fixed fields read below end with DllCharacteristics at +70 81 # The declared optional header must contain every fixed field we read,
82 # and the complete declared header must fit inside the file.
83 if opt_size < 72 or opt + opt_size > len(data):
82 raise PeFormatError("truncated optional header") 84 raise PeFormatError("truncated optional header")
83 self.is64 = magic == 0x20B 85 self.is64 = magic == 0x20B
84 self.entry_rva = struct.unpack_from("<I", data, opt + 16)[0] 86 self.entry_rva = struct.unpack_from("<I", data, opt + 16)[0]
@@ -458,9 +460,9 @@ def main(argv: list[str] | None = None) -> int:
458 rc = 1 460 rc = 1
459 continue 461 continue
460 try: 462 try:
461 with open(json_path, "w", encoding="utf-8") as f: 463 with open(json_path, "w", encoding="utf-8", newline="\n") as f:
462 json.dump(r, f, indent=1) 464 json.dump(r, f, indent=1)
463 with open(md_path, "w", encoding="utf-8") as f: 465 with open(md_path, "w", encoding="utf-8", newline="\n") as f:
464 f.write(to_markdown(r)) 466 f.write(to_markdown(r))
465 except OSError as e: 467 except OSError as e:
466 print(f"{img}: cannot write report ({e.strerror or e})", file=sys.stderr) 468 print(f"{img}: cannot write report ({e.strerror or e})", file=sys.stderr)
diff --git a/tools/pe_shader_containers.py b/tools/pe_shader_containers.py
new file mode 100644
index 000000000..5b4d39565
--- /dev/null
+++ b/tools/pe_shader_containers.py
@@ -0,0 +1,272 @@
1"""Inventory the DXBC shader containers embedded in a PE image, outside `shaders.rpf`.
2
3The package ships shader programs in two places: the game's own containers inside `shaders.rpf`, which
4`tools/shader_carve.py` recovers, and containers embedded in DLLs. This tool scans any binary for the latter,
5validates each container's chunk table, reads the `ILDN` module name, and reports what each container carries:
6
7* `has_xbch`: the `DXIL` chunk's `XDAT` tag 0x0d starts with `XBCH`. This is the console program:
8 `tools/fssm_unpack.py` decompresses it to `FSSM` and the game's RDNA2 pipeline (disasm + `rdna2spirv.py`)
9 translates it, exactly like a shader from `shaders.rpf`. `docs/embedded_shaders.md` has the measurement.
10* `has_fspx`: the `ACCC` chunk starts with `FSPX`. That is the FidelityFX AOT compute program, a different
11 format (`tools/fspx_unpack.py`, `docs/fspx.md`).
12* `has_bitcode`: the `DXIL` chunk contains an LLVM bitcode magic (`BC C0 DE`). Some containers carry both the
13 bitcode and the console `XBCH` record; the console runtime uses the latter.
14
15Usage:
16 python -I pe_shader_containers.py <image> [<image> ...] [--json FILE] [--extract DIR] [--verbose]
17
18`--json` writes the per-container records (offset, size, sha256, chunk list, name, flags). `--extract` writes
19each container as `<module>.dxbc` plus an `index.json` whose entries the translator reads (`stage: "cs"`), so the
20next step can be `fssm_unpack.py <DIR>`: nothing is extracted unless asked for, and extracted shaders are game
21data that must stay in the user's work folder, never in the repository. Nothing here prints shader bytes.
22
23Standard library only; reads files, never runs them.
24"""
25
26from __future__ import annotations
27
28import argparse
29import hashlib
30import json
31import os
32import re
33import struct
34import sys
35
36DXBC = b"DXBC"
37XDAT = b"XDAT"
38XBCH = b"XBCH"
39FSPX = b"FSPX"
40BITCODE = b"BC\xc0\xde"
41MAX_CHUNKS = 64 # a container with more chunks is not one this parser accepts
42NAME_LIMIT = 4096 # longer than any ILDN path seen; stops a malformed length from reading the image
43SAFE_NAME = re.compile(r"[^A-Za-z0-9_.-]+")
44
45
46class ContainerError(ValueError):
47 """The bytes at this offset do not form a DXBC container this parser accepts."""
48
49
50def u32(data: bytes, offset: int) -> int:
51 return struct.unpack_from("<I", data, offset)[0]
52
53
54def parse_container(data: bytes, offset: int):
55 """Return (total_size, chunks) for the container at `offset`, or raise ContainerError.
56
57 The package's containers differ from DXC's in one place only: the chunk table is a u32 offset array at
58 +32 (count at +28), and each chunk starts with its fourcc and a u32 size. `tools/fspx_unpack.parts()`
59 reads the same shape. The checks below reject the four-byte `DXBC` immediates and error strings that
60 occur in ordinary code.
61 """
62 if data[offset : offset + 4] != DXBC:
63 raise ContainerError("no DXBC magic")
64 if offset + 32 > len(data):
65 raise ContainerError("truncated header")
66 total, count = u32(data, offset + 24), u32(data, offset + 28)
67 if not 32 < total <= len(data) - offset:
68 raise ContainerError(f"total size {total} does not fit the image")
69 if not 0 < count <= MAX_CHUNKS:
70 raise ContainerError(f"implausible chunk count {count}")
71 table_end = 32 + 4 * count
72 if table_end > total:
73 raise ContainerError("chunk table past the container")
74 chunks = []
75 for k in range(count):
76 start = u32(data, offset + 32 + 4 * k)
77 if not table_end <= start <= total - 8:
78 raise ContainerError(f"chunk {k} offset {start} outside the container")
79 fourcc = data[offset + start : offset + start + 4]
80 size = u32(data, offset + start + 4)
81 if start + 8 + size > total:
82 raise ContainerError(f"chunk {k} payload past the container")
83 if start % 4:
84 raise ContainerError(f"chunk {k} offset {start} not 4-byte aligned")
85 if not all(0x20 <= b < 0x7F for b in fourcc):
86 raise ContainerError(f"chunk {k} fourcc is not printable")
87 chunks.append((fourcc, start, size))
88 starts = [start for _, start, _ in chunks]
89 if starts != sorted(starts) or len(set(starts)) != len(starts):
90 raise ContainerError("chunk table is not sorted and unique")
91 if not chunks or max(start + 8 + size for _, start, size in chunks) != total:
92 raise ContainerError("the last chunk does not end at the container size")
93 return total, chunks
94
95
96def chunk_payload(data: bytes, offset: int, chunk) -> bytes:
97 _, start, size = chunk
98 return data[offset + start + 8 : offset + start + 8 + size]
99
100
101def module_name(ildn: bytes) -> str | None:
102 """The module name in an `ILDN` part: `00 00 <u16 length> <PDB path>`; basename without `.pdb`."""
103 if len(ildn) < 4:
104 return None
105 length = struct.unpack_from("<H", ildn, 2)[0]
106 path = ildn[4 : 4 + min(length, NAME_LIMIT)].split(b"\0", 1)[0]
107 base = path.replace(b"\\", b"/").rsplit(b"/", 1)[-1].decode("latin-1")
108 return base[:-4] if base.lower().endswith(".pdb") else base or None
109
110
111def xdat_tags(dxil: bytes) -> list[dict]:
112 """The XDAT entries of a `DXIL` part, as {tag, size, magic} with the first four payload bytes as ASCII."""
113 start = dxil.find(XDAT)
114 if start < 0 or start + 12 > len(dxil):
115 return []
116 count, _header = struct.unpack_from("<II", dxil, start + 4)
117 if count > 256:
118 return []
119 out = []
120 for k in range(count):
121 at = start + 12 + 12 * k
122 if at + 12 > len(dxil):
123 break
124 tag, offset, size = struct.unpack_from("<III", dxil, at)
125 if offset + size > len(dxil):
126 continue
127 magic = dxil[offset : offset + 4]
128 out.append(
129 {
130 "tag": tag,
131 "size": size,
132 "magic": magic.decode("latin-1")
133 if all(0x20 <= b < 0x7F for b in magic)
134 else "",
135 }
136 )
137 return out
138
139
140def inspect(data: bytes, image: str) -> tuple[list[dict], list[int]]:
141 """Every valid container in `data`, and the offsets of `DXBC` hits that failed validation."""
142 found, rejected = [], []
143 i = 0
144 while True:
145 i = data.find(DXBC, i)
146 if i < 0:
147 break
148 try:
149 total, chunks = parse_container(data, i)
150 except ContainerError:
151 rejected.append(i)
152 i += 4
153 continue
154 parts = {fourcc: (start, size) for fourcc, start, size in chunks}
155 dialect = b""
156 if b"DXIL" in parts:
157 dialect = chunk_payload(data, i, (b"DXIL",) + parts[b"DXIL"])
158 elif b"ACCC" in parts:
159 dialect = chunk_payload(data, i, (b"ACCC",) + parts[b"ACCC"])
160 tags = xdat_tags(dialect) if b"DXIL" in parts else []
161 record = {
162 "image": image,
163 "offset": i,
164 "size": total,
165 "sha256": hashlib.sha256(data[i : i + total]).hexdigest(),
166 "name": module_name(chunk_payload(data, i, (b"ILDN",) + parts[b"ILDN"]))
167 if b"ILDN" in parts
168 else None,
169 "chunks": [
170 {"fourcc": fourcc.decode("latin-1"), "size": size}
171 for fourcc, _, size in chunks
172 ],
173 "xdat_tags": tags,
174 "has_xbch": any(t["tag"] == 0x0D and t["magic"] == "XBCH" for t in tags),
175 "has_fspx": (b"ACCC" in parts and dialect[:4] == FSPX),
176 "has_bitcode": BITCODE in dialect,
177 }
178 found.append(record)
179 i += total
180 return found, rejected
181
182
183def safe_stem(name: str | None, index: int) -> str:
184 stem = SAFE_NAME.sub("_", name or "").strip("._")
185 return stem or f"container_{index:02d}"
186
187
188def extract(data: bytes, records: list[dict], directory: str) -> list[dict]:
189 """Write each container as `<module>.dxbc`; return the translator's index entries."""
190 os.makedirs(directory, exist_ok=True)
191 index = []
192 for k, record in enumerate(records):
193 stem = safe_stem(record["name"], k)
194 file = f"{stem}.dxbc"
195 target = os.path.join(directory, file)
196 if os.path.exists(target):
197 file = f"{stem}_{k:02d}.dxbc"
198 target = os.path.join(directory, file)
199 with open(target, "wb") as f:
200 f.write(data[record["offset"] : record["offset"] + record["size"]])
201 index.append({"name": stem, "file": file, "stage": "cs"})
202 return index
203
204
205def main(argv=None) -> int:
206 ap = argparse.ArgumentParser(
207 description="Inventory the DXBC shader containers embedded in PE images."
208 )
209 ap.add_argument("images", nargs="+", help="PE image(s) to scan")
210 ap.add_argument("--json", help="write the per-container records here")
211 ap.add_argument(
212 "--extract",
213 metavar="DIR",
214 help="write each container as <module>.dxbc plus index.json (game data: keep it out of the repo)",
215 )
216 ap.add_argument(
217 "--verbose", action="store_true", help="print one line per container"
218 )
219 a = ap.parse_args(argv)
220
221 all_records, status, index = [], 0, []
222 for image in a.images:
223 try:
224 with open(image, "rb") as f:
225 data = f.read()
226 except OSError as e:
227 print(f"ERROR: cannot read {image}: {e.strerror or e}", file=sys.stderr)
228 status = 2
229 continue
230 records, rejected = inspect(data, image)
231 all_records.extend(records)
232 print(
233 f"{image}: {len(records)} container(s), {len(rejected)} rejected DXBC hit(s)"
234 )
235 if a.verbose:
236 for r in records:
237 name = r["name"] or "?"
238 flags = "".join(
239 c
240 for c, on in (
241 ("X", r["has_xbch"]),
242 ("F", r["has_fspx"]),
243 ("B", r["has_bitcode"]),
244 )
245 if on
246 )
247 chunks = ",".join(c["fourcc"] for c in r["chunks"])
248 print(
249 f" {r['offset']:#x} {r['size']:>7} {flags:<3} {name:<28} {chunks}"
250 )
251 if a.extract:
252 index.extend(extract(data, records, a.extract))
253
254 if a.extract:
255 with open(os.path.join(a.extract, "index.json"), "w", encoding="utf-8", newline="\n") as f:
256 json.dump(index, f, indent=0)
257 print(f" extracted {len(index)} file(s) to {a.extract}")
258 print(" these are game data: do not commit them", file=sys.stderr)
259
260 if a.json:
261 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
262 json.dump(all_records, f, indent=1)
263 print(f"wrote {a.json}")
264 return status
265
266
267if __name__ == "__main__":
268 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
269 sys.stdout.reconfigure(errors="replace")
270 except (AttributeError, ValueError, OSError):
271 pass
272 sys.exit(main())
diff --git a/tools/psin_names.py b/tools/psin_names.py
index 0c9b7281e..c57b590c5 100644
--- a/tools/psin_names.py
+++ b/tools/psin_names.py
@@ -188,14 +188,17 @@ def main():
188 ap.add_argument("--refs", help="write every resolved value as TSV (local only: it holds game names)") 188 ap.add_argument("--refs", help="write every resolved value as TSV (local only: it holds game names)")
189 ap.add_argument("--limit", type=psin_index.count, help="stop after this many PSIN files") 189 ap.add_argument("--limit", type=psin_index.count, help="stop after this many PSIN files")
190 a = ap.parse_args() 190 a = ap.parse_args()
191 for path in [a.src] + a.names: 191 inputs = [a.src, *a.names]
192 for path in inputs:
192 if not os.path.exists(path): 193 if not os.path.exists(path):
193 print(f"ERROR: {path}: no such file or folder", file=sys.stderr) 194 print(f"ERROR: {path}: no such file or folder", file=sys.stderr)
194 return 2 195 return 2
195 try: 196 try:
197 if a.refs and os.path.exists(a.refs) and any(os.path.samefile(path, a.refs) for path in inputs):
198 ap.error("--refs must not overwrite an input")
196 names = load_names(a.names) 199 names = load_names(a.names)
197 if a.refs: 200 if a.refs:
198 with open(a.refs, "w", encoding="utf-8") as refs: 201 with open(a.refs, "w", encoding="utf-8", newline="\n") as refs:
199 refs.write("file\tstruct\tfield\ttype\tvalue\tname\n") 202 refs.write("file\tstruct\tfield\ttype\tvalue\tname\n")
200 summary, table = scan(a.src, names, a.limit, refs) 203 summary, table = scan(a.src, names, a.limit, refs)
201 else: 204 else:
diff --git a/tools/rbf0_index.py b/tools/rbf0_index.py
index c13122afa..cb41da559 100644
--- a/tools/rbf0_index.py
+++ b/tools/rbf0_index.py
@@ -464,7 +464,7 @@ def write_output(path, records, summary, all_strings=False):
464 doc["sample_strings"] = r["_all_strings"] if all_strings else r["sample"] 464 doc["sample_strings"] = r["_all_strings"] if all_strings else r["sample"]
465 doc["sample_truncated"] = not all_strings and r["strings"] > len(r["sample"]) 465 doc["sample_truncated"] = not all_strings and r["strings"] > len(r["sample"])
466 docs.append(doc) 466 docs.append(doc)
467 with open(path, "w", encoding="utf-8") as f: 467 with open(path, "w", encoding="utf-8", newline="\n") as f:
468 json.dump({"summary": summary, "files": docs}, f, indent=1) 468 json.dump({"summary": summary, "files": docs}, f, indent=1)
469 return 469 return
470 with open(path, "w", encoding="utf-8", newline="") as f: 470 with open(path, "w", encoding="utf-8", newline="") as f:
diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py
index 8addea7b7..9961152f0 100644
--- a/tools/rdna2spirv.py
+++ b/tools/rdna2spirv.py
@@ -70,11 +70,14 @@ MESH_COMPUTE = False
70# `exp paramN` also exports the channel's two f16 halves decoded to f32, low halves at f16_half_location(N, 0) and high 70# `exp paramN` also exports the channel's two f16 halves decoded to f32, low halves at f16_half_location(N, 0) and high
71# halves at f16_half_location(N, 1), and a PS *_f16 read of attrN.c takes component c of that smooth input. The 71# halves at f16_half_location(N, 1), and a PS *_f16 read of attrN.c takes component c of that smooth input. The
72# interpolation is linear, so this is the same P0 + i(P1 - P0) + j(P2 - P0) of the decoded halves, rounded by the 72# interpolation is linear, so this is the same P0 + i(P1 - P0) + j(P2 - P0) of the decoded halves, rounded by the
73# device's interpolator instead of by explicit arithmetic. The halves sit below location F16_HALF_TOP (30: 31 73# device's interpolator instead of by explicit arithmetic. The halves count down from location F16_HALF_TOP (param 0's
74# locations is MoltenVK's limit, 124 components), counting down from param 0, so a producer with params 0..P-1 has 74# high halves, its low halves one below), so a producer with params 0..P-1 has room for the halves of params
75# room for the halves of params 0..(29 - P) / 2; Gen.export skips the ones that would land on its own params. 75# 0..(28 - P) / 2; Gen.export skips the ones that would land on its own params. The top is 29, not 30 (SHADER-291):
76# MoltenVK's maxVertexOutputComponents is 124 because Metal counts gl_Position in its 128 vertex-output scalars, and
77# the validation layer counts it too (VUID-RuntimeSpirv-Location-06272), so (29 + 1) * 4 + 4 = 124 is the most a VS
78# can use there.
76F16_HALVES = False 79F16_HALVES = False
77F16_HALF_TOP = 30 80F16_HALF_TOP = 29
78 81
79 82
80def f16_half_location(n, half): 83def f16_half_location(n, half):
@@ -436,7 +439,10 @@ class Gen:
436 selhi = next((m for m in mods if m.startswith("op_sel_hi:")), "op_sel_hi:[0,0,0]") 439 selhi = next((m for m in mods if m.startswith("op_sel_hi:")), "op_sel_hi:[0,0,0]")
437 sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")] 440 sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")]
438 hb = [int(x) for x in selhi.split("[")[1].rstrip("]").split(",")] 441 hb = [int(x) for x in selhi.split("[")[1].rstrip("]").split(",")]
439 return [self.f16_in(src, sb[i]) if hb[i] else self.src_f(src) for i, src in enumerate(a[1:4])] 442 # An f32 operand reads as a zero of its sign when it is denormal: the game's MODE flushes f32 denormals
443 # (denorm_mode_32 = 0), measured on gfx1036 for 0x00000001, 0x807fffff and the integer inline constants 1 and
444 # 64 used as f32 operands (@Sanonymous01, SHADER-298). The f16 operands widen to normal f32 values.
445 return [self.f16_in(src, sb[i]) if hb[i] else self.flush_f32(self.src_f(src)) for i, src in enumerate(a[1:4])]
440 446
441 def f16_bits(self, f, rtz=False): 447 def f16_bits(self, f, rtz=False):
442 """f32 ``f`` -> f16 bits in the low 16 bits of a %uint, computed with integer ops only (SHADER-56). 448 """f32 ``f`` -> f16 bits in the low 16 bits of a %uint, computed with integer ops only (SHADER-56).
@@ -1279,11 +1285,18 @@ class Gen:
1279 65: (8, "unorm", (16, 16, 16, 16)), 66: (8, "snorm", (16, 16, 16, 16)), 1285 65: (8, "unorm", (16, 16, 16, 16)), 66: (8, "snorm", (16, 16, 16, 16)),
1280 44: (4, "unorm", (2, 10, 10, 10)), 50: (4, "unorm", (10, 10, 10, 2)), 1286 44: (4, "unorm", (2, 10, 10, 10)), 50: (4, "unorm", (10, 10, 10, 2)),
1281 69: (8, "uint", (16, 16, 16, 16)), 27: (4, "uint", (16, 16)), 1287 69: (8, "uint", (16, 16, 16, 16)), 27: (4, "uint", (16, 16)),
1282 2: (1, "snorm", (8,)), 8: (2, "snorm", (16,)), 15: (2, "snorm", (8, 8))} 1288 2: (1, "snorm", (8,)), 8: (2, "snorm", (16,)), 15: (2, "snorm", (8, 8)),
1289 # Narrow integer formats, measured natively on gfx1036 (wave32 and wave64): UINT loads zero-extend
1290 # and stores saturate to the channel; SINT loads sign-extend and stores clamp the 32-bit signed value
1291 # to [-2^(w-1), 2^(w-1) - 1].
1292 5: (1, "uint", (8,)), 11: (2, "uint", (16,)), 18: (2, "uint", (8, 8)),
1293 6: (1, "sint", (8,)), 12: (2, "sint", (16,)), 19: (2, "sint", (8, 8)), 28: (4, "sint", (16, 16)),
1294 61: (4, "sint", (8, 8, 8, 8)), 70: (8, "sint", (16, 16, 16, 16))}
1283 1295
1284 def encode_format(self, fcomps, icomps, code): 1296 def encode_format(self, fcomps, icomps, code):
1285 """Encode one element of format `code` -> list of uint ids (whole dwords; elements under 4 bytes return one 1297 """Encode one element of format `code` -> list of uint ids (whole dwords; elements under 4 bytes return one
1286 value in the low bits). fcomps are f32 bit patterns (float/normalized kinds), icomps integer bit patterns (u32/i32/uint).""" 1298 value in the low bits). fcomps are f32 bit patterns (float/normalized kinds), icomps integer bit patterns
1299 (u32/i32/uint/sint)."""
1287 try: 1300 try:
1288 size, kind, widths = self.FORMATS[code] 1301 size, kind, widths = self.FORMATS[code]
1289 except KeyError: 1302 except KeyError:
@@ -1312,6 +1325,11 @@ class Gen:
1312 self.emit(f"{i} = OpConvertFToS %int {rd}") 1325 self.emit(f"{i} = OpConvertFToS %int {rd}")
1313 self.emit(f"{u} = OpBitcast %uint {i}") 1326 self.emit(f"{u} = OpBitcast %uint {i}")
1314 field = u 1327 field = u
1328 elif kind == "sint": # Narrow SINT stores clamp the signed value to the field's range.
1329 clamped, field = self.tmp(), self.tmp()
1330 lo, hi = self.as_int(self.cu((-(1 << (w - 1))) & 0xFFFFFFFF)), self.as_int(self.cu((1 << (w - 1)) - 1))
1331 self.emit(f"{clamped} = OpExtInst %int %glsl SClamp {self.as_int(icomps[c])} {lo} {hi}")
1332 self.emit(f"{field} = OpBitcast %uint {clamped}")
1315 else: # Narrow UINT stores saturate to the field width before insertion. 1333 else: # Narrow UINT stores saturate to the field width before insertion.
1316 field = self.tmp() 1334 field = self.tmp()
1317 self.emit(f"{field} = OpExtInst %uint %glsl UMin {icomps[c]} {self.cu((1 << w) - 1)}") 1335 self.emit(f"{field} = OpExtInst %uint %glsl UMin {icomps[c]} {self.cu((1 << w) - 1)}")
@@ -1420,6 +1438,11 @@ class Gen:
1420 self.emit(f"{lo} = OpULessThan %bool {au} {self.cu(1 << (w - 1))}") 1438 self.emit(f"{lo} = OpULessThan %bool {au} {self.cu(1 << (w - 1))}")
1421 self.emit(f"{res} = OpSelect %uint {lo} {sel} {self.cu(0xBF800000)}") 1439 self.emit(f"{res} = OpSelect %uint {lo} {sel} {self.cu(0xBF800000)}")
1422 out.append(res) 1440 out.append(res)
1441 elif kind == "sint":
1442 si, su = self.tmp(), self.tmp()
1443 self.emit(f"{si} = OpBitFieldSExtract %int {self.as_int(src)} {self.cu(bit % 32)} {self.cu(w)}")
1444 self.emit(f"{su} = OpBitcast %uint {si}")
1445 out.append(su)
1423 else: # uint: raw integer 1446 else: # uint: raw integer
1424 out.append(f) 1447 out.append(f)
1425 bit += w 1448 bit += w
@@ -1771,12 +1794,12 @@ class Gen:
1771 # DST_SEL swizzle: 0 -> 0, 1 -> 1.0 (float/norm) or integer 1 (UINT/SINT; SHADER-86), 4..7 -> X..W. 1794 # DST_SEL swizzle: 0 -> 0, 1 -> 1.0 (float/norm) or integer 1 (UINT/SINT; SHADER-86), 4..7 -> X..W.
1772 is_int_fmt, is_signed = "%false", "%false" 1795 is_int_fmt, is_signed = "%false", "%false"
1773 for code_v, (_, kind, _) in self.FORMATS.items(): 1796 for code_v, (_, kind, _) in self.FORMATS.items():
1774 if kind in ("u32", "i32", "uint"): 1797 if kind in ("u32", "i32", "uint", "sint"):
1775 e, o = self.tmp(), self.tmp() 1798 e, o = self.tmp(), self.tmp()
1776 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code_v)}") 1799 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code_v)}")
1777 self.emit(f"{o} = OpLogicalOr %bool {is_int_fmt} {e}") 1800 self.emit(f"{o} = OpLogicalOr %bool {is_int_fmt} {e}")
1778 is_int_fmt = o 1801 is_int_fmt = o
1779 if d16 and kind == "i32": 1802 if d16 and kind in ("i32", "sint"):
1780 signed = self.tmp() 1803 signed = self.tmp()
1781 self.emit(f"{signed} = OpLogicalOr %bool {is_signed} {e}") 1804 self.emit(f"{signed} = OpLogicalOr %bool {is_signed} {e}")
1782 is_signed = signed 1805 is_signed = signed
@@ -1807,6 +1830,13 @@ class Gen:
1807 self.emit(f"{half} = OpSelect %uint {is_signed} {signed} {unsigned}") 1830 self.emit(f"{half} = OpSelect %uint {is_signed} {signed} {unsigned}")
1808 return half 1831 return half
1809 1832
1833 is_norm = "%false"
1834 for code_v, (_, kind, _) in self.FORMATS.items():
1835 if kind in ("unorm", "snorm") and (fixed_fmt is None or code_v == fixed_fmt):
1836 e, o = self.tmp(), self.tmp()
1837 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code_v)}")
1838 self.emit(f"{o} = OpLogicalOr %bool {is_norm} {e}")
1839 is_norm = o
1810 for i in range(0, len(outs), 2): 1840 for i in range(0, len(outs), 2):
1811 dest = {"k": "vgpr", "r": vd["r"] + i // 2, "n": 1} 1841 dest = {"k": "vgpr", "r": vd["r"] + i // 2, "n": 1}
1812 lo = outs[i] 1842 lo = outs[i]
@@ -1814,12 +1844,15 @@ class Gen:
1814 r = self.tmp() 1844 r = self.tmp()
1815 if i + 1 == len(outs): 1845 if i + 1 == len(outs):
1816 # For d16_x and d16_xyz the unaddressed high half keeps its previous bits. 1846 # For d16_x and d16_xyz the unaddressed high half keeps its previous bits.
1817 fl = self.f16_bits(self.tof(lo)) 1847 fl = self.d16_norm_f16(lo, is_norm)
1818 self.emit(f"{r} = OpSelect %uint {is_int_fmt} {il} {fl}") 1848 self.emit(f"{r} = OpSelect %uint {is_int_fmt} {il} {fl}")
1819 self.write_lo16(dest, r) 1849 self.write_lo16(dest, r)
1820 continue 1850 continue
1821 hi = outs[i + 1] 1851 hi = outs[i + 1]
1822 ph = self.pack_f16_pair_int(self.tof(lo), self.tof(hi)) 1852 ph = self.tmp()
1853 fh_s = self.tmp()
1854 self.emit(f"{fh_s} = OpShiftLeftLogical %uint {self.d16_norm_f16(hi, is_norm)} {self.cu(16)}")
1855 self.emit(f"{ph} = OpBitwiseOr %uint {self.d16_norm_f16(lo, is_norm)} {fh_s}")
1823 ih, pi = self.tmp(), self.tmp() 1856 ih, pi = self.tmp(), self.tmp()
1824 high_half = int_half(hi) 1857 high_half = int_half(hi)
1825 self.emit(f"{ih} = OpShiftLeftLogical %uint {high_half} {self.cu(16)}") 1858 self.emit(f"{ih} = OpShiftLeftLogical %uint {high_half} {self.cu(16)}")
@@ -1827,6 +1860,30 @@ class Gen:
1827 self.emit(f"{r} = OpSelect %uint {is_int_fmt} {pi} {ph}") 1860 self.emit(f"{r} = OpSelect %uint {is_int_fmt} {pi} {ph}")
1828 self.dst(dest, r) 1861 self.dst(dest, r)
1829 1862
1863 # The f32 quotients m / (2^n - 1), 1 <= n <= 16, that land exactly on an f16 halfway point: 0x3f7ff000 is
1864 # 16379/16383, 32759/32767 and 65519/65535, 0x3f7fb000 is 65455/65535 (an enumeration of every m and n). The exact
1865 # quotient is below the halfway point each time, and RDNA2 rounds it once, straight to f16 (BUILD-161, RX 6700).
1866 D16_NORM_HALFWAY = (0x3F7FF000, 0x3F7FB000)
1867
1868 def d16_norm_f16(self, bits, is_norm):
1869 """f16 bits of a typed d16 buffer load component from its decoded f32 ``bits``. Round to nearest even
1870 (f16_bits), except that a UNORM/SNORM quotient (``is_norm``) whose f32 is one of D16_NORM_HALFWAY takes the
1871 f16 below it. The hardware rounds the exact quotient once; f32 first and then f16 rounds twice, which is 1 ulp
1872 high on exactly those values (UNORM16 0xffaf and 0xffef, SNORM16 0x7ff7 and 0x8009, the 14- and 15-bit
1873 twins). Measured on an RX 6700 (gfx1031) for every UNORM8/SNORM8/UNORM10/UNORM16/SNORM16 value, MUBUF and
1874 MTBUF, wave32 and wave64 (tools/d16_format_probe.py). A float format keeps the plain rounding: a 32_FLOAT
1875 0x3f7ff000 is a real tie."""
1876 h = self.f16_bits(self.tof(bits))
1877 mag, a, b, hit, both, dn, out = (self.tmp() for _ in range(7))
1878 self.emit(f"{mag} = OpBitwiseAnd %uint {bits} {self.cu(0x7FFFFFFF)}")
1879 self.emit(f"{a} = OpIEqual %bool {mag} {self.cu(self.D16_NORM_HALFWAY[0])}")
1880 self.emit(f"{b} = OpIEqual %bool {mag} {self.cu(self.D16_NORM_HALFWAY[1])}")
1881 self.emit(f"{hit} = OpLogicalOr %bool {a} {b}")
1882 self.emit(f"{both} = OpLogicalAnd %bool {hit} {is_norm}")
1883 self.emit(f"{dn} = OpISub %uint {h} {self.cu(1)}") # sign-magnitude: 1 ulp toward zero
1884 self.emit(f"{out} = OpSelect %uint {both} {dn} {h}")
1885 return out
1886
1830 def global_address(self, op, vaddr, saddr, mods): 1887 def global_address(self, op, vaddr, saddr, mods):
1831 """The 64-bit Xbox GPU VA a global_* instruction accesses (ulong id): (saddr: 64-bit SGPR pair + zero-extended 1888 """The 64-bit Xbox GPU VA a global_* instruction accesses (ulong id): (saddr: 64-bit SGPR pair + zero-extended
1832 32-bit vaddr | off: 64-bit VGPR pair) + the signed 12-bit instruction offset.""" 1889 32-bit vaddr | off: 64-bit VGPR pair) + the signed 12-bit instruction offset."""
@@ -2286,9 +2343,21 @@ class Gen:
2286 return addr, d3, in_b, (check if mode in (None, 0, 3) else None), step 2343 return addr, d3, in_b, (check if mode in (None, 0, 3) else None), step
2287 return addr, d3, in_b, step 2344 return addr, d3, in_b, step
2288 2345
2289 def buffer_store(self, op, a, mods): 2346 def mtbuf_format(self, op, mods):
2290 """buffer_store_dword[xN] (raw) and buffer_store_format_* (f32 formats stored raw, f16x2/x4, unorm8x4). 2347 """The format code an MTBUF instruction (tbuffer_load/store_format_*) encodes for itself, which replaces the
2291 Only active lanes store, inside a structured if.""" 2348 V#'s. LLVM omits the modifier for GFX10's default, BUF_FMT_8_UNORM (code 1)."""
2349 fm = next((m for m in mods if m.startswith("format:")), "format:[BUF_FMT_8_UNORM]")
2350 name = "GFX10_FORMAT_" + fm.split("BUF_FMT_")[-1].rstrip("]")
2351 code = next((c for c, n in GFX10_FORMATS.items() if n == name), None)
2352 if code is None or code not in self.FORMATS:
2353 raise Unsupported(op + " " + name)
2354 self.fixed_format_codes.add(code)
2355 return code
2356
2357 def buffer_store(self, op, a, mods, fixed_fmt=None):
2358 """buffer_store_dword[xN] (raw) and buffer_store_format_* (every format in FORMATS, read from the V# at run
2359 time). tbuffer_store_format_* comes here with its own format in fixed_fmt: only that one is encoded, and the
2360 bounds check uses its element size, whatever the V# says. Only active lanes store, inside a structured if."""
2292 if any(m in mods for m in ("lds", "tfe", "d16")): 2361 if any(m in mods for m in ("lds", "tfe", "d16")):
2293 raise Unsupported(op + " form") 2362 raise Unsupported(op + " form")
2294 d16 = "_d16_" in op 2363 d16 = "_d16_" in op
@@ -2297,7 +2366,7 @@ class Gen:
2297 if dword_store: 2366 if dword_store:
2298 addr, d3, in_b, per, step = self.buffer_address(a, mods, parts=True) 2367 addr, d3, in_b, per, step = self.buffer_address(a, mods, parts=True)
2299 else: 2368 else:
2300 addr, d3, in_b, step = self.buffer_address(a, mods, elem="fmt") 2369 addr, d3, in_b, step = self.buffer_address(a, mods, elem="fmt", fixed_fmt=fixed_fmt)
2301 per = None 2370 per = None
2302 if dword_store: 2371 if dword_store:
2303 n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1]) 2372 n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1])
@@ -2322,8 +2391,11 @@ class Gen:
2322 else: 2391 else:
2323 comps = [self.load_reg("vgpr", vd["r"] + i) for i in range(n)] 2392 comps = [self.load_reg("vgpr", vd["r"] + i) for i in range(n)]
2324 icomps = comps 2393 icomps = comps
2325 fmt = self.tmp() 2394 if fixed_fmt is not None:
2326 self.emit(f"{fmt} = OpBitFieldUExtract %uint {d3} {self.cu(12)} {self.cu(7)}") 2395 fmt = None # tbuffer: the instruction's format, so no V# FORMAT to branch on
2396 else:
2397 fmt = self.tmp()
2398 self.emit(f"{fmt} = OpBitFieldUExtract %uint {d3} {self.cu(12)} {self.cu(7)}")
2327 # Encodings for the formats that appear in store-heavy shaders; others store nothing. 2399 # Encodings for the formats that appear in store-heavy shaders; others store nothing.
2328 f32 = {22: 1, 64: 2, 74: 3, 77: 4} 2400 f32 = {22: 1, 64: 2, 74: 3, 77: 4}
2329 # Float views of the components, computed before any branch so every branch can use them. 2401 # Float views of the components, computed before any branch so every branch can use them.
@@ -2346,6 +2418,14 @@ class Gen:
2346 self.emit(f"OpBranch {lbl_end}") 2418 self.emit(f"OpBranch {lbl_end}")
2347 self.emit(f"{lbl_end} = OpLabel") 2419 self.emit(f"{lbl_end} = OpLabel")
2348 return 2420 return
2421 if fixed_fmt is not None:
2422 # A V# whose FORMAT is 0 (INVALID) disables the store, though MTBUF brings its own format (measured natively
2423 # on gfx1035, wave32 and wave64, in OOB_SELECT 0, 1 and 3).
2424 vf, valid, ok = self.tmp(), self.tmp(), self.tmp()
2425 self.emit(f"{vf} = OpBitFieldUExtract %uint {d3} {self.cu(12)} {self.cu(7)}")
2426 self.emit(f"{valid} = OpINotEqual %bool {vf} {self.cu(0)}")
2427 self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {valid}")
2428 in_b = ok
2349 act = self.tmp() 2429 act = self.tmp()
2350 self.emit(f"{act} = OpLogicalAnd %bool {self.active_b()} {in_b}") 2430 self.emit(f"{act} = OpLogicalAnd %bool {self.active_b()} {in_b}")
2351 lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" 2431 lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end"
@@ -2387,19 +2467,21 @@ class Gen:
2387 extended = self.tmp() 2467 extended = self.tmp()
2388 self.emit(f"{extended} = OpBitFieldSExtract %int {self.as_int(component)} {self.cu(0)} {self.cu(16)}") 2468 self.emit(f"{extended} = OpBitFieldSExtract %int {self.as_int(component)} {self.cu(0)} {self.cu(16)}")
2389 signed_ic.append(self.tou(extended)) 2469 signed_ic.append(self.tou(extended))
2390 for code, (size, kind, widths) in self.FORMATS.items(): 2470 formats = self.FORMATS.items() if fmt is not None else [(fixed_fmt, self.FORMATS[fixed_fmt])]
2391 e = self.tmp() 2471 for code, (size, kind, widths) in formats:
2392 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code)}") 2472 if fmt is not None:
2393 ld, le = self.tmp() + "_s", self.tmp() + "_se" 2473 e = self.tmp()
2394 self.emit(f"OpSelectionMerge {le} None") 2474 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code)}")
2395 self.emit(f"OpBranchConditional {e} {ld} {le}") 2475 ld, le = self.tmp() + "_s", self.tmp() + "_se"
2396 self.emit(f"{ld} = OpLabel") 2476 self.emit(f"OpSelectionMerge {le} None")
2477 self.emit(f"OpBranchConditional {e} {ld} {le}")
2478 self.emit(f"{ld} = OpLabel")
2397 ncomp = min(len(widths), n) 2479 ncomp = min(len(widths), n)
2398 source = normalized if kind in ("unorm", "snorm") else fc 2480 source = normalized if kind in ("unorm", "snorm") else fc
2399 fcs = source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp) 2481 fcs = source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp)
2400 if code in (50, 56): 2482 if code in (50, 56):
2401 fcs = unorm_view 2483 fcs = unorm_view
2402 integer_source = signed_ic if kind == "i32" else ic 2484 integer_source = signed_ic if kind in ("i32", "sint") else ic
2403 ics = integer_source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp) 2485 ics = integer_source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp)
2404 words = self.encode_format(fcs + [self.cu(0)] * 4, ics + [self.cu(0)] * 4, code) 2486 words = self.encode_format(fcs + [self.cu(0)] * 4, ics + [self.cu(0)] * 4, code)
2405 if size >= 4: 2487 if size >= 4:
@@ -2428,8 +2510,9 @@ class Gen:
2428 self.emit(f"{vs} = OpShiftLeftLogical %uint {val} {sh24}") 2510 self.emit(f"{vs} = OpShiftLeftLogical %uint {val} {sh24}")
2429 self.emit(f"{t1} = OpAtomicAnd %uint {ap} {self.cu(1)} {self.cu(0)} {inv}") 2511 self.emit(f"{t1} = OpAtomicAnd %uint {ap} {self.cu(1)} {self.cu(0)} {inv}")
2430 self.emit(f"{t2} = OpAtomicOr %uint {ap} {self.cu(1)} {self.cu(0)} {vs}") 2512 self.emit(f"{t2} = OpAtomicOr %uint {ap} {self.cu(1)} {self.cu(0)} {vs}")
2431 self.emit(f"OpBranch {le}") 2513 if fmt is not None:
2432 self.emit(f"{le} = OpLabel") 2514 self.emit(f"OpBranch {le}")
2515 self.emit(f"{le} = OpLabel")
2433 self.emit(f"OpBranch {lbl_end}") 2516 self.emit(f"OpBranch {lbl_end}")
2434 self.emit(f"{lbl_end} = OpLabel") 2517 self.emit(f"{lbl_end} = OpLabel")
2435 2518
@@ -3059,6 +3142,28 @@ class Gen:
3059 self.emit(f"{z} = OpSelect %uint {any_} {self.cu(1)} {self.cu(0)}") 3142 self.emit(f"{z} = OpSelect %uint {any_} {self.cu(1)} {self.cu(0)}")
3060 self.emit(f"OpStore %scc {z}") 3143 self.emit(f"OpStore %scc {z}")
3061 3144
3145 MASK_SOP2_B32 = ("s_and_b32", "s_or_b32", "s_xor_b32", "s_andn2_b32", "s_orn2_b32", "s_nand_b32", "s_nor_b32",
3146 "s_xnor_b32", "s_cselect_b32")
3147
3148 def sop2_b32_srcs(self, op, a):
3149 """The two sources of a 32-bit SOP2. In a wave32 program a bitwise op (or s_cselect) that writes EXEC / VCC
3150 reads both through mask_src, so a constant, inline or held in an SGPR, gives each lane its own bit; a mask is
3151 read as before. Until 2026-11-22
3152 a constant was used whole: `s_and_b32 exec_lo, exec_lo, 0xff00` (or the same constant in an SGPR) left every
3153 lane of EXEC on. Data ops, and wave64 programs (a b32 op there is on one half of a mask), are unchanged."""
3154 if op in self.MASK_SOP2_B32 and not self.wave64 and len(a) >= 3:
3155 d = a[0]
3156 to_mask = d["k"] == "special" and d.get("t", "") in ("exec_lo", "vcc_lo", "exec", "vcc")
3157 maskable = all(x["k"] in ("sgpr", "imm") or (x["k"] == "special" and
3158 x.get("t", "").startswith(("exec", "vcc"))) for x in a[1:3])
3159 # Only when the result is a mask (EXEC / VCC destination). An SGPR destination is classified by
3160 # lane_masks.py, which calls it data when the other operand is a constant; a per-lane bit stored there
3161 # would then be counted as data (s_and_b32 s20, exec_lo, 1; s_bcnt1_i32_b32 s21, s20 gave 32 and 0
3162 # instead of 1, found by @Pierre-Kookis on #1792), so that case keeps the data read.
3163 if maskable and to_mask:
3164 return self.mask_src(a[1], wide=False), self.mask_src(a[2], wide=False)
3165 return self.src_u(a[1]), self.src_u(a[2])
3166
3062 def scc_logic(self, a, r): 3167 def scc_logic(self, a, r):
3063 """SCC of a 32-bit bitwise SOP2 (s_and/or/xor/andn2/orn2/nand/nor/xnor_b32): D != 0. In a wave32 program 3168 """SCC of a 32-bit bitwise SOP2 (s_and/or/xor/andn2/orn2/nand/nor/xnor_b32): D != 0. In a wave32 program
3064 an operation on lane masks (a source holds one, or it writes EXEC) has the whole wave's mask as D, so SCC 3169 an operation on lane masks (a source holds one, or it writes EXEC) has the whole wave's mask as D, so SCC
@@ -3343,7 +3448,26 @@ class Gen:
3343 or of the 32-bit value with L mod 32 (a b32 op). Until 2026-11-22 every lane took bit 0 (0xff00 was no 3448 or of the 32-bit value with L mod 32 (a b32 op). Until 2026-11-22 every lane took bit 0 (0xff00 was no
3344 lane, 5 every lane).""" 3449 lane, 5 every lane)."""
3345 if a["k"] == "sgpr": 3450 if a["k"] == "sgpr":
3346 return self.load_reg("sgpr", a["r"]) 3451 if self.holds_lane_mask(a):
3452 return self.load_reg("sgpr", a["r"])
3453 # Not known to hold a mask: the SGPR may hold a constant (s_mov_b32 s20, 0x3ffffc00) that is the same in
3454 # every invocation, so lane L takes its bit L, as for an immediate. Until 2026-11-22 the raw value was used
3455 # and any non-zero constant enabled every lane. A mask the analysis missed is still exact: each
3456 # invocation holds 0 or ~0 there, and bit L of that is the same 0 or 1. A pair in a wave64 64-bit
3457 # context gives lanes 32..63 their bit from the high SGPR (a mask keeps the same 0 / ~0 in both).
3458 lane = self.wave_lane()
3459 word = self.load_reg("sgpr", a["r"])
3460 if a.get("n", 1) == 2 and wide and self.wave64:
3461 hi, up, sel = self.load_reg("sgpr", a["r"] + 1), self.tmp(), self.tmp()
3462 self.emit(f"{up} = OpUGreaterThanEqual %bool {lane} {self.cu(32)}")
3463 self.emit(f"{sel} = OpSelect %uint {up} {hi} {word}")
3464 word = sel
3465 sh, shr, bit, r = (self.tmp() for _ in range(4))
3466 self.emit(f"{sh} = OpBitwiseAnd %uint {lane} {self.cu(31)}")
3467 self.emit(f"{shr} = OpShiftRightLogical %uint {word} {sh}")
3468 self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}")
3469 self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}")
3470 return r
3347 if a["k"] == "special" and a["t"] in ("vcc", "vcc_lo", "vcc_hi"): 3471 if a["k"] == "special" and a["t"] in ("vcc", "vcc_lo", "vcc_hi"):
3348 v = self.tmp() 3472 v = self.tmp()
3349 self.emit(f"{v} = OpLoad %uint %vcc") 3473 self.emit(f"{v} = OpLoad %uint %vcc")
@@ -3895,13 +4019,16 @@ class Gen:
3895 if op in ("s_denorm_mode", "s_round_mode"): 4019 if op in ("s_denorm_mode", "s_round_mode"):
3896 raise Unsupported(op + " (not in the corpus; MODE is modelled through s_setreg only)") 4020 raise Unsupported(op + " (not in the corpus; MODE is modelled through s_setreg only)")
3897 if op == "s_mov_b32" and a[0]["k"] == "special" and a[0]["t"] in ("exec_lo", "exec_hi") and \ 4021 if op == "s_mov_b32" and a[0]["k"] == "special" and a[0]["t"] in ("exec_lo", "exec_hi") and \
3898 (a[0]["t"] == "exec_hi" or a[1]["k"] in ("imm", "fimm")): 4022 (a[0]["t"] == "exec_hi" or a[1]["k"] in ("imm", "fimm") or
4023 (a[1]["k"] == "sgpr" and not self.holds_lane_mask(a[1]))):
3899 src = a[1] 4024 src = a[1]
3900 const = (src["v"] & 0xFFFFFFFF) if src["k"] == "imm" else None 4025 const = (src["v"] & 0xFFFFFFFF) if src["k"] == "imm" else None
3901 if src["k"] == "fimm": 4026 if src["k"] == "fimm":
3902 const = struct.unpack("<I", struct.pack("<f", src["v"]))[0] 4027 const = struct.unpack("<I", struct.pack("<f", src["v"]))[0]
3903 self.exec_half_write(0 if a[0]["t"] == "exec_lo" else 1, None if const is not None else self.src_u(src), 4028 # an SGPR that isn't a mask (a constant, say) gives each lane its own bit, as a constant does (mask_src)
3904 const) 4029 val = None if const is not None else (self.mask_src(src, wide=False) if src["k"] == "sgpr"
4030 else self.src_u(src))
4031 self.exec_half_write(0 if a[0]["t"] == "exec_lo" else 1, val, const)
3905 elif op == "v_mov_b32" or op == "s_mov_b32": 4032 elif op == "v_mov_b32" or op == "s_mov_b32":
3906 lit_val = None 4033 lit_val = None
3907 if op == "s_mov_b32" and a[0]["k"] == "sgpr" and self.desc_cache_ok(): 4034 if op == "s_mov_b32" and a[0]["k"] == "sgpr" and self.desc_cache_ok():
@@ -4754,13 +4881,11 @@ class Gen:
4754 elif op in ("tbuffer_load_format_x", "tbuffer_load_format_xy", "tbuffer_load_format_xyz", 4881 elif op in ("tbuffer_load_format_x", "tbuffer_load_format_xy", "tbuffer_load_format_xyz",
4755 "tbuffer_load_format_xyzw", "tbuffer_load_format_d16_x", "tbuffer_load_format_d16_xy", 4882 "tbuffer_load_format_xyzw", "tbuffer_load_format_d16_x", "tbuffer_load_format_d16_xy",
4756 "tbuffer_load_format_d16_xyz", "tbuffer_load_format_d16_xyzw"): 4883 "tbuffer_load_format_d16_xyz", "tbuffer_load_format_d16_xyzw"):
4757 # MTBUF encodes its own format. LLVM omits the modifier for GFX10's default, BUF_FMT_8_UNORM. 4884 self.buffer_load_format(op[1:], a, mods, fixed_fmt=self.mtbuf_format(op, mods))
4758 fm = next((m for m in mods if m.startswith("format:")), "format:[BUF_FMT_8_UNORM]") 4885 elif op in ("tbuffer_store_format_x", "tbuffer_store_format_xy", "tbuffer_store_format_xyz",
4759 name = "GFX10_FORMAT_" + fm.split("BUF_FMT_")[-1].rstrip("]") 4886 "tbuffer_store_format_xyzw", "tbuffer_store_format_d16_x", "tbuffer_store_format_d16_xy",
4760 code = next((c for c, n in GFX10_FORMATS.items() if n == name), None) 4887 "tbuffer_store_format_d16_xyz", "tbuffer_store_format_d16_xyzw"):
4761 if code is None or code not in self.FORMATS: 4888 self.buffer_store(op[1:], a, mods, fixed_fmt=self.mtbuf_format(op, mods))
4762 raise Unsupported(op + " " + name)
4763 self.buffer_load_format(op[1:], a, mods, fixed_fmt=code)
4764 elif op in ("s_bitset0_b64", "s_bitset1_b64"): 4889 elif op in ("s_bitset0_b64", "s_bitset1_b64"):
4765 # D[S0 & 63] = 0 / 1 in the SGPR pair D (D is both source and destination); SCC is not written. The pair 4890 # D[S0 & 63] = 0 / 1 in the SGPR pair D (D is both source and destination); SCC is not written. The pair
4766 # is 64-bit data (as for s_lshl_b64); a pair that lane_masks.py marks as a lane mask stays Unsupported. 4891 # is 64-bit data (as for s_lshl_b64); a pair that lane_masks.py marks as a lane mask stays Unsupported.
@@ -5746,10 +5871,16 @@ class Gen:
5746 self.emit(f"{r} = OpCompositeExtract %uint {s2} 0") 5871 self.emit(f"{r} = OpCompositeExtract %uint {s2} 0")
5747 self.emit(f"{c2} = OpCompositeExtract %uint {s2} 1") 5872 self.emit(f"{c2} = OpCompositeExtract %uint {s2} 1")
5748 self.emit(f"{carry} = OpBitwiseOr %uint {c1} {c2}") 5873 self.emit(f"{carry} = OpBitwiseOr %uint {c1} {c2}")
5874 carry_nz = self.tmp_bool_nz(carry)
5875 if "clamp" in mods:
5876 # Hardware saturates D (0xffffffff on add carry, 0 on sub borrow) while reporting the real carry/borrow.
5877 clamped = self.tmp()
5878 self.emit(f"{clamped} = OpSelect %uint {carry_nz} {self.cu(0) if sub else self.cu(0xFFFFFFFF)} {r}")
5879 r = clamped
5749 self.dst(vd, r) 5880 self.dst(vd, r)
5750 if not (cd["k"] == "special" and cd["t"] == "null"): 5881 if not (cd["k"] == "special" and cd["t"] == "null"):
5751 cm, m = self.tmp(), self.tmp() 5882 cm, m = self.tmp(), self.tmp()
5752 self.emit(f"{cm} = OpLogicalAnd %bool {self.tmp_bool_nz(carry)} {self.active_b()}") # inactive lanes write 0 5883 self.emit(f"{cm} = OpLogicalAnd %bool {carry_nz} {self.active_b()}") # inactive lanes write 0
5753 self.emit(f"{m} = OpSelect %uint {cm} {self.cu(0xFFFFFFFF)} {self.cu(0)}") 5884 self.emit(f"{m} = OpSelect %uint {cm} {self.cu(0xFFFFFFFF)} {self.cu(0)}")
5754 self.mask_dst(cd, m) 5885 self.mask_dst(cd, m)
5755 elif op == "v_mul_legacy_f32": 5886 elif op == "v_mul_legacy_f32":
@@ -5924,7 +6055,7 @@ class Gen:
5924 self.dst(a[0], r) 6055 self.dst(a[0], r)
5925 self.emit(f"OpStore %scc {self.cu(1 if val != 0 else 0)}") 6056 self.emit(f"OpStore %scc {self.cu(1 if val != 0 else 0)}")
5926 return 6057 return
5927 x, y = self.src_u(a[1]), self.src_u(a[2]) 6058 x, y = self.sop2_b32_srcs(op, a)
5928 r = self.tmp() 6059 r = self.tmp()
5929 if op == "s_cselect_b32": 6060 if op == "s_cselect_b32":
5930 c, b = self.tmp(), self.tmp() 6061 c, b = self.tmp(), self.tmp()
@@ -6445,16 +6576,7 @@ class Gen:
6445 self.scc_nonzero(r) 6576 self.scc_nonzero(r)
6446 elif op in ("v_fma_mixlo_f16", "v_fma_mixhi_f16"): 6577 elif op in ("v_fma_mixlo_f16", "v_fma_mixhi_f16"):
6447 vals = self.fma_mix_srcs(a, mods) 6578 vals = self.fma_mix_srcs(a, mods)
6448 r = self.tmp() 6579 r = self.fma_mix_odd(*vals)
6449 self.emit_fma(r, vals[0], vals[1], vals[2])
6450 if self.round_mode:
6451 # Toward zero the hardware rounds the exact fma once, to f16; round-to-odd at f32 narrows exactly.
6452 # Nearest even keeps the f32 Fma then narrow (unchanged).
6453 ro, m, isz, rs = self.fma_mix_odd(*vals), self.tmp(), self.tmp(), self.tmp()
6454 self.emit(f"{m} = OpLoad %uint %mode_r16")
6455 self.emit(f"{isz} = OpIEqual %bool {m} {self.cu(3)}")
6456 self.emit(f"{rs} = OpSelect %float {isz} {ro} {r}")
6457 r = rs
6458 r = self.clamp_mods(r, mods) 6580 r = self.clamp_mods(r, mods)
6459 self.f16_out(a[0], r, hi=(op == "v_fma_mixhi_f16")) 6581 self.f16_out(a[0], r, hi=(op == "v_fma_mixhi_f16"))
6460 elif op == "v_cvt_pk_u8_f32": 6582 elif op == "v_cvt_pk_u8_f32":
@@ -6652,30 +6774,34 @@ class Gen:
6652 self.emit(f"{r} = OpConvertUToF %float {m}") 6774 self.emit(f"{r} = OpConvertUToF %float {m}")
6653 self.dst(a[0], self.tou(self.clamp_mods(r, mods))) 6775 self.dst(a[0], self.tou(self.clamp_mods(r, mods)))
6654 elif op in ("v_cvt_flr_i32_f32", "v_cvt_rpi_i32_f32"): 6776 elif op in ("v_cvt_flr_i32_f32", "v_cvt_rpi_i32_f32"):
6655 # RDNA ISA pseudocode: flr = f32_to_i32(floor(S0)), rpi = f32_to_i32(floor(S0 + 0.5)), the + 0.5 rounded 6777 # Measured natively on RDNA2 (gfx1035 & gfx1036, wave32 & wave64):
6656 # in binary32 like any f32 add. f32_to_i32 saturates as v_cvt_i32_f32 does (#300): +-2^31 and beyond go to 6778 # - v_cvt_flr_i32_f32 = sat_i32(floor(S0)).
6657 # INT_MAX / INT_MIN, NaN to 0. Source neg/abs apply before the rounding. 6779 # - v_cvt_rpi_i32_f32 = sat_i32(floor(S0 + 0.5)) computed exactly without binary32 rounding of S0 + 0.5:
6780 # with f = Floor(x), frac = x - f is exact in binary32 across all normal ranges (0 for |x| >= 2^23,
6781 # and rounds to >= 0.5 iff exact x - f >= 0.5 around -0.5), so (frac >= 0.5) ? (f + 1.0) : f is exact.
6782 # - Out-of-range values (|x| >= 2^31, +-inf) and NaNs all saturate by the sign bit of x (+ -> 0x7FFFFFFF,
6783 # - -> 0x80000000). Check x's bits before Floor so a driver cannot lose a NaN's sign bit.
6658 x = self.src_f(a[1]) 6784 x = self.src_f(a[1])
6785 x_bits = self.tou(x)
6786 x_mag, x_neg, x_in_range, bound, safe_x_u, fl, signed, converted, result = (self.tmp() for _ in range(9))
6787 self.emit(f"{x_mag} = OpBitwiseAnd %uint {x_bits} {self.cu(0x7FFFFFFF)}")
6788 self.emit(f"{x_in_range} = OpULessThan %bool {x_mag} {self.cu(0x4F000000)}") # |x| < 2^31
6789 self.emit(f"{x_neg} = OpINotEqual %bool {x_bits} {x_mag}")
6790 self.emit(f"{bound} = OpSelect %uint {x_neg} {self.cu(0x80000000)} {self.cu(0x7FFFFFFF)}")
6791 # Guard before Floor/FSub/FToS: -2^31 (0xCF000000) takes `bound` = 0x80000000 directly.
6792 self.emit(f"{safe_x_u} = OpSelect %uint {x_in_range} {x_bits} {self.cu(0)}")
6793 safe_x = self.tof(safe_x_u)
6794 self.emit(f"{fl} = OpExtInst %float %glsl Floor {safe_x}")
6659 if op == "v_cvt_rpi_i32_f32": 6795 if op == "v_cvt_rpi_i32_f32":
6660 t = self.tmp() 6796 frac, ge_half, fl_plus1, rounded = (self.tmp() for _ in range(4))
6661 self.emit(f"{t} = OpFAdd %float {x} {self.fconst(0.5)}") 6797 self.emit(f"{frac} = OpFSub %float {safe_x} {fl}")
6662 x = t 6798 self.emit(f"{ge_half} = OpFOrdGreaterThanEqual %bool {frac} {self.fconst(0.5)}")
6663 fl = self.tmp() 6799 self.emit(f"{fl_plus1} = OpFAdd %float {fl} %f1")
6664 self.emit(f"{fl} = OpExtInst %float %glsl Floor {x}") 6800 self.emit(f"{rounded} = OpSelect %float {ge_half} {fl_plus1} {fl}")
6665 bits = self.tou(fl) 6801 fl = rounded
6666 magnitude, negative, not_nan, bound, in_range, saturated, safe, signed, converted, result = \ 6802 self.emit(f"{signed} = OpConvertFToS %int {fl}")
6667 (self.tmp() for _ in range(10))
6668 self.emit(f"{magnitude} = OpBitwiseAnd %uint {bits} {self.cu(0x7FFFFFFF)}")
6669 self.emit(f"{in_range} = OpULessThan %bool {magnitude} {self.cu(0x4F000000)}") # |x| < 2^31
6670 self.emit(f"{negative} = OpINotEqual %bool {bits} {magnitude}")
6671 self.emit(f"{not_nan} = OpULessThan %bool {magnitude} {self.cu(0x7F800001)}")
6672 self.emit(f"{bound} = OpSelect %uint {negative} {self.cu(0x80000000)} {self.cu(0x7FFFFFFF)}")
6673 self.emit(f"{saturated} = OpSelect %uint {not_nan} {bound} {self.cu(0)}")
6674 # Convert only an in-range operand: SPIR-V leaves the out-of-range conversion undefined.
6675 self.emit(f"{safe} = OpSelect %uint {in_range} {bits} {self.cu(0)}")
6676 self.emit(f"{signed} = OpConvertFToS %int {self.tof(safe)}")
6677 self.emit(f"{converted} = OpBitcast %uint {signed}") 6803 self.emit(f"{converted} = OpBitcast %uint {signed}")
6678 self.emit(f"{result} = OpSelect %uint {in_range} {converted} {saturated}") 6804 self.emit(f"{result} = OpSelect %uint {x_in_range} {converted} {bound}")
6679 self.dst(a[0], result) 6805 self.dst(a[0], result)
6680 elif op in ("v_cvt_u32_f32", "v_cvt_i32_f32"): 6806 elif op in ("v_cvt_u32_f32", "v_cvt_i32_f32"):
6681 # Compare binary32 words before converting: the raw SPIR-V conversion 6807 # Compare binary32 words before converting: the raw SPIR-V conversion
@@ -6749,9 +6875,9 @@ class Gen:
6749 m = self.tmp() 6875 m = self.tmp()
6750 self.emit(f"{m} = OpBitwiseAnd %uint {y_raw} {self.cu(31)}") 6876 self.emit(f"{m} = OpBitwiseAnd %uint {y_raw} {self.cu(31)}")
6751 y = m 6877 y = m
6878 x = self.src_u(a[1])
6752 else: 6879 else:
6753 y = self.src_u(a[2]) 6880 x, y = self.sop2_b32_srcs(op, a) # lane-mask sources as mask_src (s_and/or_b32 on EXEC)
6754 x = self.src_u(a[1])
6755 self.emit(f"{r} = {kind} %uint {x} {y}") 6881 self.emit(f"{r} = {kind} %uint {x} {y}")
6756 self.dst(a[0], r) 6882 self.dst(a[0], r)
6757 if op in ("s_and_b32", "s_or_b32"): 6883 if op in ("s_and_b32", "s_or_b32"):
@@ -6873,6 +6999,24 @@ class Gen:
6873 self.emit(f"{m} = OpIMul %uint {hs[0]} {hs[1]}") 6999 self.emit(f"{m} = OpIMul %uint {hs[0]} {hs[1]}")
6874 self.emit(f"{r} = OpIAdd %uint {m} {self.src_u(a[3])}") 7000 self.emit(f"{r} = OpIAdd %uint {m} {self.src_u(a[3])}")
6875 self.dst(a[0], r) 7001 self.dst(a[0], r)
7002 elif op in ("v_dot4_i32_i8", "v_dot4c_i32_i8"):
7003 # The four products of the signed bytes of two dwords, summed, plus an addend: the third source for
7004 # v_dot4_i32_i8 (VOP3P), the destination's old value for v_dot4c_i32_i8 (VOP2). The sum wraps at 32 bits.
7005 # Measured on RDNA2 hardware (docs/design.md, "Signed-byte dot products"), where clamp saturates
7006 # v_dot4_i32_i8 to a signed 32-bit value and op_sel picks the 16-bit half of a source each half of the
7007 # product reads. llvm-mc prints neither for the programs measured, so both forms are refused, not guessed.
7008 if "clamp" in mods or any(m.startswith("op_sel") for m in mods):
7009 raise Unsupported(op + (" clamp" if "clamp" in mods else " op_sel"))
7010 x, y = self.src_u(a[1]), self.src_u(a[2])
7011 acc = self.src_u(a[3]) if op == "v_dot4_i32_i8" else self.src_u(a[0])
7012 for i in range(4):
7013 xb, yb, prod, total = (self.tmp() for _ in range(4))
7014 self.emit(f"{xb} = OpBitFieldSExtract %uint {x} {self.cu(8 * i)} {self.cu(8)}")
7015 self.emit(f"{yb} = OpBitFieldSExtract %uint {y} {self.cu(8 * i)} {self.cu(8)}")
7016 self.emit(f"{prod} = OpIMul %uint {xb} {yb}")
7017 self.emit(f"{total} = OpIAdd %uint {acc} {prod}")
7018 acc = total
7019 self.dst(a[0], acc)
6876 elif op == "v_mad_u32_u24": 7020 elif op == "v_mad_u32_u24":
6877 x, y, z = (self.src_u(t) for t in a[1:4]) 7021 x, y, z = (self.src_u(t) for t in a[1:4])
6878 xm, ym, p, r = self.tmp(), self.tmp(), self.tmp(), self.tmp() 7022 xm, ym, p, r = self.tmp(), self.tmp(), self.tmp(), self.tmp()
@@ -9046,6 +9190,11 @@ def assemble(gen):
9046 used = set(gen.inputs.values()) 9190 used = set(gen.inputs.values())
9047 if len(used) != len(gen.inputs): # --f16-interp-fallback: a decoded-half location is also an attribute 9191 if len(used) != len(gen.inputs): # --f16-interp-fallback: a decoded-half location is also an attribute
9048 raise Unsupported("--f16-interp-fallback: a decoded-half location is also read as an attribute") 9192 raise Unsupported("--f16-interp-fallback: a decoded-half location is also read as an attribute")
9193 # The producer fills both halves of every attribute in f16_halves (the index's f16_halves lists the pair), so a
9194 # raw attribute at the location of a half this shader doesn't read is overwritten all the same.
9195 reserved = {f16_half_location(n, h) for n in gen.f16_halves for h in (0, 1)}
9196 if any(not k.startswith("%in_f16h") and v in reserved for k, v in gen.inputs.items()):
9197 raise Unsupported("--f16-interp-fallback: a decoded-half location is also read as an attribute")
9049 gen.bary_location = next(n for n in range(len(used) + 1) if n not in used) if bary and BARY_FALLBACK else None 9198 gen.bary_location = next(n for n in range(len(used) + 1) if n not in used) if bary and BARY_FALLBACK else None
9050 bary_builtin = bary and gen.bary_location is None 9199 bary_builtin = bary and gen.bary_location is None
9051 if gen.frag_inputs or bary: 9200 if gen.frag_inputs or bary:
@@ -10000,7 +10149,8 @@ def read_before_write_vgprs(insns):
10000 a, op = ins["args"], ins["op"] 10149 a, op = ins["args"], ins["op"]
10001 if not a: 10150 if not a:
10002 continue 10151 continue
10003 reads_all = op.startswith(("exp", "buffer_store", "image_store", "v_cmp", "v_cmpx", "ds_write", "global_store")) \ 10152 reads_all = op.startswith(("exp", "buffer_store", "tbuffer_store", "image_store", "v_cmp", "v_cmpx", "ds_write",
10153 "global_store")) \
10004 or (op.startswith("global_atomic_") and "glc" not in ins["mods"]) # no vdst without glc 10154 or (op.startswith("global_atomic_") and "glc" not in ins["mods"]) # no vdst without glc
10005 regs = [] 10155 regs = []
10006 for x in (a if reads_all else a[1:]): 10156 for x in (a if reads_all else a[1:]):
@@ -10008,7 +10158,7 @@ def read_before_write_vgprs(insns):
10008 regs += range(x["r"], x["r"] + x.get("n", 1)) 10158 regs += range(x["r"], x["r"] + x.get("n", 1))
10009 elif x["k"] == "vlist": 10159 elif x["k"] == "vlist":
10010 regs += x["r"] 10160 regs += x["r"]
10011 if (base_op(op) in ("v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16") or 10161 if (base_op(op) in ("v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16", "v_dot4c_i32_i8") or
10012 (op.startswith("global_load_") and "_d16" in op)) and a[0]["k"] == "vgpr": # d16 keeps a half 10162 (op.startswith("global_load_") and "_d16" in op)) and a[0]["k"] == "vgpr": # d16 keeps a half
10013 regs.append(a[0]["r"]) 10163 regs.append(a[0]["r"])
10014 for r in regs: 10164 for r in regs:
@@ -10058,7 +10208,8 @@ def interp_ij_analysis(insns, g):
10058 a, op = ins["args"], ins["op"] 10208 a, op = ins["args"], ins["op"]
10059 if not a: 10209 if not a:
10060 continue 10210 continue
10061 reads_all = op.startswith(("exp", "buffer_store", "image_store", "v_cmp", "v_cmpx", "ds_write", "global_store")) 10211 reads_all = op.startswith(("exp", "buffer_store", "tbuffer_store", "image_store", "v_cmp", "v_cmpx", "ds_write",
10212 "global_store"))
10062 if not reads_all and a[0]["k"] == "vgpr": 10213 if not reads_all and a[0]["k"] == "vgpr":
10063 for r in range(a[0]["r"], a[0]["r"] + a[0].get("n", 1)): 10214 for r in range(a[0]["r"], a[0]["r"] + a[0].get("n", 1)):
10064 writes[r].append(n) 10215 writes[r].append(n)
@@ -10229,14 +10380,15 @@ def reg_reads_writes(insns):
10229 a, op = ins["args"], ins["op"] 10380 a, op = ins["args"], ins["op"]
10230 if not a: 10381 if not a:
10231 continue 10382 continue
10232 reads_all = op.startswith(("exp", "buffer_store", "image_store", "v_cmp", "v_cmpx", "ds_write", "global_store")) 10383 reads_all = op.startswith(("exp", "buffer_store", "tbuffer_store", "image_store", "v_cmp", "v_cmpx", "ds_write",
10384 "global_store"))
10233 regs = [] 10385 regs = []
10234 for x in (a if reads_all else a[1:]): 10386 for x in (a if reads_all else a[1:]):
10235 if x["k"] == "vgpr": 10387 if x["k"] == "vgpr":
10236 regs += range(x["r"], x["r"] + x.get("n", 1)) 10388 regs += range(x["r"], x["r"] + x.get("n", 1))
10237 elif x["k"] == "vlist": 10389 elif x["k"] == "vlist":
10238 regs += x["r"] 10390 regs += x["r"]
10239 if base_op(op) in ("v_fmac_f32", "v_mac_f32", "v_fmac_f16") and a[0]["k"] == "vgpr": 10391 if base_op(op) in ("v_fmac_f32", "v_mac_f32", "v_fmac_f16", "v_dot4c_i32_i8") and a[0]["k"] == "vgpr":
10240 regs.append(a[0]["r"]) 10392 regs.append(a[0]["r"])
10241 rr.update(regs) 10393 rr.update(regs)
10242 if not reads_all and a[0]["k"] == "vgpr": 10394 if not reads_all and a[0]["k"] == "vgpr":
@@ -10463,6 +10615,10 @@ def translate(path):
10463 if stage not in ("vs", "ps", "cs", "ms", "gs"): 10615 if stage not in ("vs", "ps", "cs", "ms", "gs"):
10464 raise Unsupported(f"stage {stage}") 10616 raise Unsupported(f"stage {stage}")
10465 insns = info["insns"] 10617 insns = info["insns"]
10618 if not insns:
10619 # parse_file only reads tab-indented instructions, so a hand-written or re-indented .s parses to nothing
10620 # and used to translate to a module that passes spirv-val and does no work at all. Refuse it instead.
10621 raise Unsupported("no instructions (nothing tab-indented?)")
10466 if info["invalid"]: 10622 if info["invalid"]:
10467 # Undecodable words are constant tables embedded in the code range (147/155 such VS/PS use s_getpc_b64 to 10623 # Undecodable words are constant tables embedded in the code range (147/155 such VS/PS use s_getpc_b64 to
10468 # read them). LLVM skips them, so re-anchor every instruction to its true offset in the FSSM blob, then 10624 # read them). LLVM skips them, so re-anchor every instruction to its true offset in the FSSM blob, then
@@ -11302,13 +11458,95 @@ def write_index(path, index):
11302 """Write an index under another name and rename it into place, so a run stopped part-way never leaves half of 11458 """Write an index under another name and rename it into place, so a run stopped part-way never leaves half of
11303 one: make_game.py takes these files as proof that a shard, or the whole translation, finished.""" 11459 one: make_game.py takes these files as proof that a shard, or the whole translation, finished."""
11304 tmp = path + ".tmp" # must not end in .json: --merge globs index.part*.json 11460 tmp = path + ".tmp" # must not end in .json: --merge globs index.part*.json
11305 with open(tmp, "w", encoding="utf-8") as f: 11461 with open(tmp, "w", encoding="utf-8", newline="\n") as f:
11306 _json.dump(index, f, indent=0, sort_keys=True) 11462 _json.dump(index, f, indent=0, sort_keys=True)
11307 f.flush() 11463 f.flush()
11308 os.fsync(f.fileno()) # on disk before the rename, or a power cut could leave the name with no data 11464 os.fsync(f.fileno()) # on disk before the rename, or a power cut could leave the name with no data
11309 os.replace(tmp, path) # ponytail: no retry; add one if a scanner on Windows ever holds the new file open 11465 os.replace(tmp, path) # ponytail: no retry; add one if a scanner on Windows ever holds the new file open
11310 11466
11311 11467
11468class ShardSetError(Exception):
11469 """The index parts on disk are not one complete shard set: merging them would publish a partial index."""
11470
11471
11472SHARD_MARKER = "shard{index}.json"
11473
11474
11475def _read_shard_markers(out):
11476 """{index: count} from the shard<i>.json markers a --shard run writes beside its index.part<i>.json."""
11477 import glob as _gl, json as _js
11478 markers = {}
11479 for path in sorted(_gl.glob(os.path.join(out, "shard*.json"))):
11480 m = re.fullmatch(r"shard(\d+)\.json", os.path.basename(path))
11481 if not m: # make_game.py's shards.json plan is not a marker
11482 continue
11483 with open(path, encoding="utf-8") as f:
11484 doc = _js.load(f)
11485 try:
11486 index, count = int(doc["index"]), int(doc["count"])
11487 except (KeyError, TypeError, ValueError):
11488 raise ShardSetError(f"{path} is not a shard marker (expected an object with \"index\" and \"count\")") from None
11489 if index != int(m.group(1)):
11490 raise ShardSetError(f"{path} is a marker for shard {index}, but its name says shard {m.group(1)}")
11491 if index in markers and markers[index] != count:
11492 raise ShardSetError(f"shard markers disagree on the shard count: {path}")
11493 markers[index] = count
11494 return markers
11495
11496
11497def merge_shard_parts(out):
11498 """{shader: meta} from index.part*.json, after checking the set is complete.
11499
11500 A --shard i/n run writes index.part<i>.json and shard<i>.json ({"index": i, "count": n}); the markers say how
11501 many parts the set has. Parts from before the markers existed fall back to make_game.py's shards.json plan.
11502 With neither there is no way to know the count, so the old merge-everything behaviour is kept."""
11503 import glob as _gl, json as _js
11504 parts = sorted(_gl.glob(os.path.join(out, "index.part*.json")))
11505 indices = []
11506 for part in parts:
11507 m = re.search(r"index\.part(\d+)\.json$", part)
11508 if not m:
11509 raise ShardSetError(f"{part} is not an index.part<i>.json file")
11510 indices.append(int(m.group(1)))
11511 if len(set(indices)) != len(indices):
11512 raise ShardSetError(f"index.part*.json has two parts with the same index: {sorted(indices)}")
11513 markers = _read_shard_markers(out)
11514 expected = None
11515 if markers:
11516 counts = set(markers.values())
11517 if len(counts) != 1:
11518 raise ShardSetError(f"shard markers disagree on the shard count: {sorted(counts)}")
11519 expected = counts.pop()
11520 else:
11521 plan = os.path.join(out, "shards.json")
11522 if os.path.isfile(plan):
11523 try:
11524 with open(plan, encoding="utf-8") as f:
11525 expected = int(_js.load(f).get("jobs") or 0) or None
11526 except (OSError, ValueError, TypeError, AttributeError):
11527 expected = None
11528 if expected is not None:
11529 missing = [i for i in range(expected) if i not in set(indices)]
11530 extra = [i for i in indices if i >= expected]
11531 if missing or extra:
11532 raise ShardSetError(
11533 f"incomplete shard set: {len(indices)} of {expected} parts (0..{expected - 1})"
11534 + (f", missing {missing}" if missing else "")
11535 + (f", unexpected {extra}" if extra else "")
11536 + "; let every --shard run finish before --merge")
11537 if markers and set(markers) != set(indices):
11538 raise ShardSetError(f"index parts and shard markers disagree: parts {sorted(set(indices))}, "
11539 f"markers {sorted(markers)}")
11540 merged = {}
11541 for part in parts:
11542 with open(part, encoding="utf-8") as f:
11543 doc = _js.load(f)
11544 if not isinstance(doc, dict):
11545 raise ShardSetError(f"{part} does not contain a shader index object")
11546 merged.update(doc)
11547 return merged
11548
11549
11312def assemble_spirv(sa, sv): 11550def assemble_spirv(sa, sv):
11313 """Keep the assembled module out of the final path until validation succeeds.""" 11551 """Keep the assembled module out of the final path until validation succeeds."""
11314 with tempfile.NamedTemporaryFile(prefix=".spirv-", suffix=".tmp", dir=os.path.dirname(sv), delete=False) as f: 11552 with tempfile.NamedTemporaryFile(prefix=".spirv-", suffix=".tmp", dir=os.path.dirname(sv), delete=False) as f:
@@ -11411,11 +11649,11 @@ def main():
11411 MESH_COMPUTE = a.mesh_compute 11649 MESH_COMPUTE = a.mesh_compute
11412 F16_HALVES = a.f16_interp_fallback 11650 F16_HALVES = a.f16_interp_fallback
11413 if a.merge: 11651 if a.merge:
11414 import glob as _gl, json as _js 11652 try:
11415 merged = {} 11653 merged = merge_shard_parts(a.out)
11416 for part in sorted(_gl.glob(os.path.join(a.out, "index.part*.json"))): 11654 except ShardSetError as e:
11417 with open(part, encoding="utf-8") as f: 11655 print(f"ERROR: {e}", file=sys.stderr)
11418 merged.update(_js.load(f)) 11656 return 2
11419 # The stubs go first: index.json is what tells make_game.py the translation finished. 11657 # The stubs go first: index.json is what tells make_game.py the translation finished.
11420 import spirv_stubs 11658 import spirv_stubs
11421 spirv_stubs.generate_for_index(a.out, merged) 11659 spirv_stubs.generate_for_index(a.out, merged)
@@ -11439,20 +11677,30 @@ def main():
11439 why, ok, valid = Counter(), 0, 0 11677 why, ok, valid = Counter(), 0, 0
11440 meta = {} 11678 meta = {}
11441 invalid = set() 11679 invalid = set()
11680
11681 def drop_stale(name):
11682 # A shader that no longer translates must not stay published from an earlier run: remove its old
11683 # module, and the index merge below drops its entry, exactly like a spirv-as/val rejection. The
11684 # .spvasm text stays for diagnosis, as it does on a rejection.
11685 Path(os.path.join(a.out, name + ".spv")).unlink(missing_ok=True)
11686 invalid.add(name)
11687
11442 for p in files: 11688 for p in files:
11443 name = os.path.splitext(os.path.basename(p))[0] 11689 name = os.path.splitext(os.path.basename(p))[0]
11444 try: 11690 try:
11445 asm = translate(p) 11691 asm = translate(p)
11446 except Unsupported as e: 11692 except Unsupported as e:
11447 why[str(e)] += 1 11693 why[str(e)] += 1
11694 drop_stale(name)
11448 continue 11695 continue
11449 except (IndexError, KeyError, ValueError) as e: 11696 except (IndexError, KeyError, ValueError) as e:
11450 why[f"translator error {type(e).__name__}"] += 1 11697 why[f"translator error {type(e).__name__}"] += 1
11698 drop_stale(name)
11451 continue 11699 continue
11452 ok += 1 11700 ok += 1
11453 sa = os.path.join(a.out, name + ".spvasm") 11701 sa = os.path.join(a.out, name + ".spvasm")
11454 sv = os.path.join(a.out, name + ".spv") 11702 sv = os.path.join(a.out, name + ".spv")
11455 with open(sa, "w") as f: 11703 with open(sa, "w", newline="\n") as f:
11456 f.write(asm) 11704 f.write(asm)
11457 r = assemble_spirv(sa, sv) 11705 r = assemble_spirv(sa, sv)
11458 if r.returncode == 0: 11706 if r.returncode == 0:
@@ -11463,7 +11711,7 @@ def main():
11463 except Exception as e: # noqa: BLE001 - metadata must never cost a translation 11711 except Exception as e: # noqa: BLE001 - metadata must never cost a translation
11464 meta[name] = {"error": f"{type(e).__name__}: {e}"} 11712 meta[name] = {"error": f"{type(e).__name__}: {e}"}
11465 else: 11713 else:
11466 invalid.add(name) 11714 drop_stale(name)
11467 why["INVALID: " + (r.stderr.strip().splitlines() or ["?"])[0][:90]] += 1 11715 why["INVALID: " + (r.stderr.strip().splitlines() or ["?"])[0][:90]] += 1
11468 if a.no_asm and os.path.exists(sa): 11716 if a.no_asm and os.path.exists(sa):
11469 os.remove(sa) 11717 os.remove(sa)
@@ -11476,6 +11724,8 @@ def main():
11476 for name in invalid: 11724 for name in invalid:
11477 old.pop(name, None) 11725 old.pop(name, None)
11478 old.update(meta) 11726 old.update(meta)
11727 if shard is not None: # a marker beside the part, so --merge can tell a complete set from a partial one
11728 write_index(os.path.join(a.out, SHARD_MARKER.format(index=shard)), {"index": shard, "count": sn})
11479 write_index(idx_path, old) 11729 write_index(idx_path, old)
11480 if shard is None: 11730 if shard is None:
11481 import spirv_stubs 11731 import spirv_stubs
diff --git a/tools/restofworld_index.py b/tools/restofworld_index.py
index c890cf65b..76b263ded 100644
--- a/tools/restofworld_index.py
+++ b/tools/restofworld_index.py
@@ -322,7 +322,7 @@ def summarise(rows, span, zero, unread):
322def write_output(path, rows, summary): 322def write_output(path, rows, summary):
323 """Write CSV or JSON from the file extension.""" 323 """Write CSV or JSON from the file extension."""
324 if os.path.splitext(path)[1].lower() == ".json": 324 if os.path.splitext(path)[1].lower() == ".json":
325 with open(path, "w", encoding="utf-8") as f: 325 with open(path, "w", encoding="utf-8", newline="\n") as f:
326 json.dump({"summary": summary, "files": rows}, f, indent=1) 326 json.dump({"summary": summary, "files": rows}, f, indent=1)
327 return 327 return
328 with open(path, "w", encoding="utf-8", newline="") as f: 328 with open(path, "w", encoding="utf-8", newline="") as f:
diff --git a/tools/rpf9_carve.py b/tools/rpf9_carve.py
index 43863d4cf..9621ea212 100644
--- a/tools/rpf9_carve.py
+++ b/tools/rpf9_carve.py
@@ -162,7 +162,7 @@ def main() -> int:
162 "bink2_files": sum(1 for r in rows if r.get("type") == "bink2"), 162 "bink2_files": sum(1 for r in rows if r.get("type") == "bink2"),
163 "zero_padding": zero, "unread_bytes": unread, 163 "zero_padding": zero, "unread_bytes": unread,
164 "span": span} 164 "span": span}
165 with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8") as f: 165 with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8", newline="\n") as f:
166 json.dump({"summary": summary, "files": rows}, f) 166 json.dump({"summary": summary, "files": rows}, f)
167 print(json.dumps(summary, indent=1)) 167 print(json.dumps(summary, indent=1))
168 span = max(1, span) # an empty data area (or --start at the end) has nothing to divide by 168 span = max(1, span) # an empty data area (or --start at the end) has nothing to divide by
diff --git a/tools/rpf9_names.py b/tools/rpf9_names.py
index f131f82d6..f2d50e8fc 100644
--- a/tools/rpf9_names.py
+++ b/tools/rpf9_names.py
@@ -207,7 +207,7 @@ def publish_report(path, rows, summary):
207 os.makedirs(directory, exist_ok=True) 207 os.makedirs(directory, exist_ok=True)
208 with tempfile.TemporaryDirectory(dir=directory, prefix=".rpf9_names-") as stage_dir: 208 with tempfile.TemporaryDirectory(dir=directory, prefix=".rpf9_names-") as stage_dir:
209 temp = os.path.join(stage_dir, "report.json") 209 temp = os.path.join(stage_dir, "report.json")
210 with open(temp, "w", encoding="utf-8") as f: 210 with open(temp, "w", encoding="utf-8", newline="\n") as f:
211 json.dump({"summary": summary, "files": rows}, f, indent=1) 211 json.dump({"summary": summary, "files": rows}, f, indent=1)
212 f.write("\n") 212 f.write("\n")
213 os.chmod(temp, published_mode(path)) 213 os.chmod(temp, published_mode(path))
diff --git a/tools/rpf_probe.py b/tools/rpf_probe.py
index 7cfe678dc..49b512b3d 100644
--- a/tools/rpf_probe.py
+++ b/tools/rpf_probe.py
@@ -84,7 +84,7 @@ def main() -> int:
84 os.makedirs(out_dir, exist_ok=True) 84 os.makedirs(out_dir, exist_ok=True)
85 with tempfile.TemporaryDirectory(dir=out_dir) as staging: 85 with tempfile.TemporaryDirectory(dir=out_dir) as staging:
86 staged = os.path.join(staging, "rpf_probe.json") 86 staged = os.path.join(staging, "rpf_probe.json")
87 with open(staged, "w", encoding="utf-8") as f: 87 with open(staged, "w", encoding="utf-8", newline="\n") as f:
88 json.dump(rows, f, indent=1) 88 json.dump(rows, f, indent=1)
89 os.replace(staged, a.out) 89 os.replace(staged, a.out)
90 except OSError as error: 90 except OSError as error:
diff --git a/tools/salu_diff.py b/tools/salu_diff.py
index 244bee384..9108d5e01 100644
--- a/tools/salu_diff.py
+++ b/tools/salu_diff.py
@@ -71,7 +71,8 @@ OUT_SCC = 30 # s_cselect_b32 s30, 1, 0 observes SCC at the end
71BFE_ANY = False # any s_bfe_* control word (--bfe-any), not only offset + width <= 32 71BFE_ANY = False # any s_bfe_* control word (--bfe-any), not only offset + width <= 32
72INLINE64 = False # inline constants in 64-bit positions (--inline64); the translator reads those as lane masks 72INLINE64 = False # inline constants in 64-bit positions (--inline64); the translator reads those as lane masks
73 73
74LANE_MASK_OPS = ("s_and_b64", "s_or_b64", "s_xor_b64", "s_andn2_b64", "s_orn2_b64", "s_not_b64", "s_wqm_b64", 74LANE_MASK_OPS = ("s_and_b64", "s_or_b64", "s_xor_b64", "s_andn2_b64", "s_orn2_b64", "s_nand_b64", "s_nor_b64",
75 "s_xnor_b64", "s_not_b64", "s_wqm_b64",
75 "s_wqm_b32", "s_cselect_b64", "s_bfm_b64") 76 "s_wqm_b32", "s_cselect_b64", "s_bfm_b64")
76 77
77INTERESTING = (0, 1, 2, 3, 31, 32, 33, 63, 64, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFF, 0xFFFFFFFE, 78INTERESTING = (0, 1, 2, 3, 31, 32, 33, 63, 64, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFF, 0xFFFFFFFE,
@@ -172,7 +173,9 @@ def _sop2():
172def _sop2_64(): 173def _sop2_64():
173 ops = {} 174 ops = {}
174 for name, f in (("and", lambda a, b: a & b), ("or", lambda a, b: a | b), ("xor", lambda a, b: a ^ b), 175 for name, f in (("and", lambda a, b: a & b), ("or", lambda a, b: a | b), ("xor", lambda a, b: a ^ b),
175 ("andn2", lambda a, b: a & ~b), ("orn2", lambda a, b: a | ~b)): 176 ("andn2", lambda a, b: a & ~b), ("orn2", lambda a, b: a | ~b),
177 ("nand", lambda a, b: ~(a & b)), ("nor", lambda a, b: ~(a | b)),
178 ("xnor", lambda a, b: ~(a ^ b))):
176 ops[f"s_{name}_b64"] = ("sop2_64", lambda a, b, c, f=f: (f(a, b) & M64, int(f(a, b) & M64 != 0))) 179 ops[f"s_{name}_b64"] = ("sop2_64", lambda a, b, c, f=f: (f(a, b) & M64, int(f(a, b) & M64 != 0)))
177 ops["s_cselect_b64"] = ("sop2_64", lambda a, b, c: (a if c else b, None)) 180 ops["s_cselect_b64"] = ("sop2_64", lambda a, b, c: (a if c else b, None))
178 ops["s_lshl_b64"] = ("sop2_64s", lambda a, b, c: ((a << (b & 63)) & M64, int((a << (b & 63)) & M64 != 0))) 181 ops["s_lshl_b64"] = ("sop2_64s", lambda a, b, c: ((a << (b & 63)) & M64, int((a << (b & 63)) & M64 != 0)))
@@ -493,7 +496,7 @@ def translated(lines, name="ps_salu"):
493 dis = os.path.join(tmp, "disasm") 496 dis = os.path.join(tmp, "disasm")
494 os.mkdir(dis) 497 os.mkdir(dis)
495 path = os.path.join(dis, name + ".s") 498 path = os.path.join(dis, name + ".s")
496 with open(path, "w", encoding="utf-8") as f: 499 with open(path, "w", encoding="utf-8", newline="\n") as f:
497 if has_branches(lines): 500 if has_branches(lines):
498 # The translator places branch targets from the encoding sizes; it does not read the bytes. 501 # The translator places branch targets from the encoding sizes; it does not read the bytes.
499 body = listing(lines + ["exp mrt0 v8, v9, v10, v11 done vm", "s_endpgm"]) 502 body = listing(lines + ["exp mrt0 v8, v9, v10, v11 done vm", "s_endpgm"])
diff --git a/tools/save_keys.py b/tools/save_keys.py
index a5280b9cc..503b42bad 100644
--- a/tools/save_keys.py
+++ b/tools/save_keys.py
@@ -317,7 +317,7 @@ def cmd_resolve(a):
317 print(f" total (joaat) {len(resolved):6} of {len(keys)} keys ({100 * len(resolved) / max(1, len(keys)):.1f}%)") 317 print(f" total (joaat) {len(resolved):6} of {len(keys)} keys ({100 * len(resolved) / max(1, len(keys)):.1f}%)")
318 if a.out: 318 if a.out:
319 try: 319 try:
320 with open(a.out, "w", encoding="utf-8") as f: 320 with open(a.out, "w", encoding="utf-8", newline="\n") as f:
321 json.dump({"%08x" % k: sorted(x.decode("latin-1") for x in v) for k, v in sorted(resolved.items())}, 321 json.dump({"%08x" % k: sorted(x.decode("latin-1") for x in v) for k, v in sorted(resolved.items())},
322 f, indent=1) 322 f, indent=1)
323 except OSError as e: 323 except OSError as e:
@@ -337,6 +337,8 @@ def main(argv=None):
337 r.add_argument("--compose", type=int, default=0, metavar="N") 337 r.add_argument("--compose", type=int, default=0, metavar="N")
338 r.add_argument("--out") 338 r.add_argument("--out")
339 a = ap.parse_args(argv) 339 a = ap.parse_args(argv)
340 if a.cmd == "resolve" and a.compose < 0:
341 r.error("--compose must be 0 or more")
340 return {"collect": cmd_collect, "resolve": cmd_resolve}[a.cmd](a) or 0 342 return {"collect": cmd_collect, "resolve": cmd_resolve}[a.cmd](a) or 0
341 343
342 344
diff --git a/tools/saves.py b/tools/saves.py
index a7fcef116..428346305 100644
--- a/tools/saves.py
+++ b/tools/saves.py
@@ -14,7 +14,7 @@ Commands
14 diff <JSAV a> <JSAV b> list blocks that were added, removed or changed between two saves 14 diff <JSAV a> <JSAV b> list blocks that were added, removed or changed between two saves
15 import <save dir>... [--out DIR] [--map OLD=CONTAINER/BLOB]... [--with-packed] [--force] [--dry-run] 15 import <save dir>... [--out DIR] [--map OLD=CONTAINER/BLOB]... [--with-packed] [--force] [--dry-run]
16 copy the ASAV/JSAV payloads out of plain save folders into the on-disk layout 16 copy the ASAV/JSAV payloads out of plain save folders into the on-disk layout
17 of the offline XGameSave shim (runtime/shims/xgameruntime_services.cpp): 17 of the offline XGameSave shim of the open #279 (not on main yet):
18 DIR/local-user/<container>/<blob>, names %-encoded the same way. 18 DIR/local-user/<container>/<blob>, names %-encoded the same way.
19 DIR defaults to %LOCALAPPDATA%\\Leonida\\saves (the shim's LEONIDA_SAVE_DIR default). 19 DIR defaults to %LOCALAPPDATA%\\Leonida\\saves (the shim's LEONIDA_SAVE_DIR default).
20 VERIFY: container/blob names are a guess until the executable shows them; by default 20 VERIFY: container/blob names are a guess until the executable shows them; by default
@@ -245,16 +245,16 @@ def extract(p, out):
245 e['file'] = f'blocks/{e["index"]:03d}_{e["group"]}_{e["hash"]}.json' 245 e['file'] = f'blocks/{e["index"]:03d}_{e["group"]}_{e["hash"]}.json'
246 with open(os.path.join(out, e['file']), 'wb') as f: 246 with open(os.path.join(out, e['file']), 'wb') as f:
247 f.write(b) 247 f.write(b)
248 with open(os.path.join(out, 'index.json'), 'w') as f: 248 with open(os.path.join(out, 'index.json'), 'w', newline="\n") as f:
249 json.dump({'header': h, 'entries': es}, f, indent=1) 249 json.dump({'header': h, 'entries': es}, f, indent=1)
250 body = d[h['body_offset']:h['body_end']].decode('utf-8') 250 body = d[h['body_offset']:h['body_end']].decode('utf-8')
251 with open(os.path.join(out, 'save.pretty.json'), 'w', encoding='utf-8') as f: 251 with open(os.path.join(out, 'save.pretty.json'), 'w', encoding='utf-8', newline="\n") as f:
252 json.dump(json.loads(body), f, indent=1) 252 json.dump(json.loads(body), f, indent=1)
253 print(f'{len(es)} blocks -> {out}') 253 print(f'{len(es)} blocks -> {out}')
254 elif k == 'ASAV': 254 elif k == 'ASAV':
255 h = parse_asav(d) 255 h = parse_asav(d)
256 pl = asav_payload(d, h) 256 pl = asav_payload(d, h)
257 with open(os.path.join(out, 'header.json'), 'w') as f: 257 with open(os.path.join(out, 'header.json'), 'w', newline="\n") as f:
258 json.dump(h, f, indent=1) 258 json.dump(h, f, indent=1)
259 with open(os.path.join(out, 'header.bin'), 'wb') as f: 259 with open(os.path.join(out, 'header.bin'), 'wb') as f:
260 f.write(d[:h['payload_offset']]) 260 f.write(d[:h['payload_offset']])
@@ -263,7 +263,7 @@ def extract(p, out):
263 if pl[:1] == b'{': 263 if pl[:1] == b'{':
264 try: 264 try:
265 obj = json.loads(pl.rstrip(b'\0').decode('utf-8')) 265 obj = json.loads(pl.rstrip(b'\0').decode('utf-8'))
266 with open(os.path.join(out, 'payload.json'), 'w', encoding='utf-8') as f: 266 with open(os.path.join(out, 'payload.json'), 'w', encoding='utf-8', newline="\n") as f:
267 json.dump(obj, f, indent=1) 267 json.dump(obj, f, indent=1)
268 except ValueError as ex: 268 except ValueError as ex:
269 print('payload looks like text but did not parse as JSON:', ex) 269 print('payload looks like text but did not parse as JSON:', ex)
@@ -467,7 +467,7 @@ def import_saves(args):
467 with open(tmp, 'wb') as f: 467 with open(tmp, 'wb') as f:
468 f.write(read(src)) 468 f.write(read(src))
469 os.replace(tmp, dst) 469 os.replace(tmp, dst)
470 with open(os.path.join(out, 'import-manifest.json'), 'w', encoding='utf-8') as f: 470 with open(os.path.join(out, 'import-manifest.json'), 'w', encoding='utf-8', newline="\n") as f:
471 json.dump(manifest, f, indent=1) 471 json.dump(manifest, f, indent=1)
472 print(f'wrote {len(plan)} blobs under {root}') 472 print(f'wrote {len(plan)} blobs under {root}')
473 473
diff --git a/tools/shader_carve.py b/tools/shader_carve.py
index 15fb02c4d..a2252628a 100644
--- a/tools/shader_carve.py
+++ b/tools/shader_carve.py
@@ -116,10 +116,13 @@ def main(argv=None) -> int:
116 f.write(data) 116 f.write(data)
117 index.append({"name": name, "file": fname, "offset": mt.start(), "kind": mt.group(2)[0], 117 index.append({"name": name, "file": fname, "offset": mt.start(), "kind": mt.group(2)[0],
118 "stage": stage, "sm": sm, "size": size, "parts": {k: v[1] for k, v in p.items()}}) 118 "stage": stage, "sm": sm, "size": size, "parts": {k: v[1] for k, v in p.items()}})
119 if not index:
120 print(f"ERROR: no shaders carved from {src} (rejected candidates: {bad}).", file=sys.stderr)
121 return 1
119 # make_game.py takes index.json as proof the carve finished: write it last, under another name, then rename. 122 # make_game.py takes index.json as proof the carve finished: write it last, under another name, then rename.
120 with tempfile.TemporaryDirectory(dir=out, prefix=".shader-index-") as staging: 123 with tempfile.TemporaryDirectory(dir=out, prefix=".shader-index-") as staging:
121 tmp = os.path.join(staging, "index.json") 124 tmp = os.path.join(staging, "index.json")
122 with open(tmp, "w", encoding="utf-8") as f: 125 with open(tmp, "w", encoding="utf-8", newline="\n") as f:
123 json.dump(index, f, indent=1) 126 json.dump(index, f, indent=1)
124 f.flush() 127 f.flush()
125 os.fsync(f.fileno()) 128 os.fsync(f.fileno())
diff --git a/tools/shader_diff.py b/tools/shader_diff.py
index c42bcf22f..4b52ab7ba 100644
--- a/tools/shader_diff.py
+++ b/tools/shader_diff.py
@@ -177,7 +177,7 @@ def generate_program(rng, n_ops):
177 177
178 178
179def _write_listing(path, lines, with_export): 179def _write_listing(path, lines, with_export):
180 with open(path, "w", encoding="utf-8") as f: 180 with open(path, "w", encoding="utf-8", newline="\n") as f:
181 f.write("; shader_diff case code 0x0..0x1000\n") 181 f.write("; shader_diff case code 0x0..0x1000\n")
182 for line in lines: 182 for line in lines:
183 f.write("\t" + line + "\n") 183 f.write("\t" + line + "\n")
diff --git a/tools/shader_disasm.py b/tools/shader_disasm.py
index d22ca2bc2..38f49e7a6 100644
--- a/tools/shader_disasm.py
+++ b/tools/shader_disasm.py
@@ -119,7 +119,7 @@ def one(path, out, mcpu):
119 FAILED.append((path, reason)) 119 FAILED.append((path, reason))
120 return "failed" 120 return "failed"
121 name = os.path.splitext(os.path.basename(path))[0] 121 name = os.path.splitext(os.path.basename(path))[0]
122 with open(os.path.join(out, name + ".s"), "w", encoding="utf-8") as f: 122 with open(os.path.join(out, name + ".s"), "w", encoding="utf-8", newline="\n") as f:
123 f.write(f"; {name} code 0x{start:x}..0x{end:x} ({how}), {mcpu}, {bad} invalid words\n") 123 f.write(f"; {name} code 0x{start:x}..0x{end:x} ({how}), {mcpu}, {bad} invalid words\n")
124 f.write(asm) 124 f.write(asm)
125 if err.strip(): 125 if err.strip():
diff --git a/tools/shader_profile.py b/tools/shader_profile.py
index 47a975fe4..b14d0d346 100644
--- a/tools/shader_profile.py
+++ b/tools/shader_profile.py
@@ -363,7 +363,7 @@ def main():
363 if a.per_shader: 363 if a.per_shader:
364 out["per_shader"] = sorted(shaders, key=lambda e: e["name"]) 364 out["per_shader"] = sorted(shaders, key=lambda e: e["name"])
365 try: 365 try:
366 with open(path, "w", encoding="utf-8") as f: 366 with open(path, "w", encoding="utf-8", newline="\n") as f:
367 json.dump(out, f, indent=1, allow_nan=False) 367 json.dump(out, f, indent=1, allow_nan=False)
368 except OSError as e: 368 except OSError as e:
369 print(f"ERROR: cannot write {path}: {e.strerror or e}", file=sys.stderr) 369 print(f"ERROR: cannot write {path}: {e.strerror or e}", file=sys.stderr)
diff --git a/tools/skin_streams.py b/tools/skin_streams.py
index b453aadd9..db5adcfcc 100644
--- a/tools/skin_streams.py
+++ b/tools/skin_streams.py
@@ -486,7 +486,7 @@ def main(argv=None):
486 parent = os.path.dirname(os.path.abspath(a.json)) 486 parent = os.path.dirname(os.path.abspath(a.json))
487 if parent: 487 if parent:
488 os.makedirs(parent, exist_ok=True) 488 os.makedirs(parent, exist_ok=True)
489 with open(a.json, "w", encoding="utf-8") as fh: 489 with open(a.json, "w", encoding="utf-8", newline="\n") as fh:
490 json.dump(report, fh, indent=1) 490 json.dump(report, fh, indent=1)
491 except OSError as exc: 491 except OSError as exc:
492 print(f"error: cannot write {a.json}: {exc.strerror or exc}", file=sys.stderr) 492 print(f"error: cannot write {a.json}: {exc.strerror or exc}", file=sys.stderr)
diff --git a/tools/spirv_gs_to_compute.py b/tools/spirv_gs_to_compute.py
index afb9edba6..e480fd65d 100644
--- a/tools/spirv_gs_to_compute.py
+++ b/tools/spirv_gs_to_compute.py
@@ -325,7 +325,7 @@ def main(argv):
325 target = f"spv{ver.group(1)}.{ver.group(2)}" if ver else "vulkan1.2" 325 target = f"spv{ver.group(1)}.{ver.group(2)}" if ver else "vulkan1.2"
326 subprocess.run([asm, "--target-env", target, "-", "-o", args[1]], input=new, check=True, text=True) 326 subprocess.run([asm, "--target-env", target, "-", "-o", args[1]], input=new, check=True, text=True)
327 if lay_path: 327 if lay_path:
328 with open(lay_path, "w") as f: 328 with open(lay_path, "w", newline="\n") as f:
329 json.dump(lay, f, indent=1) 329 json.dump(lay, f, indent=1)
330 print(json.dumps(lay)) 330 print(json.dumps(lay))
331 return 0 331 return 0
diff --git a/tools/spirv_metal_set0.py b/tools/spirv_metal_set0.py
index cbd2792f5..9282a60e6 100644
--- a/tools/spirv_metal_set0.py
+++ b/tools/spirv_metal_set0.py
@@ -28,7 +28,8 @@ BINDLESS_H = os.path.join(ROOT, "runtime", "src", "vulkan_bindless.h")
28 28
29def capacities(path=BINDLESS_H): 29def capacities(path=BINDLESS_H):
30 """Descriptor counts by binding number, from the `bindings` table of vulkan_bindless.h.""" 30 """Descriptor counts by binding number, from the `bindings` table of vulkan_bindless.h."""
31 src = open(path, encoding="utf-8").read() 31 with open(path, encoding="utf-8") as f:
32 src = f.read()
32 m = re.search(r"std::array<Binding,\s*(\d+)>\s*bindings\s*=\s*\{\{(.*?)\}\};", src, re.S) 33 m = re.search(r"std::array<Binding,\s*(\d+)>\s*bindings\s*=\s*\{\{(.*?)\}\};", src, re.S)
33 if not m: 34 if not m:
34 raise SystemExit(f"{path}: no `bindings` table") 35 raise SystemExit(f"{path}: no `bindings` table")
@@ -47,6 +48,17 @@ def metal_ids(counts):
47 return ids 48 return ids
48 49
49 50
51def _fresh_id(base, used):
52 """Return `base` if unused, otherwise `base_1`, `base_2`, ... and record it in `used`."""
53 cand = base
54 i = 1
55 while cand in used:
56 cand = f"{base}_{i}"
57 i += 1
58 used.add(cand)
59 return cand
60
61
50def rewrite(text, counts): 62def rewrite(text, counts):
51 """Rewrite the disassembly (spirv-dis --raw-id is not needed; names are kept) of one module.""" 63 """Rewrite the disassembly (spirv-dis --raw-id is not needed; names are kept) of one module."""
52 ids = metal_ids(counts) 64 ids = metal_ids(counts)
@@ -65,28 +77,52 @@ def rewrite(text, counts):
65 raise SystemExit(f"{v}: binding {b} isn't in vulkan_bindless.h") 77 raise SystemExit(f"{v}: binding {b} isn't in vulkan_bindless.h")
66 78
67 defs = {} # result id -> instruction text 79 defs = {} # result id -> instruction text
68 for ln in lines: 80 ptr_pos = {} # OpTypePointer result id -> line index, so shared capacities emit at the earliest pointer
81 for idx, ln in enumerate(lines):
69 m = re.match(r"\s*(%\S+) = (.*)$", ln) 82 m = re.match(r"\s*(%\S+) = (.*)$", ln)
70 if m: 83 if m:
71 defs[m.group(1)] = m.group(2) 84 defs[m.group(1)] = m.group(2)
85 if re.match(r"OpTypePointer\b", m.group(2)):
86 ptr_pos[m.group(1)] = idx
72 uint = next((r for r, d in defs.items() if d == "OpTypeInt 32 0"), None) 87 uint = next((r for r, d in defs.items() if d == "OpTypeInt 32 0"), None)
73 88
74 new_types = [] # inserted right after the variable's pointer type is declared 89 candidates = []
75 retype = {} # variable -> new pointer type 90 for order, (v, b) in enumerate(set0.items()):
76 for v, b in sorted(set0.items(), key=lambda kv: kv[1]):
77 var = re.match(r"OpVariable (%\S+) UniformConstant$", defs.get(v, "")) 91 var = re.match(r"OpVariable (%\S+) UniformConstant$", defs.get(v, ""))
78 if not var: 92 if not var:
79 continue # the hash table (a storage buffer) and other non-array resources keep their type 93 continue # the hash table (a storage buffer) and other non-array resources keep their type
80 ptr = re.match(r"OpTypePointer UniformConstant (%\S+)$", defs[var.group(1)]) 94 old_ptr = var.group(1)
95 ptr = re.match(r"OpTypePointer UniformConstant (%\S+)$", defs.get(old_ptr, ""))
81 rt = re.match(r"OpTypeRuntimeArray (%\S+)$", defs.get(ptr.group(1), "")) if ptr else None 96 rt = re.match(r"OpTypeRuntimeArray (%\S+)$", defs.get(ptr.group(1), "")) if ptr else None
82 if not rt: 97 if not rt:
83 continue 98 continue
84 if uint is None: 99 if uint is None:
85 raise SystemExit("module has no 32-bit uint type for the array lengths") 100 raise SystemExit("module has no 32-bit uint type for the array lengths")
86 cap, arr, nptr = f"%msl_cap_b{b}", f"%msl_arr_b{b}", f"%msl_ptr_b{b}" 101 candidates.append((b, ptr_pos.get(old_ptr, len(lines)), order, v, old_ptr, rt.group(1)))
87 new_types.append((var.group(1), [f"{cap} = OpConstant {uint} {counts[b]}", 102
88 f"{arr} = OpTypeArray {rt.group(1)} {cap}", 103 used_ids = set(defs) | set(sets) | set(binds)
89 f"{nptr} = OpTypePointer UniformConstant {arr}"])) 104 cap_by_bind = {} # binding -> OpConstant id (emitted once per binding)
105 ptr_by_key = {} # (binding, elem_type) -> new OpTypePointer id
106 new_types = [] # inserted right after the variable's pointer type is declared
107 retype = {} # variable -> new pointer type
108 for b, _, _, v, old_ptr, elem in sorted(candidates):
109 if (b, elem) in ptr_by_key:
110 retype[v] = ptr_by_key[(b, elem)]
111 continue
112 decl = []
113 cap = cap_by_bind.get(b)
114 if cap is None:
115 cap = _fresh_id(f"%msl_cap_b{b}", used_ids)
116 cap_by_bind[b] = cap
117 decl.append(f"{cap} = OpConstant {uint} {counts[b]}")
118 arr = _fresh_id(f"%msl_arr_b{b}", used_ids)
119 nptr = _fresh_id(f"%msl_ptr_b{b}", used_ids)
120 decl.extend([
121 f"{arr} = OpTypeArray {elem} {cap}",
122 f"{nptr} = OpTypePointer UniformConstant {arr}",
123 ])
124 new_types.append((old_ptr, decl))
125 ptr_by_key[(b, elem)] = nptr
90 retype[v] = nptr 126 retype[v] = nptr
91 127
92 out = [] 128 out = []
diff --git a/tools/story_index.py b/tools/story_index.py
index 7a7c7a837..06d1e742a 100644
--- a/tools/story_index.py
+++ b/tools/story_index.py
@@ -299,7 +299,7 @@ def write_output(path, rows, summary):
299 with tempfile.TemporaryDirectory(dir=parent) as staging: 299 with tempfile.TemporaryDirectory(dir=parent) as staging:
300 staged = os.path.join(staging, "story_index" + ext) 300 staged = os.path.join(staging, "story_index" + ext)
301 if ext == ".json": 301 if ext == ".json":
302 with open(staged, "w", encoding="utf-8") as f: 302 with open(staged, "w", encoding="utf-8", newline="\n") as f:
303 json.dump({"summary": summary, "files": rows}, f, indent=1) 303 json.dump({"summary": summary, "files": rows}, f, indent=1)
304 else: 304 else:
305 with open(staged, "w", encoding="utf-8", newline="") as f: 305 with open(staged, "w", encoding="utf-8", newline="") as f:
diff --git a/tools/tex_export.py b/tools/tex_export.py
index f7de7dd28..59d7d4c28 100644
--- a/tools/tex_export.py
+++ b/tools/tex_export.py
@@ -225,7 +225,7 @@ def main():
225 pngs[t["export"]["png"]] += 1 225 pngs[t["export"]["png"]] += 1
226 if i % 2000 == 0: 226 if i % 2000 == 0:
227 print(f"[{i}/{len(texs)}] {dict(res)}", flush=True) 227 print(f"[{i}/{len(texs)}] {dict(res)}", flush=True)
228 with open(os.path.join(a.out, "export_log.json"), "w", encoding="utf-8") as f: 228 with open(os.path.join(a.out, "export_log.json"), "w", encoding="utf-8", newline="\n") as f:
229 json.dump(texs, f) 229 json.dump(texs, f)
230 print(f"{len(texs)} textures: {dict(res)} -> {a.out}") 230 print(f"{len(texs)} textures: {dict(res)} -> {a.out}")
231 if a.png: 231 if a.png:
diff --git a/tools/tex_headers.py b/tools/tex_headers.py
index f41cc47bc..389b83cf2 100644
--- a/tools/tex_headers.py
+++ b/tools/tex_headers.py
@@ -751,7 +751,7 @@ def main():
751 if parent: # the scan is already done; a missing folder used to lose it in a FileNotFoundError 751 if parent: # the scan is already done; a missing folder used to lose it in a FileNotFoundError
752 os.makedirs(parent, exist_ok=True) 752 os.makedirs(parent, exist_ok=True)
753 try: 753 try:
754 with open(path, "w", encoding="utf-8") as f: 754 with open(path, "w", encoding="utf-8", newline="\n") as f:
755 json.dump(allt, f) 755 json.dump(allt, f)
756 except OSError as e: 756 except OSError as e:
757 print(f"ERROR: cannot write {path}: {e.strerror or e}", file=sys.stderr) 757 print(f"ERROR: cannot write {path}: {e.strerror or e}", file=sys.stderr)
diff --git a/tools/text_tables.py b/tools/text_tables.py
index 8db40ae5f..60c4e9dce 100644
--- a/tools/text_tables.py
+++ b/tools/text_tables.py
@@ -40,10 +40,12 @@ import os
40import re 40import re
41import struct 41import struct
42import sys 42import sys
43import tempfile
43 44
44ROOT = os.path.dirname(os.path.abspath(__file__)) 45ROOT = os.path.dirname(os.path.abspath(__file__))
45if ROOT not in sys.path: 46if ROOT not in sys.path:
46 sys.path.insert(0, ROOT) 47 sys.path.insert(0, ROOT)
48from file_mode import published_mode # noqa: E402
47from hashdict import joaat # noqa: E402 49from hashdict import joaat # noqa: E402
48 50
49RESOURCE_MAGIC = b"0DRP" 51RESOURCE_MAGIC = b"0DRP"
@@ -288,6 +290,12 @@ def main(argv=None) -> int:
288 ap.add_argument("--strings", help="CSV: every string (source, offset, lang, hash, label, text)") 290 ap.add_argument("--strings", help="CSV: every string (source, offset, lang, hash, label, text)")
289 a = ap.parse_args(argv) 291 a = ap.parse_args(argv)
290 outs = [p for p in (a.dialogue, a.tables, a.strings) if p] 292 outs = [p for p in (a.dialogue, a.tables, a.strings) if p]
293 seen = set()
294 for p in outs:
295 key = os.path.normcase(os.path.realpath(p))
296 if key in seen:
297 ap.error("outputs must be distinct files")
298 seen.add(key)
291 for path in a.sources + a.labels: 299 for path in a.sources + a.labels:
292 if not os.path.exists(path): 300 if not os.path.exists(path):
293 print(f"text_tables: error: {path}: no such file or directory", file=sys.stderr) 301 print(f"text_tables: error: {path}: no such file or directory", file=sys.stderr)
@@ -308,24 +316,73 @@ def main(argv=None) -> int:
308 316
309 lines = sum(len(v) for v in scan.pairs.values()) 317 lines = sum(len(v) for v in scan.pairs.values())
310 langs = scan.languages() 318 langs = scan.languages()
319 jobs = []
320 if a.dialogue:
321 fields = ["wave", "key", "label", "speaker"] + [f"text_{x}" for x in langs]
322 jobs.append((a.dialogue, fields, scan.dialogue_rows()))
323 if a.tables:
324 jobs.append((a.tables, ["source", "offset", "lang", "group", "strings", "resolved"],
325 ({"source": s, "offset": o, "lang": lang,
326 "group": table_group(names[h] for h in t if h in names),
327 "strings": len(t), "resolved": sum(h in names for h in t)}
328 for s, o, lang, t in scan.tables)))
329 if a.strings:
330 jobs.append((a.strings, ["source", "offset", "lang", "hash", "label", "text"],
331 ({"source": s, "offset": o, "lang": lang, "hash": f"{h:08x}", "label": names.get(h, ""),
332 "text": _clean(text)}
333 for s, o, lang, t in scan.tables for h, text in t.items())))
334 # Stage every report next to its destination, then swap them all in. A write that fails part-way must
335 # leave the previous reports intact instead of truncating the ones that came before it.
336 staged = []
337 originals = {}
311 try: 338 try:
312 if a.dialogue: 339 for dest, fields, rows in jobs:
313 fields = ["wave", "key", "label", "speaker"] + [f"text_{x}" for x in langs] 340 parent = os.path.dirname(os.path.abspath(dest))
314 _write_csv(a.dialogue, fields, scan.dialogue_rows()) 341 fd, tmp = tempfile.mkstemp(dir=parent, prefix=".text_tables-", suffix=".csv")
315 if a.tables: 342 os.close(fd)
316 _write_csv(a.tables, ["source", "offset", "lang", "group", "strings", "resolved"], 343 staged.append((tmp, dest))
317 ({"source": s, "offset": o, "lang": lang, 344 _write_csv(tmp, fields, rows)
318 "group": table_group(names[h] for h in t if h in names), 345 for _tmp, dest in staged:
319 "strings": len(t), "resolved": sum(h in names for h in t)} 346 if os.path.isdir(dest):
320 for s, o, lang, t in scan.tables)) 347 raise OSError(f"{dest} is a directory")
321 if a.strings: 348 for tmp, dest in staged:
322 _write_csv(a.strings, ["source", "offset", "lang", "hash", "label", "text"], 349 os.chmod(tmp, published_mode(dest))
323 ({"source": s, "offset": o, "lang": lang, "hash": f"{h:08x}", "label": names.get(h, ""), 350 # Move every old report aside before putting any new one in place. On Windows a report held
324 "text": _clean(text)} 351 # open by a reader cannot be renamed; failing here leaves all the originals untouched.
325 for s, o, lang, t in scan.tables for h, text in t.items())) 352 for _tmp, dest in staged:
353 if os.path.lexists(dest):
354 fd, backup = tempfile.mkstemp(dir=os.path.dirname(os.path.abspath(dest)),
355 prefix=".text_tables-old-", suffix=".csv")
356 os.close(fd)
357 os.remove(backup)
358 os.replace(dest, backup)
359 originals[dest] = backup
360 else:
361 originals[dest] = None
362 for tmp, dest in staged:
363 os.replace(tmp, dest)
326 except OSError as error: 364 except OSError as error:
365 for dest, backup in originals.items():
366 try:
367 if os.path.lexists(dest):
368 os.remove(dest)
369 if backup is not None:
370 os.replace(backup, dest)
371 except OSError:
372 pass
373 for tmp, _ in staged:
374 try:
375 os.remove(tmp)
376 except OSError:
377 pass
327 print(f"text_tables: error: cannot write: {error}", file=sys.stderr) 378 print(f"text_tables: error: cannot write: {error}", file=sys.stderr)
328 return 2 379 return 2
380 for backup in originals.values():
381 if backup is not None:
382 try:
383 os.remove(backup)
384 except OSError:
385 pass
329 with_text = collections.Counter() 386 with_text = collections.Counter()
330 for row in scan.dialogue_rows(): 387 for row in scan.dialogue_rows():
331 for lang in langs: 388 for lang in langs:
diff --git a/tools/ttpf_assets.py b/tools/ttpf_assets.py
index da8470a85..2939c66c3 100644
--- a/tools/ttpf_assets.py
+++ b/tools/ttpf_assets.py
@@ -4,9 +4,13 @@ import hashlib
4import json 4import json
5import os 5import os
6from pathlib import Path 6from pathlib import Path
7import sys
7import tempfile 8import tempfile
8import zlib 9import zlib
9 10
11# `python -I` implies `-P`, so the script's directory is not on sys.path; the sibling modules are next to it.
12sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
13
10import bcpack 14import bcpack
11from file_mode import published_mode 15from file_mode import published_mode
12import ttpf_mips as ttpf 16import ttpf_mips as ttpf
diff --git a/tools/ttpf_mips.py b/tools/ttpf_mips.py
index 58e58e9be..698f4c558 100644
--- a/tools/ttpf_mips.py
+++ b/tools/ttpf_mips.py
@@ -1497,7 +1497,7 @@ def scan_pools(paths, as_json=None, include_tuples=False):
1497 if as_json: 1497 if as_json:
1498 try: 1498 try:
1499 os.makedirs(os.path.dirname(os.path.abspath(as_json)), exist_ok=True) 1499 os.makedirs(os.path.dirname(os.path.abspath(as_json)), exist_ok=True)
1500 with open(as_json, "w", encoding="utf-8") as f: 1500 with open(as_json, "w", encoding="utf-8", newline="\n") as f:
1501 json.dump(report, f, indent=1) 1501 json.dump(report, f, indent=1)
1502 except OSError as exc: 1502 except OSError as exc:
1503 raise ValueError(f"cannot write {as_json}: {exc.strerror or exc}") from None 1503 raise ValueError(f"cannot write {as_json}: {exc.strerror or exc}") from None
diff --git a/tools/turing_atlas.py b/tools/turing_atlas.py
index c058b55c2..56fcb2c76 100644
--- a/tools/turing_atlas.py
+++ b/tools/turing_atlas.py
@@ -188,7 +188,7 @@ def validate_cases():
188 for name, asm in CASES.items(): 188 for name, asm in CASES.items():
189 src = os.path.join(d, name + ".spvasm") 189 src = os.path.join(d, name + ".spvasm")
190 spv = os.path.join(d, name + ".spv") 190 spv = os.path.join(d, name + ".spv")
191 with open(src, "w", encoding="utf-8") as f: 191 with open(src, "w", encoding="utf-8", newline="\n") as f:
192 f.write(asm) 192 f.write(asm)
193 ra = run(["spirv-as", src, "-o", spv, "--target-env", "vulkan1.4"]) 193 ra = run(["spirv-as", src, "-o", spv, "--target-env", "vulkan1.4"])
194 if ra is None or ra.returncode != 0: 194 if ra is None or ra.returncode != 0:
@@ -230,7 +230,7 @@ def main():
230 folder = os.path.dirname(a.out) # --out into a folder that does not exist yet, as awc_manifest.py does 230 folder = os.path.dirname(a.out) # --out into a folder that does not exist yet, as awc_manifest.py does
231 if folder: 231 if folder:
232 os.makedirs(folder, exist_ok=True) 232 os.makedirs(folder, exist_ok=True)
233 with open(a.out, "w", encoding="utf-8") as f: 233 with open(a.out, "w", encoding="utf-8", newline="\n") as f:
234 f.write(text + "\n") 234 f.write(text + "\n")
235 print(f"atlas -> {a.out}") 235 print(f"atlas -> {a.out}")
236 else: 236 else:
diff --git a/tools/user_sgpr_census.py b/tools/user_sgpr_census.py
index 35fa44ddf..bdb49ff12 100644
--- a/tools/user_sgpr_census.py
+++ b/tools/user_sgpr_census.py
@@ -24,6 +24,7 @@ Usage:
24""" 24"""
25import argparse 25import argparse
26import json 26import json
27import os
27import sys 28import sys
28from collections import Counter, defaultdict 29from collections import Counter, defaultdict
29 30
@@ -83,19 +84,36 @@ def census(index, base=None):
83 return out 84 return out
84 85
85 86
87def stage_sgpr(text):
88 stage, _, value = text.partition("=")
89 message = f"expected STAGE=SGPR with a nonnegative SGPR: {text!r}"
90 try:
91 sgpr = int(value)
92 except ValueError:
93 raise argparse.ArgumentTypeError(message) from None
94 if not stage or sgpr < 0:
95 raise argparse.ArgumentTypeError(message)
96 return stage, sgpr
97
98
86def main(argv=None): 99def main(argv=None):
87 ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) 100 ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
88 ap.add_argument("index", help="spirv/index.json written by tools/rdna2spirv.py") 101 ap.add_argument("index", help="spirv/index.json written by tools/rdna2spirv.py")
89 ap.add_argument("--json", help="also write the summary here") 102 ap.add_argument("--json", help="also write the summary here")
90 ap.add_argument("--expect", nargs="*", default=[], metavar="STAGE=SGPR", 103 ap.add_argument("--expect", nargs="*", type=stage_sgpr, default=[], metavar="STAGE=SGPR",
91 help="fail if the most common lowest-pointer SGPR of STAGE is not SGPR") 104 help="fail if the most common lowest-pointer SGPR of STAGE is not SGPR")
92 ap.add_argument("--base", nargs="*", default=[], metavar="STAGE=SGPR", 105 ap.add_argument("--base", nargs="*", type=stage_sgpr, default=[], metavar="STAGE=SGPR",
93 help="report the reads below this first root-argument SGPR per stage") 106 help="report the reads below this first root-argument SGPR per stage")
94 a = ap.parse_args(argv) 107 a = ap.parse_args(argv)
108 if a.json:
109 try:
110 if os.path.samefile(a.index, a.json):
111 ap.error("--json must not overwrite the input index")
112 except FileNotFoundError:
113 pass
95 with open(a.index, encoding="utf-8") as f: 114 with open(a.index, encoding="utf-8") as f:
96 index = json.load(f) 115 index = json.load(f)
97 base = {k: int(v) for k, _, v in (b.partition("=") for b in a.base)} 116 summary = census(index, dict(a.base))
98 summary = census(index, base)
99 for stage, s in summary.items(): 117 for stage, s in summary.items():
100 top = s["most_common_lowest_pointer_sgpr"] 118 top = s["most_common_lowest_pointer_sgpr"]
101 print(f"{stage}: {s['shaders']} shaders; lowest pointer SGPR " 119 print(f"{stage}: {s['shaders']} shaders; lowest pointer SGPR "
@@ -103,13 +121,12 @@ def main(argv=None):
103 f"pointer gaps {s['pointer_gap']}; after a ptr32 {s['after_ptr32']}" 121 f"pointer gaps {s['pointer_gap']}; after a ptr32 {s['after_ptr32']}"
104 + (f"; below base {s['below_base']}" if "below_base" in s else "")) 122 + (f"; below base {s['below_base']}" if "below_base" in s else ""))
105 if a.json: 123 if a.json:
106 with open(a.json, "w", encoding="utf-8") as f: 124 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
107 json.dump(summary, f, indent=1, sort_keys=True) 125 json.dump(summary, f, indent=1, sort_keys=True)
108 bad = [] 126 bad = []
109 for item in a.expect: 127 for stage, sgpr in a.expect:
110 stage, _, sgpr = item.partition("=")
111 got = summary.get(stage, {}).get("most_common_lowest_pointer_sgpr") 128 got = summary.get(stage, {}).get("most_common_lowest_pointer_sgpr")
112 if got != int(sgpr): 129 if got != sgpr:
113 bad.append(f"{stage}: expected s{sgpr}, got {'s%d' % got if got is not None else 'none'}") 130 bad.append(f"{stage}: expected s{sgpr}, got {'s%d' % got if got is not None else 'none'}")
114 for b in bad: 131 for b in bad:
115 print("MISMATCH", b, file=sys.stderr) 132 print("MISMATCH", b, file=sys.stderr)
diff --git a/tools/valu_fuzz.py b/tools/valu_fuzz.py
index 2b9beeb97..ed6c24e0d 100644
--- a/tools/valu_fuzz.py
+++ b/tools/valu_fuzz.py
@@ -845,7 +845,7 @@ def translate(progs, work, emulate):
845 for p in progs: 845 for p in progs:
846 text = p.asm() 846 text = p.asm()
847 asm_path = work / (p.name + ".asm") 847 asm_path = work / (p.name + ".asm")
848 asm_path.write_text(text, encoding="utf-8") 848 asm_path.write_text(text, encoding="utf-8", newline="\n")
849 cmd = mc + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-show-encoding"] 849 cmd = mc + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-show-encoding"]
850 if p.wave == 64: 850 if p.wave == 64:
851 cmd.append("-mattr=+wavefrontsize64,-wavefrontsize32") 851 cmd.append("-mattr=+wavefrontsize64,-wavefrontsize32")
@@ -853,7 +853,7 @@ def translate(progs, work, emulate):
853 if r.returncode or "error:" in r.stderr: 853 if r.returncode or "error:" in r.stderr:
854 raise RuntimeError(f"{p.name} did not assemble:\n{r.stderr}") 854 raise RuntimeError(f"{p.name} did not assemble:\n{r.stderr}")
855 code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith(".")) 855 code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith("."))
856 (disasm / (p.name + ".s")).write_text(f"; {p.name}\n{code}", encoding="utf-8") 856 (disasm / (p.name + ".s")).write_text(f"; {p.name}\n{code}", encoding="utf-8", newline="\n")
857 (fssm / (p.name + ".fssm")).write_bytes(compute_header(asm_path)) 857 (fssm / (p.name + ".fssm")).write_bytes(compute_header(asm_path))
858 cmd = [sys.executable, "-I", os.path.join(HERE, "rdna2spirv.py"), str(disasm), "--out", str(spirv)] 858 cmd = [sys.executable, "-I", os.path.join(HERE, "rdna2spirv.py"), str(disasm), "--out", str(spirv)]
859 if emulate: 859 if emulate:
diff --git a/tools/vertex_types.py b/tools/vertex_types.py
index 6702b5fae..871d886e5 100644
--- a/tools/vertex_types.py
+++ b/tools/vertex_types.py
@@ -525,7 +525,7 @@ def main(argv=None):
525 if args.json: 525 if args.json:
526 try: 526 try:
527 os.makedirs(os.path.dirname(os.path.abspath(args.json)), exist_ok=True) 527 os.makedirs(os.path.dirname(os.path.abspath(args.json)), exist_ok=True)
528 with open(args.json, "w", encoding="utf-8") as fh: 528 with open(args.json, "w", encoding="utf-8", newline="\n") as fh:
529 json.dump(out, fh, indent=1) 529 json.dump(out, fh, indent=1)
530 except OSError as exc: 530 except OSError as exc:
531 print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr) 531 print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr)
diff --git a/tools/vk_subgroup_info.py b/tools/vk_subgroup_info.py
index 3630c2baf..97e3880cf 100644
--- a/tools/vk_subgroup_info.py
+++ b/tools/vk_subgroup_info.py
@@ -6,12 +6,13 @@ make_game.py uses it to choose between native wave64 translation and --wave64-em
6Vulkan implementation through ctypes (standard library only), so it works before the runtime stage has built anything. 6Vulkan implementation through ctypes (standard library only), so it works before the runtime stage has built anything.
7On macOS it opens MoltenVK directly, using the same LEONIDA_VULKAN_LOADER override as the C++ test tools. 7On macOS it opens MoltenVK directly, using the same LEONIDA_VULKAN_LOADER override as the C++ test tools.
8 8
9Device choice follows the runtime (runtime/shims/d3d12_vulkan_device.cpp): Vulkan 1.3 devices with dynamicRendering, 9Device choice follows the runtime (runtime/shims/d3d12_vulkan_device.cpp, runtime/src/vulkan_device_filter.h):
10synchronization2, timelineSemaphore and separateDepthStencilLayouts and a graphics queue family; a discrete GPU wins 10LEONIDA_VK_DEVICE filters by deviceName substring case-insensitively (failing when nothing matches), then Vulkan 1.3
11(the last one), otherwise the first. The runtime also needs the rest of its device setup (surface, extensions); 11devices with dynamicRendering, synchronization2, timelineSemaphore and separateDepthStencilLayouts and a graphics queue
12that is not checked here. vk_pipeline_check picks by device type only, so on a PC where the two differ the pipelines 12family; a discrete GPU wins (the last one), otherwise the first. The runtime also needs the rest of its device setup
13stage can run on another GPU than the one asked here. VK_LOADER_DRIVERS_SELECT (e.g. '*amd*') narrows which 13(surface, extensions); that is not checked here. vk_pipeline_check picks by device type only, so on a PC where the two
14drivers the loader offers. 14differ the pipelines stage can run on another GPU than the one asked here. VK_LOADER_DRIVERS_SELECT (e.g. '*amd*')
15narrows which drivers the loader offers.
15 16
16native64 matches the current translated SPIR-V 1.5 modules, which do not allow varying subgroup sizes: either 64 can 17native64 matches the current translated SPIR-V 1.5 modules, which do not allow varying subgroup sizes: either 64 can
17be required for both compute and mesh, or the default subgroupSize is 64 and subgroup operations are supported in 18be required for both compute and mesh, or the default subgroupSize is 64 and subgroup operations are supported in
@@ -180,6 +181,8 @@ def query() -> dict:
180 devs = physical_devices(vk, inst) 181 devs = physical_devices(vk, inst)
181 if not devs: 182 if not devs:
182 raise RuntimeError("no Vulkan device") 183 raise RuntimeError("no Vulkan device")
184 device_filter = os.environ.get("LEONIDA_VK_DEVICE", "")
185 wanted = device_filter.lower()
183 chosen = None 186 chosen = None
184 for d in devs: 187 for d in devs:
185 d = ctypes.c_void_p(d) 188 d = ctypes.c_void_p(d)
@@ -193,8 +196,11 @@ def query() -> dict:
193 set_next(props, subgroup) 196 set_next(props, subgroup)
194 vk.vkGetPhysicalDeviceProperties2(d, props) 197 vk.vkGetPhysicalDeviceProperties2(d, props)
195 raw = bytes(props)[16:] 198 raw = bytes(props)[16:]
199 dev_name = raw[PROPS_DEVICE_NAME:PROPS_DEVICE_NAME + 256].split(b"\0")[0].decode("utf-8", "replace")
196 if int.from_bytes(raw[PROPS_API_VERSION:PROPS_API_VERSION + 4], "little") < VK_API_VERSION_1_3: 200 if int.from_bytes(raw[PROPS_API_VERSION:PROPS_API_VERSION + 4], "little") < VK_API_VERSION_1_3:
197 continue 201 continue
202 if wanted and wanted not in dev_name.lower():
203 continue
198 f13 = block(F13_SIZE, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES) 204 f13 = block(F13_SIZE, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES)
199 f12 = block(F12_SIZE, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES) 205 f12 = block(F12_SIZE, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES)
200 set_next(f12, f13) 206 set_next(f12, f13)
@@ -215,13 +221,18 @@ def query() -> dict:
215 dtype = int.from_bytes(raw[PROPS_DEVICE_TYPE:PROPS_DEVICE_TYPE + 4], "little") 221 dtype = int.from_bytes(raw[PROPS_DEVICE_TYPE:PROPS_DEVICE_TYPE + 4], "little")
216 # the runtime's rule: the first usable device, replaced by every later discrete GPU 222 # the runtime's rule: the first usable device, replaced by every later discrete GPU
217 if chosen is None or dtype == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: 223 if chosen is None or dtype == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU:
218 chosen = (raw[PROPS_DEVICE_NAME:PROPS_DEVICE_NAME + 256].split(b"\0")[0].decode("utf-8", "replace"), 224 chosen = (dev_name,
219 subgroup.subgroupSize, subgroup.supportedStages, sg.minSubgroupSize, sg.maxSubgroupSize, 225 subgroup.subgroupSize, subgroup.supportedStages, sg.minSubgroupSize, sg.maxSubgroupSize,
220 sg.requiredSubgroupSizeStages, bool(u32(f13, F13_SUBGROUP_SIZE_CONTROL)), 226 sg.requiredSubgroupSizeStages, bool(u32(f13, F13_SUBGROUP_SIZE_CONTROL)),
221 bool(u32(bary, 16)) and u32(drv, 16) != VK_DRIVER_ID_MOLTENVK, 227 bool(u32(bary, 16)) and u32(drv, 16) != VK_DRIVER_ID_MOLTENVK,
222 int.from_bytes(raw[PROPS_VENDOR_ID:PROPS_VENDOR_ID + 4], "little"), 228 int.from_bytes(raw[PROPS_VENDOR_ID:PROPS_VENDOR_ID + 4], "little"),
223 int.from_bytes(raw[PROPS_DEVICE_ID:PROPS_DEVICE_ID + 4], "little"), u32(drv, 16)) 229 int.from_bytes(raw[PROPS_DEVICE_ID:PROPS_DEVICE_ID + 4], "little"), u32(drv, 16))
224 if chosen is None: 230 if chosen is None:
231 if device_filter:
232 raise RuntimeError(
233 f"LEONIDA_VK_DEVICE={device_filter}: no Vulkan 1.3 GPU with the features and graphics queue "
234 "the runtime needs matches"
235 )
225 raise RuntimeError("no Vulkan 1.3 GPU with the features and graphics queue the runtime needs") 236 raise RuntimeError("no Vulkan 1.3 GPU with the features and graphics queue the runtime needs")
226 name, subgroup_size, supported_stages, lo, hi, required_stages, sgc, per_vertex, vendor, device, driver = chosen 237 name, subgroup_size, supported_stages, lo, hi, required_stages, sgc, per_vertex, vendor, device, driver = chosen
227 compute_required = bool(required_stages & VK_SHADER_STAGE_COMPUTE_BIT) 238 compute_required = bool(required_stages & VK_SHADER_STAGE_COMPUTE_BIT)
diff --git a/tools/wave64_graphics_scan.py b/tools/wave64_graphics_scan.py
index b9410a5e8..f830a2da7 100644
--- a/tools/wave64_graphics_scan.py
+++ b/tools/wave64_graphics_scan.py
@@ -96,10 +96,10 @@ def scan_directory(disasm):
96 "mask_word_source": {"exec_vcc": Counter(), "other": Counter()}} 96 "mask_word_source": {"exec_vcc": Counter(), "other": Counter()}}
97 for stage in GRAPHICS} 97 for stage in GRAPHICS}
98 other = {"shaders": 0, "wave64": 0} 98 other = {"shaders": 0, "wave64": 0}
99 for name in sorted(os.listdir(disasm)): 99 with os.scandir(disasm) as entries:
100 if not name.endswith(".s"): 100 paths = sorted(entry.path for entry in entries
101 continue 101 if entry.name.endswith(".s") and entry.is_file())
102 path = os.path.join(disasm, name) 102 for path in paths:
103 info = parse_file(path) 103 info = parse_file(path)
104 stage = rdna2spirv.stage_of(info["name"], path) 104 stage = rdna2spirv.stage_of(info["name"], path)
105 wave64 = wave64_rule(stage, info["insns"]) 105 wave64 = wave64_rule(stage, info["insns"])
@@ -158,7 +158,7 @@ def main(argv=None) -> int:
158 o = report["other_stages"] 158 o = report["other_stages"]
159 print("other stages: %d shaders, %d wave64 (not counted)" % (o["shaders"], o["wave64"])) 159 print("other stages: %d shaders, %d wave64 (not counted)" % (o["shaders"], o["wave64"]))
160 if args.out: 160 if args.out:
161 with open(args.out, "w", encoding="utf-8") as f: 161 with open(args.out, "w", encoding="utf-8", newline="\n") as f:
162 json.dump(report, f, indent=1) 162 json.dump(report, f, indent=1)
163 print("wrote %s" % args.out) 163 print("wrote %s" % args.out)
164 return 0 164 return 0
diff --git a/tools/world_census.py b/tools/world_census.py
index 86b63b4b5..0d1e04539 100644
--- a/tools/world_census.py
+++ b/tools/world_census.py
@@ -101,7 +101,7 @@ def _mapped_source(archive, expected_id):
101def _staged_json(path, doc, **options): 101def _staged_json(path, doc, **options):
102 with tempfile.TemporaryDirectory(dir=os.path.dirname(path)) as directory: 102 with tempfile.TemporaryDirectory(dir=os.path.dirname(path)) as directory:
103 tmp = os.path.join(directory, os.path.basename(path)) 103 tmp = os.path.join(directory, os.path.basename(path))
104 with open(tmp, "w", encoding="utf-8") as f: 104 with open(tmp, "w", encoding="utf-8", newline="\n") as f:
105 json.dump(doc, f, **options) 105 json.dump(doc, f, **options)
106 try: 106 try:
107 mode = os.lstat(path).st_mode 107 mode = os.lstat(path).st_mode
diff --git a/tools/world_index.py b/tools/world_index.py
index e0464beac..972c986a9 100644
--- a/tools/world_index.py
+++ b/tools/world_index.py
@@ -419,6 +419,15 @@ def _carve_successors(folder):
419 for off, stored in by_off.items() if (off + stored + 15) & ~15 in by_off} 419 for off, stored in by_off.items() if (off + stored + 15) & ~15 in by_off}
420 420
421 421
422def _read_carved(path, max_inflate):
423 """Read a carved file within the cap, or return None if it is too large."""
424 with open(path, "rb") as f:
425 if os.fstat(f.fileno()).st_size > max_inflate:
426 return None
427 data = f.read(max_inflate + 1) # detect growth after fstat
428 return data if len(data) <= max_inflate else None
429
430
422def scan_path(path, start=None, limit=None, max_inflate=CAP, collect=None, *, directory_files=None): 431def scan_path(path, start=None, limit=None, max_inflate=CAP, collect=None, *, directory_files=None):
423 """Scan an RPF9 archive, or every carved file in a directory.""" 432 """Scan an RPF9 archive, or every carved file in a directory."""
424 if directory_files is not None or os.path.isdir(path): 433 if directory_files is not None or os.path.isdir(path):
@@ -440,10 +449,9 @@ def scan_path(path, start=None, limit=None, max_inflate=CAP, collect=None, *, di
440 stats["files"] += 1 449 stats["files"] += 1
441 stats["scanned_bytes"] += sub["scanned_bytes"] 450 stats["scanned_bytes"] += sub["scanned_bytes"]
442 continue 451 continue
443 if os.path.getsize(p) > max_inflate: 452 b = _read_carved(p, max_inflate)
453 if b is None:
444 continue 454 continue
445 with open(p, "rb") as f:
446 b = f.read(max_inflate + 1)
447 stats["files"] += 1 455 stats["files"] += 1
448 stats["scanned_bytes"] += len(b) 456 stats["scanned_bytes"] += len(b)
449 # As in scan_rpf: a 0DRPz resource that needs a continuation takes the next stream, when the 457 # As in scan_rpf: a 0DRPz resource that needs a continuation takes the next stream, when the
@@ -480,8 +488,9 @@ def scan_path(path, start=None, limit=None, max_inflate=CAP, collect=None, *, di
480 magic = f.read(4) 488 magic = f.read(4)
481 if magic == b"9FPR": 489 if magic == b"9FPR":
482 return scan_rpf(path, start, limit, max_inflate, collect) 490 return scan_rpf(path, start, limit, max_inflate, collect)
483 with open(path, "rb") as f: 491 b = _read_carved(path, max_inflate)
484 b = f.read(max_inflate + 1) 492 if b is None:
493 return [], {"path": os.path.abspath(path), "files": 0, "scanned_bytes": 0}
485 row = parse_resource(b, collect) 494 row = parse_resource(b, collect)
486 return ([dict(row, offset=0, size=len(b), file=os.path.basename(path))] if row else [], 495 return ([dict(row, offset=0, size=len(b), file=os.path.basename(path))] if row else [],
487 {"path": os.path.abspath(path), "files": 1, "scanned_bytes": len(b)}) 496 {"path": os.path.abspath(path), "files": 1, "scanned_bytes": len(b)})
@@ -742,7 +751,7 @@ def _write_reports(a, rows, stats, agg):
742 summary["versions"] = sorted({r["version"] for r in rows}) 751 summary["versions"] = sorted({r["version"] for r in rows})
743 doc = {"summary": summary, "resources": rows} 752 doc = {"summary": summary, "resources": rows}
744 os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) 753 os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
745 with open(a.out, "w", encoding="utf-8") as f: 754 with open(a.out, "w", encoding="utf-8", newline="\n") as f:
746 json.dump(doc, f, indent=1, sort_keys=True) 755 json.dump(doc, f, indent=1, sort_keys=True)
747 if a.csv: 756 if a.csv:
748 cols = ["source", "offset", "size", "signature", "version", "kind", "structs", "enums", "blocks", 757 cols = ["source", "offset", "size", "signature", "version", "kind", "structs", "enums", "blocks",
@@ -763,7 +772,7 @@ def _write_reports(a, rows, stats, agg):
763 w.writerow(r) 772 w.writerow(r)
764 if agg is not None: 773 if agg is not None:
765 os.makedirs(os.path.dirname(os.path.abspath(a.archetypes_out)), exist_ok=True) 774 os.makedirs(os.path.dirname(os.path.abspath(a.archetypes_out)), exist_ok=True)
766 with open(a.archetypes_out, "w", encoding="utf-8") as f: 775 with open(a.archetypes_out, "w", encoding="utf-8", newline="\n") as f:
767 json.dump(agg.to_json(), f, indent=1, sort_keys=True) 776 json.dump(agg.to_json(), f, indent=1, sort_keys=True)
768 summary["archetype_file"] = agg.to_json()["summary"] 777 summary["archetype_file"] = agg.to_json()["summary"]
769 return summary 778 return summary
diff --git a/tools/world_lights_paths.py b/tools/world_lights_paths.py
index ee1c78c3d..65bce000b 100644
--- a/tools/world_lights_paths.py
+++ b/tools/world_lights_paths.py
@@ -708,6 +708,15 @@ def summarize(total, entities=None, lights_out=None):
708 return summary 708 return summary
709 709
710 710
711def same_report_path(first, second):
712 if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)):
713 return True
714 try:
715 return os.path.samefile(first, second)
716 except OSError:
717 return False
718
719
711def main(argv=None): 720def main(argv=None):
712 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) 721 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
713 ap.add_argument("archive") 722 ap.add_argument("archive")
@@ -727,6 +736,8 @@ def main(argv=None):
727 if a.entities and not os.path.isfile(a.entities): 736 if a.entities and not os.path.isfile(a.entities):
728 print(f"ERROR: {a.entities}: no such file", file=sys.stderr) 737 print(f"ERROR: {a.entities}: no such file", file=sys.stderr)
729 return 2 738 return 2
739 if a.out and a.lights_out and same_report_path(a.out, a.lights_out):
740 ap.error("--out and --lights-out must use different paths")
730 total = scan(a.archive, a.jobs, a.start, a.limit, bool(a.lights_out)) 741 total = scan(a.archive, a.jobs, a.start, a.limit, bool(a.lights_out))
731 summary = summarize(total, a.entities, a.lights_out) 742 summary = summarize(total, a.entities, a.lights_out)
732 text = json.dumps(summary, indent=1, sort_keys=True) 743 text = json.dumps(summary, indent=1, sort_keys=True)
diff --git a/tools/world_names.py b/tools/world_names.py
index 4ffe3f01a..06152aac5 100644
--- a/tools/world_names.py
+++ b/tools/world_names.py
@@ -606,7 +606,7 @@ def _write_json(path: str, data: dict) -> None:
606 os.makedirs(directory, exist_ok=True) 606 os.makedirs(directory, exist_ok=True)
607 with tempfile.TemporaryDirectory(dir=directory, prefix=".world-names-") as staging: 607 with tempfile.TemporaryDirectory(dir=directory, prefix=".world-names-") as staging:
608 tmp = os.path.join(staging, "report.json") 608 tmp = os.path.join(staging, "report.json")
609 with open(tmp, "w", encoding="utf-8") as handle: 609 with open(tmp, "w", encoding="utf-8", newline="\n") as handle:
610 json.dump(data, handle, indent=1, sort_keys=True) 610 json.dump(data, handle, indent=1, sort_keys=True)
611 handle.write("\n") 611 handle.write("\n")
612 os.replace(tmp, path) 612 os.replace(tmp, path)
diff --git a/tools/xdxr_bvh.py b/tools/xdxr_bvh.py
index edcc79a8b..e8fcefde3 100644
--- a/tools/xdxr_bvh.py
+++ b/tools/xdxr_bvh.py
@@ -740,11 +740,15 @@ def check_build(directory, rays=300, seed=1):
740 return [f"no cases in {directory}"] 740 return [f"no cases in {directory}"]
741 problems = [] 741 problems = []
742 cases = {n: _load_case(directory, n) for n in names} 742 cases = {n: _load_case(directory, n) for n in names}
743 mem = Memory()
744 for n, (desc, data) in cases.items():
745 mem.place(desc["address"], data)
746 rng = random.Random(seed) 743 rng = random.Random(seed)
747 for n, (desc, data) in cases.items(): 744 for n, (desc, data) in cases.items():
745 # An in-place update leaves two dumps at one address (before and after): the case being checked comes first,
746 # so its own bytes answer reads there.
747 mem = Memory()
748 mem.place(desc["address"], data)
749 for other, (odesc, odata) in cases.items():
750 if other != n:
751 mem.place(odesc["address"], odata)
748 errs = validate(data, expect_bottom=desc["kind"] == "blas") 752 errs = validate(data, expect_bottom=desc["kind"] == "blas")
749 problems += [f"{n}: {e}" for e in errs] 753 problems += [f"{n}: {e}" for e in errs]
750 if desc["kind"] == "blas": 754 if desc["kind"] == "blas":