diff options
| author | Vonsek <45567075+Vonsek@users.noreply.github.com> | 2026-11-22 09:43:07 +0100 |
|---|---|---|
| committer | Vonsek <45567075+Vonsek@users.noreply.github.com> | 2026-11-22 09:43:07 +0100 |
| commit | 8ccf429a56bf62ae231d0aa06e043c17bb8a83e2 (patch) | |
| tree | 8a0d75f90344444a356ac7021acb451852621eb5 /scripts | |
| parent | e444c83335ea6f3cabf68539c2f6d63d39d0a868 (diff) | |
| parent | c603b8f8ff9090fbf5bcc0297990f40cd1cb6638 (diff) | |
Merge main into the S#/T# mip test (#319)
Conflicts in docs/d3d12_vulkan.md, runtime/CMakeLists.txt, check.py,
run_gpu_tests.py and test_shader_checks.py: main's versions with
vk_sampler_test, ps_ssharp and its checks added back (ps_ssharp is drawn
with vs_ids through DRAWN_WITH now).
AI-assisted (Claude Code).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'scripts')
| -rw-r--r-- | scripts/audit_shader4_regs.py | 368 | ||||
| -rw-r--r-- | scripts/bench_wave64.py | 112 | ||||
| -rw-r--r-- | scripts/build_llvm_mc.ps1 | 18 | ||||
| -rw-r--r-- | scripts/build_runtime.ps1 | 20 | ||||
| -rw-r--r-- | scripts/carve_all.ps1 | 16 | ||||
| -rw-r--r-- | scripts/first_look.ps1 | 2 | ||||
| -rw-r--r-- | scripts/meta_to_xml.ps1 | 10 | ||||
| -rw-r--r-- | scripts/run_gpu_tests.py | 501 | ||||
| -rw-r--r-- | scripts/run_wine_tests.py | 166 | ||||
| -rw-r--r-- | scripts/shader_stats.py | 162 |
10 files changed, 1284 insertions, 91 deletions
diff --git a/scripts/audit_shader4_regs.py b/scripts/audit_shader4_regs.py new file mode 100644 index 000000000..0785a0999 --- /dev/null +++ b/scripts/audit_shader4_regs.py | |||
| @@ -0,0 +1,368 @@ | |||
| 1 | """Audit initial SGPR/VGPR read-before-write registers and RSRC2/PSV0 headers across CS, MS, and GS shaders. | ||
| 2 | |||
| 3 | Standard library only (no GPU, LLVM, or SPIRV-Tools required). Intended to run locally on a disassembled corpus: | ||
| 4 | |||
| 5 | python3 -I scripts/audit_shader4_regs.py <disasm_dir> [--fssm DIR] [--dxbc DIR] [--json OUT] [--limit N] | ||
| 6 | |||
| 7 | Directory layout defaults match make_game.py / tools/rdna2spirv.py: | ||
| 8 | <disasm_dir>/<name>.s | ||
| 9 | <disasm_dir>/../fssm/<name>.fssm | ||
| 10 | <disasm_dir>/../<name>.dxbc | ||
| 11 | <disasm_dir>/../index.json (optional stage map; otherwise stage is inferred from filename prefix) | ||
| 12 | """ | ||
| 13 | import argparse | ||
| 14 | import json | ||
| 15 | import os | ||
| 16 | import re | ||
| 17 | import struct | ||
| 18 | import sys | ||
| 19 | from collections import Counter | ||
| 20 | |||
| 21 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 22 | sys.path.insert(0, os.path.join(ROOT, "tools")) | ||
| 23 | import shader_ir # noqa: E402 | ||
| 24 | from shader_meta import SGPR_RMW # noqa: E402 | ||
| 25 | |||
| 26 | NO_DEST_OPS = ("s_cmp", "s_bitcmp", "v_cmpx", "s_set", "s_rfe", "s_branch", "s_cbranch", | ||
| 27 | "s_waitcnt", "s_barrier", "s_nop", "s_endpgm", "s_sendmsg", "s_sleep", | ||
| 28 | "exp", "buffer_store", "global_store", "flat_store", "scratch_store", | ||
| 29 | "image_store", "ds_write") | ||
| 30 | WAVE64_RE = re.compile(r"exec_hi|v_mbcnt_hi_u32_b32|_saveexec_b64|_wrexec_b64") | ||
| 31 | |||
| 32 | |||
| 33 | def base_op(op): | ||
| 34 | for sfx in ("_e32", "_e64", "_sdwa", "_dpp"): | ||
| 35 | if op.endswith(sfx): | ||
| 36 | return op[:-len(sfx)] | ||
| 37 | return op | ||
| 38 | |||
| 39 | |||
| 40 | def load_stage_map(disasm_dir): | ||
| 41 | parent = os.path.dirname(os.path.realpath(disasm_dir)) | ||
| 42 | for cand in (os.path.join(parent, "index.json"), os.path.join(disasm_dir, "index.json")): | ||
| 43 | if os.path.isfile(cand): | ||
| 44 | try: | ||
| 45 | with open(cand, encoding="utf-8") as _f: | ||
| 46 | data = json.load(_f) | ||
| 47 | if isinstance(data, list): | ||
| 48 | return {os.path.splitext(e["file"])[0]: e.get("stage", "?") for e in data if "file" in e} | ||
| 49 | if isinstance(data, dict): | ||
| 50 | return {k: v.get("stage", "?") for k, v in data.items() if isinstance(v, dict)} | ||
| 51 | except (OSError, ValueError, KeyError, TypeError): | ||
| 52 | pass | ||
| 53 | return {} | ||
| 54 | |||
| 55 | |||
| 56 | def stage_of(name, stage_map): | ||
| 57 | if name in stage_map: | ||
| 58 | return stage_map[name] | ||
| 59 | if len(name) >= 3 and name[2] == "_": | ||
| 60 | return name[:2].lower() | ||
| 61 | return "?" | ||
| 62 | |||
| 63 | |||
| 64 | def read_psv0(dxbc_path): | ||
| 65 | """Parse DXBC PSV0 chunk for MS (stage 13) or GS metadata; returns dict or None.""" | ||
| 66 | if not os.path.isfile(dxbc_path): | ||
| 67 | return None | ||
| 68 | with open(dxbc_path, "rb") as _f: | ||
| 69 | d = _f.read() | ||
| 70 | if len(d) < 32 or d[:4] != b"DXBC": | ||
| 71 | return None | ||
| 72 | nchunks = struct.unpack_from("<I", d, 28)[0] | ||
| 73 | for k in range(nchunks): | ||
| 74 | if 32 + 4 * k + 4 > len(d): | ||
| 75 | break | ||
| 76 | off = struct.unpack_from("<I", d, 32 + 4 * k)[0] | ||
| 77 | if off + 8 <= len(d) and d[off:off + 4] == b"PSV0": | ||
| 78 | plen = struct.unpack_from("<I", d, off + 4)[0] | ||
| 79 | p = d[off + 8:off + 8 + plen] | ||
| 80 | if len(p) < 4: | ||
| 81 | return None | ||
| 82 | rsize = struct.unpack_from("<I", p, 0)[0] | ||
| 83 | r = p[4:4 + rsize] | ||
| 84 | if len(r) < 48: | ||
| 85 | return {"rsize": rsize} | ||
| 86 | shared, _, payload = struct.unpack_from("<III", r, 0) | ||
| 87 | maxv, maxp = struct.unpack_from("<HH", r, 12) | ||
| 88 | tx, ty, tz = struct.unpack_from("<III", r, 36) | ||
| 89 | return { | ||
| 90 | "psv_stage": r[24], | ||
| 91 | "topology": r[27], | ||
| 92 | "shared_bytes": shared, | ||
| 93 | "payload_bytes": payload, | ||
| 94 | "maxv": maxv, | ||
| 95 | "maxp": maxp, | ||
| 96 | "threads": [tx, ty, tz], | ||
| 97 | } | ||
| 98 | return None | ||
| 99 | |||
| 100 | |||
| 101 | def decode_cs_rsrc2(fssm_path): | ||
| 102 | """Read COMPUTE_PGM_RSRC2 (0x138) and thread-group size (0x13C..0x144) from FSSM.""" | ||
| 103 | if not os.path.isfile(fssm_path): | ||
| 104 | return None | ||
| 105 | with open(fssm_path, "rb") as _f: | ||
| 106 | hdr = _f.read(0x148) | ||
| 107 | if len(hdr) < 0x148: | ||
| 108 | return None | ||
| 109 | rsrc2, lx, ly, lz = struct.unpack_from("<4I", hdr, 0x138) | ||
| 110 | return { | ||
| 111 | "rsrc2_hex": f"0x{rsrc2:08x}", | ||
| 112 | "scratch_en": rsrc2 & 1, | ||
| 113 | "user_sgpr": (rsrc2 >> 1) & 31, | ||
| 114 | "trap_present": (rsrc2 >> 6) & 1, | ||
| 115 | "tgid_x": (rsrc2 >> 7) & 1, | ||
| 116 | "tgid_y": (rsrc2 >> 8) & 1, | ||
| 117 | "tgid_z": (rsrc2 >> 9) & 1, | ||
| 118 | "tg_size_en": (rsrc2 >> 10) & 1, | ||
| 119 | "tidig_comp_cnt": (rsrc2 >> 11) & 3, | ||
| 120 | "lds_blocks_512b": (rsrc2 >> 15) & 0x1FF, | ||
| 121 | "group_size": [lx, ly, lz], | ||
| 122 | } | ||
| 123 | |||
| 124 | |||
| 125 | def read_fssm_words(fssm_path): | ||
| 126 | """Read raw u32 words at 0x138..0x144 for non-CS FSSM inspection.""" | ||
| 127 | if not os.path.isfile(fssm_path): | ||
| 128 | return None | ||
| 129 | with open(fssm_path, "rb") as _f: | ||
| 130 | hdr = _f.read(0x148) | ||
| 131 | if len(hdr) < 0x148: | ||
| 132 | return None | ||
| 133 | w = struct.unpack_from("<4I", hdr, 0x138) | ||
| 134 | return [f"0x{x:08x}" for x in w] | ||
| 135 | |||
| 136 | |||
| 137 | def _fmt_s3_arg(a, is_dst=False): | ||
| 138 | if is_dst: | ||
| 139 | return "D" | ||
| 140 | k = a["k"] | ||
| 141 | if k == "sgpr": | ||
| 142 | if a["r"] == 3 and a.get("n", 1) == 1: | ||
| 143 | return "s3" | ||
| 144 | return "sN" | ||
| 145 | if k == "vgpr": | ||
| 146 | return "vN" | ||
| 147 | if k == "imm": | ||
| 148 | v = a["v"] | ||
| 149 | return hex(v) if v >= 16 or v < 0 else str(v) | ||
| 150 | return a.get("t", k) | ||
| 151 | |||
| 152 | |||
| 153 | def rbw_registers(insns): | ||
| 154 | """Straight-line read-before-write SGPR, VGPR sets and s3-read instruction patterns.""" | ||
| 155 | written_s, written_v = set(), set() | ||
| 156 | rbw_s, rbw_v = set(), set() | ||
| 157 | s3_patterns = [] | ||
| 158 | |||
| 159 | def expand_reg(a): | ||
| 160 | return range(a["r"], a["r"] + a.get("n", 1)) | ||
| 161 | |||
| 162 | for ins in insns: | ||
| 163 | op = base_op(ins["op"]) | ||
| 164 | args = ins["args"] | ||
| 165 | if not args: | ||
| 166 | continue | ||
| 167 | is_no_dest = op.startswith(NO_DEST_OPS) | ||
| 168 | reads_imm_dst = op in SGPR_RMW | ||
| 169 | # Instructions that read their destination too. | ||
| 170 | dst_also_read = ( | ||
| 171 | reads_imm_dst or "fmac" in op or "mac_" in op or op == "v_writelane_b32" | ||
| 172 | or op == "v_swap_b32" or "_atomic_" in op | ||
| 173 | ) | ||
| 174 | # v_add_co_u32 / v_sub_co_u32 write both a[0] (VGPR) and a[1] (carry SGPR/vcc). | ||
| 175 | if not is_no_dest and op.startswith("v_") and "_co_" in op and "_ci_" not in op and len(args) >= 2: | ||
| 176 | dsts = args[:2] | ||
| 177 | srcs = args[2:] | ||
| 178 | elif is_no_dest: | ||
| 179 | dsts = [] | ||
| 180 | srcs = args | ||
| 181 | else: | ||
| 182 | dsts = args[:1] | ||
| 183 | srcs = (args[:1] if dst_also_read else []) + args[1:] | ||
| 184 | |||
| 185 | reads_s3_rbw = False | ||
| 186 | for a in srcs: | ||
| 187 | if a["k"] == "sgpr": | ||
| 188 | for r in expand_reg(a): | ||
| 189 | if r not in written_s: | ||
| 190 | rbw_s.add(r) | ||
| 191 | if r == 3: | ||
| 192 | reads_s3_rbw = True | ||
| 193 | elif a["k"] == "vgpr": | ||
| 194 | for r in expand_reg(a): | ||
| 195 | if r not in written_v: | ||
| 196 | rbw_v.add(r) | ||
| 197 | if reads_s3_rbw: | ||
| 198 | dst_ids = set() if reads_imm_dst else {id(x) for x in dsts} | ||
| 199 | fmt_args = ", ".join(_fmt_s3_arg(x, is_dst=(id(x) in dst_ids)) for x in args) | ||
| 200 | s3_patterns.append(f"{op} {fmt_args}".strip()) | ||
| 201 | |||
| 202 | for a in dsts: | ||
| 203 | if a["k"] == "sgpr": | ||
| 204 | written_s.update(expand_reg(a)) | ||
| 205 | elif a["k"] == "vgpr": | ||
| 206 | written_v.update(expand_reg(a)) | ||
| 207 | |||
| 208 | return sorted(rbw_s), sorted(rbw_v), s3_patterns | ||
| 209 | |||
| 210 | |||
| 211 | def detect_wave64(insns): | ||
| 212 | return any( | ||
| 213 | WAVE64_RE.search(" ".join([i["op"]] + [x.get("t", "") for x in i["args"]])) | ||
| 214 | or (base_op(i["op"]).endswith("_b64") and any(x.get("t") in ("exec", "vcc") for x in i["args"])) | ||
| 215 | for i in insns | ||
| 216 | ) | ||
| 217 | |||
| 218 | |||
| 219 | def audit(disasm_dir, fssm_dir=None, dxbc_dir=None, stages=("cs", "ms", "gs"), limit=None): | ||
| 220 | if limit is not None and limit < 0: | ||
| 221 | raise ValueError("limit must be non-negative") | ||
| 222 | parent = os.path.dirname(os.path.realpath(disasm_dir)) | ||
| 223 | fssm_dir = fssm_dir or os.path.join(parent, "fssm") | ||
| 224 | dxbc_dir = dxbc_dir or parent | ||
| 225 | stage_map = load_stage_map(disasm_dir) | ||
| 226 | |||
| 227 | files = sorted(f for f in os.listdir(disasm_dir) if f.endswith(".s")) | ||
| 228 | if limit is not None: | ||
| 229 | files = files[:limit] | ||
| 230 | |||
| 231 | report = { | ||
| 232 | st: { | ||
| 233 | "count": 0, | ||
| 234 | "wave64_heuristic": 0, | ||
| 235 | "wave32_heuristic": 0, | ||
| 236 | "rsrc2_combos": Counter(), | ||
| 237 | "psv0_combos": Counter(), | ||
| 238 | "fssm_0x138_words": Counter(), | ||
| 239 | "rbw_sgpr_counts": Counter(), | ||
| 240 | "rbw_vgpr_counts": Counter(), | ||
| 241 | "rbw_sgpr_sets": Counter(), | ||
| 242 | "rbw_vgpr_sets": Counter(), | ||
| 243 | "s3_rbw_op_patterns": Counter(), | ||
| 244 | } | ||
| 245 | for st in stages | ||
| 246 | } | ||
| 247 | |||
| 248 | for fname in files: | ||
| 249 | stem = os.path.splitext(fname)[0] | ||
| 250 | st = stage_of(stem, stage_map) | ||
| 251 | if st not in report: | ||
| 252 | continue | ||
| 253 | info = shader_ir.parse_file(os.path.join(disasm_dir, fname)) | ||
| 254 | insns = info["insns"] | ||
| 255 | rbw_s, rbw_v, s3_pats = rbw_registers(insns) | ||
| 256 | rec = report[st] | ||
| 257 | rec["count"] += 1 | ||
| 258 | if detect_wave64(insns): | ||
| 259 | rec["wave64_heuristic"] += 1 | ||
| 260 | else: | ||
| 261 | rec["wave32_heuristic"] += 1 | ||
| 262 | for r in rbw_s: | ||
| 263 | rec["rbw_sgpr_counts"][f"s{r}"] += 1 | ||
| 264 | for r in rbw_v: | ||
| 265 | rec["rbw_vgpr_counts"][f"v{r}"] += 1 | ||
| 266 | rec["rbw_sgpr_sets"][",".join(f"s{r}" for r in rbw_s) or "(none)"] += 1 | ||
| 267 | rec["rbw_vgpr_sets"][",".join(f"v{r}" for r in rbw_v) or "(none)"] += 1 | ||
| 268 | for pat in s3_pats: | ||
| 269 | rec["s3_rbw_op_patterns"][pat] += 1 | ||
| 270 | |||
| 271 | fssm_path = os.path.join(fssm_dir, stem + ".fssm") | ||
| 272 | dxbc_path = os.path.join(dxbc_dir, stem + ".dxbc") | ||
| 273 | if st == "cs": | ||
| 274 | dec = decode_cs_rsrc2(fssm_path) | ||
| 275 | if dec: | ||
| 276 | key = ( | ||
| 277 | f"user={dec['user_sgpr']} tgid={dec['tgid_x']}{dec['tgid_y']}{dec['tgid_z']} " | ||
| 278 | f"tg_size={dec['tg_size_en']} tidig={dec['tidig_comp_cnt']} " | ||
| 279 | f"scratch={dec['scratch_en']} trap={dec['trap_present']} " | ||
| 280 | f"lds={dec['lds_blocks_512b'] * 512}B" | ||
| 281 | ) | ||
| 282 | rec["rsrc2_combos"][key] += 1 | ||
| 283 | else: | ||
| 284 | rec["rsrc2_combos"]["(missing fssm)"] += 1 | ||
| 285 | else: | ||
| 286 | words = read_fssm_words(fssm_path) | ||
| 287 | if words: | ||
| 288 | rec["fssm_0x138_words"][" ".join(words)] += 1 | ||
| 289 | psv = read_psv0(dxbc_path) | ||
| 290 | if psv: | ||
| 291 | if "threads" in psv: | ||
| 292 | key = ( | ||
| 293 | f"stage={psv['psv_stage']} topo={psv['topology']} " | ||
| 294 | f"threads={'x'.join(map(str, psv['threads']))} " | ||
| 295 | f"maxv={psv['maxv']} maxp={psv['maxp']} " | ||
| 296 | f"payload={psv['payload_bytes']}B shared={psv['shared_bytes']}B" | ||
| 297 | ) | ||
| 298 | else: | ||
| 299 | key = f"rsize={psv['rsize']}" | ||
| 300 | rec["psv0_combos"][key] += 1 | ||
| 301 | |||
| 302 | # Convert Counters to plain sorted dicts for JSON/text output. | ||
| 303 | out = {} | ||
| 304 | for st, rec in report.items(): | ||
| 305 | out[st] = { | ||
| 306 | "count": rec["count"], | ||
| 307 | "wave64_heuristic": rec["wave64_heuristic"], | ||
| 308 | "wave32_heuristic": rec["wave32_heuristic"], | ||
| 309 | "rsrc2_combos": dict(rec["rsrc2_combos"].most_common()), | ||
| 310 | "psv0_combos": dict(rec["psv0_combos"].most_common()), | ||
| 311 | "fssm_0x138_words": dict(rec["fssm_0x138_words"].most_common(20)), | ||
| 312 | "rbw_sgpr_counts": dict(sorted(rec["rbw_sgpr_counts"].items(), key=lambda kv: int(kv[0][1:]))), | ||
| 313 | "rbw_vgpr_counts": dict(sorted(rec["rbw_vgpr_counts"].items(), key=lambda kv: int(kv[0][1:]))), | ||
| 314 | "top_rbw_sgpr_sets": dict(rec["rbw_sgpr_sets"].most_common(15)), | ||
| 315 | "top_rbw_vgpr_sets": dict(rec["rbw_vgpr_sets"].most_common(15)), | ||
| 316 | "s3_rbw_op_patterns": dict(rec["s3_rbw_op_patterns"].most_common(20)), | ||
| 317 | } | ||
| 318 | return out | ||
| 319 | |||
| 320 | |||
| 321 | def print_report(rep): | ||
| 322 | for st, rec in rep.items(): | ||
| 323 | print(f"=== {st.upper()} ({rec['count']} shaders; wave64={rec['wave64_heuristic']}, wave32={rec['wave32_heuristic']}) ===") | ||
| 324 | if rec["rsrc2_combos"]: | ||
| 325 | print(" COMPUTE_PGM_RSRC2 combinations:") | ||
| 326 | for k, v in list(rec["rsrc2_combos"].items())[:20]: | ||
| 327 | print(f" {v:6d} {k}") | ||
| 328 | if rec["psv0_combos"]: | ||
| 329 | print(" PSV0 combinations:") | ||
| 330 | for k, v in list(rec["psv0_combos"].items())[:20]: | ||
| 331 | print(f" {v:6d} {k}") | ||
| 332 | if rec["fssm_0x138_words"]: | ||
| 333 | print(" FSSM 0x138..0x144 raw words (top 10):") | ||
| 334 | for k, v in list(rec["fssm_0x138_words"].items())[:10]: | ||
| 335 | print(f" {v:6d} {k}") | ||
| 336 | if rec["rbw_sgpr_counts"]: | ||
| 337 | print(" RBW SGPRs:", " ".join(f"{k}:{v}" for k, v in rec["rbw_sgpr_counts"].items())) | ||
| 338 | if rec["rbw_vgpr_counts"]: | ||
| 339 | print(" RBW VGPRs:", " ".join(f"{k}:{v}" for k, v in rec["rbw_vgpr_counts"].items())) | ||
| 340 | if rec["s3_rbw_op_patterns"]: | ||
| 341 | print(" s3 RBW instruction patterns:") | ||
| 342 | for k, v in list(rec["s3_rbw_op_patterns"].items())[:10]: | ||
| 343 | print(f" {v:6d} {k}") | ||
| 344 | |||
| 345 | |||
| 346 | def main(argv=None): | ||
| 347 | ap = argparse.ArgumentParser(description="Audit CS/MS/GS RSRC2/PSV0 headers and read-before-write registers.") | ||
| 348 | ap.add_argument("disasm_dir", help="directory of disassembled .s files") | ||
| 349 | ap.add_argument("--fssm", default=None, help="directory of .fssm files (default: <disasm_dir>/../fssm)") | ||
| 350 | ap.add_argument("--dxbc", default=None, help="directory of .dxbc files (default: <disasm_dir>/..)") | ||
| 351 | ap.add_argument("--json", dest="json_out", default=None, help="optional path to write full JSON report") | ||
| 352 | ap.add_argument("--limit", type=int, default=None, help="stop after N .s files") | ||
| 353 | a = ap.parse_args(argv) | ||
| 354 | if a.limit is not None and a.limit < 0: | ||
| 355 | ap.exit(2, f"{ap.prog}: error: --limit must be non-negative\n") | ||
| 356 | |||
| 357 | rep = audit(a.disasm_dir, fssm_dir=a.fssm, dxbc_dir=a.dxbc, limit=a.limit) | ||
| 358 | print_report(rep) | ||
| 359 | if a.json_out: | ||
| 360 | with open(a.json_out, "w", encoding="utf-8") as f: | ||
| 361 | json.dump(rep, f, indent=2) | ||
| 362 | f.write("\n") | ||
| 363 | print(f"wrote {a.json_out}") | ||
| 364 | return 0 | ||
| 365 | |||
| 366 | |||
| 367 | if __name__ == "__main__": | ||
| 368 | sys.exit(main()) | ||
diff --git a/scripts/bench_wave64.py b/scripts/bench_wave64.py new file mode 100644 index 000000000..812cc80a4 --- /dev/null +++ b/scripts/bench_wave64.py | |||
| @@ -0,0 +1,112 @@ | |||
| 1 | """Time a wave64 compute shader (runtime/test/shaders/cs_bench_mix.asm) native and emulated, on the AMD and NVIDIA GPU. | ||
| 2 | |||
| 3 | python -I scripts/bench_wave64.py [--build DIR] [--llvm-mc PATH] [--groups N] [--reps N] [--procs N] [--shader NAME] | ||
| 4 | |||
| 5 | Three configurations: AMD with its native 64-wide subgroup (no flag), AMD with --wave64-emulate, NVIDIA with | ||
| 6 | --wave64-emulate (the GPU is chosen with VK_LOADER_DRIVERS_SELECT='*amd*' / '*nv*'). Each runs `procs` processes of | ||
| 7 | vk_compute_test with VKC_BENCH=`reps` timed dispatches of `groups` workgroups; the table gives the median over all | ||
| 8 | dispatches, the spread of the per-process medians (other programs share the GPU, so look at it), the number of | ||
| 9 | translated segments (static: blocks + continuation segments; every continuation segment is one more workgroup barrier | ||
| 10 | on the path through it) and whether the output bytes of the emulated runs equal the native AMD run, which is the reference (they must). | ||
| 11 | """ | ||
| 12 | import argparse | ||
| 13 | import json | ||
| 14 | import os | ||
| 15 | import re | ||
| 16 | import statistics | ||
| 17 | import subprocess | ||
| 18 | import sys | ||
| 19 | import tempfile | ||
| 20 | |||
| 21 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 22 | BUILD_PY = os.path.join(ROOT, "runtime", "test", "shaders", "build.py") | ||
| 23 | CONFIGS = [("AMD native", "*amd*", False), ("AMD --wave64-emulate", "*amd*", True), | ||
| 24 | ("NVIDIA --wave64-emulate", "*nv*", True)] | ||
| 25 | |||
| 26 | |||
| 27 | def build(work, name, emulate, llvm_mc): | ||
| 28 | out = os.path.join(work, "emu" if emulate else "native") | ||
| 29 | env = dict(os.environ, LLVM_MC=llvm_mc) | ||
| 30 | env.pop("LEONIDA_W64_EMULATE", None) | ||
| 31 | if emulate: | ||
| 32 | env["LEONIDA_W64_EMULATE"] = "1" | ||
| 33 | r = subprocess.run([sys.executable, "-I", BUILD_PY, out, name], env=env, capture_output=True, text=True) | ||
| 34 | if r.returncode: | ||
| 35 | sys.exit(r.stdout + r.stderr) | ||
| 36 | return os.path.join(out, "spirv", name + ".spv") | ||
| 37 | |||
| 38 | |||
| 39 | def segments(spv): | ||
| 40 | """(segments, continuation segments) of an emulated module: the cases of the scheduler's OpSwitch.""" | ||
| 41 | text = open(spv[:-4] + ".spvasm", encoding="utf-8").read() | ||
| 42 | m = re.search(r"OpSwitch %pcv %sw_default ([^\n]+)", text) | ||
| 43 | if not m: | ||
| 44 | return None | ||
| 45 | cases = [int(x) for x in re.findall(r"(\d+) %blk\d+", m.group(1))] | ||
| 46 | blocks = next((i for i, c in enumerate(cases) if c != i), len(cases)) # blocks 0..n-1, then "done" = n, then segments | ||
| 47 | return len(cases), len(cases) - blocks | ||
| 48 | |||
| 49 | |||
| 50 | def run(tools, spv, groups, reps, driver, emulate): | ||
| 51 | env = dict(os.environ, VK_LOADER_DRIVERS_SELECT=driver, VKC_BENCH=str(reps)) | ||
| 52 | args = [os.path.join(tools, "vk_compute_test" + (".exe" if os.name == "nt" else "")), spv, str(groups), "dump"] | ||
| 53 | if not emulate: | ||
| 54 | args.append("--require-wave64") | ||
| 55 | r = subprocess.run(args, env=env, capture_output=True, text=True) | ||
| 56 | out = r.stdout + r.stderr | ||
| 57 | m = re.search(r"bench ms: median=([\d.]+) min=([\d.]+) max=([\d.]+)", out) | ||
| 58 | h = re.search(r"bench out fnv1a: (\w+)", out) | ||
| 59 | dev = re.search(r"device: (.*) \(subgroup", out) | ||
| 60 | if r.returncode or not m or not h or "0 mismatches" not in out: | ||
| 61 | why = f"exit {r.returncode}" if r.returncode else "no 'bench ms' / 'bench out fnv1a' line (rebuild vk_compute_test)" | ||
| 62 | return None, why + ": " + (out.strip().splitlines()[-1:] or ["no output"])[0], None | ||
| 63 | return (float(m.group(1)), float(m.group(2))), h.group(1), dev.group(1) if dev else "?" | ||
| 64 | |||
| 65 | |||
| 66 | def main(): | ||
| 67 | ap = argparse.ArgumentParser() | ||
| 68 | ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build")) | ||
| 69 | ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc")) | ||
| 70 | ap.add_argument("--groups", type=int, default=65536) | ||
| 71 | ap.add_argument("--reps", type=int, default=30) | ||
| 72 | ap.add_argument("--procs", type=int, default=5) | ||
| 73 | ap.add_argument("--shader", default="cs_bench_mix") | ||
| 74 | a = ap.parse_args() | ||
| 75 | with tempfile.TemporaryDirectory(prefix="bench-w64-") as work: | ||
| 76 | spv = {False: build(work, a.shader, False, a.llvm_mc), True: build(work, a.shader, True, a.llvm_mc)} | ||
| 77 | seg = segments(spv[True]) | ||
| 78 | print(f"{a.shader}: {a.groups} workgroups of the shader's group size, {a.procs} x {a.reps} timed dispatches") | ||
| 79 | if seg: | ||
| 80 | print(f"emulated: {seg[0]} segments, {seg[1]} of them continuation segments (one extra round each)") | ||
| 81 | hashes, rows = {}, [] | ||
| 82 | for name, driver, emulate in CONFIGS: | ||
| 83 | med, mins, seen, dev = [], [], set(), None | ||
| 84 | for _ in range(a.procs): | ||
| 85 | t, h, dev = run(a.build, spv[emulate], a.groups, a.reps, driver, emulate) | ||
| 86 | if t is None: | ||
| 87 | med = None | ||
| 88 | print(f"{name}: failed or unsupported: {h}") | ||
| 89 | break | ||
| 90 | med.append(t[0]) | ||
| 91 | mins.append(t[1]) | ||
| 92 | seen.add(h) | ||
| 93 | if med: | ||
| 94 | # Only a configuration whose every process ran counts: the hashes of the processes before a | ||
| 95 | # failed one used to be kept, so the failure passed as a configuration that had run. | ||
| 96 | hashes[name] = seen | ||
| 97 | rows.append((name, dev, statistics.median(med), min(mins), min(med), max(med))) | ||
| 98 | for name, dev, m, lo, a_, b_ in rows: | ||
| 99 | print(f"{name:26} {dev:34} median {m:8.3f} ms best {lo:8.3f} process medians {a_:.3f}..{b_:.3f}") | ||
| 100 | ref_name = CONFIGS[0][0] | ||
| 101 | ref = hashes.get(ref_name) | ||
| 102 | if not ref or len(ref) != 1: | ||
| 103 | print(f"no reference output from {ref_name}: cannot compare") | ||
| 104 | return 1 | ||
| 105 | bad = [n for n, _, _ in CONFIGS[1:] if n in hashes and hashes[n] != ref] | ||
| 106 | print(f"reference output hash: {next(iter(ref))} ({ref_name})") | ||
| 107 | print("emulated output equals the reference" if not bad else f"OUTPUT DIFFERS from the reference: {', '.join(bad)}") | ||
| 108 | return 1 if bad or len(hashes) < len(CONFIGS) else 0 | ||
| 109 | |||
| 110 | |||
| 111 | if __name__ == "__main__": | ||
| 112 | sys.exit(main()) | ||
diff --git a/scripts/build_llvm_mc.ps1 b/scripts/build_llvm_mc.ps1 index ea72db26f..66508971b 100644 --- a/scripts/build_llvm_mc.ps1 +++ b/scripts/build_llvm_mc.ps1 | |||
| @@ -15,6 +15,16 @@ param( | |||
| 15 | ) | 15 | ) |
| 16 | $ErrorActionPreference = "Stop" | 16 | $ErrorActionPreference = "Stop" |
| 17 | 17 | ||
| 18 | if (-not $Keep) { | ||
| 19 | # Compare directory boundaries, including when the paths do not exist yet. | ||
| 20 | $paths = $ExecutionContext.SessionState.Path | ||
| 21 | $tempDir = [IO.Path]::GetFullPath($paths.GetUnresolvedProviderPathFromPSPath($Temp)).TrimEnd('\') + '\' | ||
| 22 | $destDir = [IO.Path]::GetFullPath($paths.GetUnresolvedProviderPathFromPSPath($Dest)).TrimEnd('\') + '\' | ||
| 23 | if ($destDir.StartsWith($tempDir, [StringComparison]::OrdinalIgnoreCase)) { | ||
| 24 | throw "Cleanup would delete the installation. Choose a -Dest outside -Temp or use -Keep." | ||
| 25 | } | ||
| 26 | } | ||
| 27 | |||
| 18 | foreach ($t in "git", "python") { | 28 | foreach ($t in "git", "python") { |
| 19 | if (-not (Get-Command $t -ErrorAction SilentlyContinue)) { throw "$t wasn't found on PATH." } | 29 | if (-not (Get-Command $t -ErrorAction SilentlyContinue)) { throw "$t wasn't found on PATH." } |
| 20 | } | 30 | } |
| @@ -74,7 +84,13 @@ if ($LASTEXITCODE -ne 0 -or -not ($probe -match "s_endpgm")) { throw "the built | |||
| 74 | New-Item -ItemType Directory -Force $Dest | Out-Null | 84 | New-Item -ItemType Directory -Force $Dest | Out-Null |
| 75 | $final = Join-Path $Dest "llvm-mc.exe" | 85 | $final = Join-Path $Dest "llvm-mc.exe" |
| 76 | Copy-Item -Force $exe $final | 86 | Copy-Item -Force $exe $final |
| 77 | if (-not $Keep) { Remove-Item -Recurse -Force $Temp } | 87 | if (-not $Keep) { |
| 88 | try { | ||
| 89 | Remove-Item -LiteralPath $Temp -Recurse -Force | ||
| 90 | } catch { | ||
| 91 | Write-Warning "Installed $final, but cleanup of '$Temp' failed: $($_.Exception.Message)" | ||
| 92 | } | ||
| 93 | } | ||
| 78 | if (-not $NoEnv) { | 94 | if (-not $NoEnv) { |
| 79 | [Environment]::SetEnvironmentVariable("LLVM_MC", $final, "User") | 95 | [Environment]::SetEnvironmentVariable("LLVM_MC", $final, "User") |
| 80 | Write-Host "LLVM_MC set for this user (open a new terminal to pick it up)." | 96 | Write-Host "LLVM_MC set for this user (open a new terminal to pick it up)." |
diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1 index 777064af6..2ac61356b 100644 --- a/scripts/build_runtime.ps1 +++ b/scripts/build_runtime.ps1 | |||
| @@ -1,6 +1,8 @@ | |||
| 1 | # Builds runtime\build\gta6rt.exe with MSVC at BelowNormal priority, on half the cores. | 1 | # Builds runtime\build\gta6rt.exe with MSVC at BelowNormal priority, on half the cores. |
| 2 | # Uses VS's CMake + Ninja when the "C++ CMake tools" component is installed, otherwise calls cl.exe directly. | 2 | # Uses VS's CMake + Ninja when the "C++ CMake tools" component is installed, otherwise calls cl.exe directly. |
| 3 | param([switch]$Debug) | 3 | # The GameInput controller shim (SDL3, docs/gameinput.md) is built only on the CMake path: with an installed SDL3, or |
| 4 | # with -FetchSdl3, which lets CMake download the pinned SDL3 release. The cl.exe fallback never builds it. | ||
| 5 | param([switch]$Debug, [switch]$FetchSdl3) | ||
| 4 | $ErrorActionPreference = "Stop" | 6 | $ErrorActionPreference = "Stop" |
| 5 | 7 | ||
| 6 | $root = Split-Path $PSScriptRoot -Parent | 8 | $root = Split-Path $PSScriptRoot -Parent |
| @@ -18,19 +20,26 @@ $cmakeDir = Join-Path $vs "Common7\IDE\CommonExtensions\Microsoft\CMake" | |||
| 18 | $cmake = Join-Path $cmakeDir "CMake\bin\cmake.exe" | 20 | $cmake = Join-Path $cmakeDir "CMake\bin\cmake.exe" |
| 19 | $ninja = Join-Path $cmakeDir "Ninja\ninja.exe" | 21 | $ninja = Join-Path $cmakeDir "Ninja\ninja.exe" |
| 20 | $cfg = if ($Debug) { "Debug" } else { "RelWithDebInfo" } | 22 | $cfg = if ($Debug) { "Debug" } else { "RelWithDebInfo" } |
| 23 | $sdl = if ($FetchSdl3) { "-DLEONIDA_SDL3_FETCH=ON" } else { "" } | ||
| 21 | 24 | ||
| 22 | if ((Test-Path $cmake) -and (Test-Path $ninja)) { | 25 | if ((Test-Path $cmake) -and (Test-Path $ninja)) { |
| 23 | $body = @" | 26 | $body = @" |
| 24 | "$cmake" -S "$src" -B "$out" -G Ninja "-DCMAKE_MAKE_PROGRAM=$ninja" -DCMAKE_BUILD_TYPE=$cfg || exit /b 1 | 27 | "$cmake" -S "$src" -B "$out" -G Ninja "-DCMAKE_MAKE_PROGRAM=$ninja" -DCMAKE_BUILD_TYPE=$cfg $sdl || exit /b 1 |
| 25 | "$cmake" --build "$out" -j $jobs || exit /b 1 | 28 | "$cmake" --build "$out" -j $jobs || exit /b 1 |
| 26 | "@ | 29 | "@ |
| 27 | } else { | 30 | } else { |
| 28 | # Keep this list in step with runtime\CMakeLists.txt. | 31 | # Keep this list in step with runtime\CMakeLists.txt. Optional parts that need a dependency are left out here: |
| 29 | $files = "src\main.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\xmem.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp" | ForEach-Object { "`"$src\$_`"" } | 32 | # the GameInput shim (SDL3), so controllers go through the host's GameInput.dll, if any, as without the shim. |
| 33 | Write-Warning "VS C++ CMake tools not found: building with cl.exe directly, without the GameInput shim (SDL3). Install the CMake tools component to get it." | ||
| 34 | $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue" | ||
| 35 | $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" } | ||
| 36 | $files = "src\main.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\xmem.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\process.cpp" | ForEach-Object { "`"$src\$_`"" } | ||
| 37 | $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`"" | ||
| 30 | $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" } | 38 | $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" } |
| 31 | $body = @" | 39 | $body = @" |
| 32 | cd /d "$out" || exit /b 1 | 40 | cd /d "$out" || exit /b 1 |
| 33 | cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /Zi $opt /MP$jobs /DWIN32_LEAN_AND_MEAN /DNOMINMAX /DUNICODE /D_UNICODE $($files -join ' ') /Fe:gta6rt.exe /link /OPT:NOREF psapi.lib || exit /b 1 | 41 | cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /Zi $opt /MP$jobs /DWIN32_LEAN_AND_MEAN /DNOMINMAX /DUNICODE /D_UNICODE $includes $($files -join ' ') $($xtaskqueueFiles -join ' ') /Fe:gta6rt.exe /link /OPT:NOREF psapi.lib ole32.lib || exit /b 1 |
| 42 | cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /MT /DWIN32_LEAN_AND_MEAN /DNOMINMAX "$src\src\tls_host.cpp" /LD /Fe:gta6rt_tls_host.dll || exit /b 1 | ||
| 34 | cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\root_sig_test.cpp" /Fe:root_sig_test.exe /link d3d12.lib || exit /b 1 | 43 | cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\root_sig_test.cpp" /Fe:root_sig_test.exe /link d3d12.lib || exit /b 1 |
| 35 | cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\device_proxy_test.cpp" /Fe:device_proxy_test.exe /link d3d12.lib dxgi.lib || exit /b 1 | 44 | cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\device_proxy_test.cpp" /Fe:device_proxy_test.exe /link d3d12.lib dxgi.lib || exit /b 1 |
| 36 | cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\src" "$src\test\descriptor_table_test.cpp" /Fe:descriptor_table_test.exe /link /OPT:NOREF || exit /b 1 | 45 | cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\src" "$src\test\descriptor_table_test.cpp" /Fe:descriptor_table_test.exe /link /OPT:NOREF || exit /b 1 |
| @@ -39,6 +48,7 @@ if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNO | |||
| 39 | if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_texture_test.cpp" /Fe:vk_texture_test.exe || exit /b 1 | 48 | if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_texture_test.cpp" /Fe:vk_texture_test.exe || exit /b 1 |
| 40 | if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\gfx10_descriptors_test.cpp" /Fe:gfx10_descriptors_test.exe || exit /b 1 | 49 | if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\gfx10_descriptors_test.cpp" /Fe:gfx10_descriptors_test.exe || exit /b 1 |
| 41 | if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_bindless_test.cpp" /Fe:vk_bindless_test.exe || exit /b 1 | 50 | if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_bindless_test.cpp" /Fe:vk_bindless_test.exe || exit /b 1 |
| 51 | if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_descriptor_bench.cpp" /Fe:vk_descriptor_bench.exe || exit /b 1 | ||
| 42 | "@ | 52 | "@ |
| 43 | } | 53 | } |
| 44 | 54 | ||
diff --git a/scripts/carve_all.ps1 b/scripts/carve_all.ps1 index c70aab30a..6229941f8 100644 --- a/scripts/carve_all.ps1 +++ b/scripts/carve_all.ps1 | |||
| @@ -3,18 +3,24 @@ | |||
| 3 | param([Parameter(Mandatory)][string]$Game, [Parameter(Mandatory)][string]$Out) | 3 | param([Parameter(Mandatory)][string]$Game, [Parameter(Mandatory)][string]$Out) |
| 4 | $root = Split-Path $PSScriptRoot -Parent | 4 | $root = Split-Path $PSScriptRoot -Parent |
| 5 | $tool = Join-Path $root "tools\rpf9_carve.py" | 5 | $tool = Join-Path $root "tools\rpf9_carve.py" |
| 6 | # -Game may be relative or end in a separator; archive names are cut from a separator-ended prefix. | ||
| 7 | $Game = (Resolve-Path -LiteralPath $Game).ProviderPath | ||
| 8 | # Resolve-Path preserves 8.3 short components (e.g. RUNNER~1), while Get-ChildItem emits canonical | ||
| 9 | # FullName paths. Deriving the prefix from Resolve-Path then cuts the wrong number of characters and | ||
| 10 | # re-carves already-caved archives; use the canonical form for both sides of the Substring. | ||
| 11 | $prefix = (Get-Item -LiteralPath $Game).FullName.TrimEnd('\') + '\' | ||
| 6 | $rows = @() | 12 | $rows = @() |
| 7 | foreach ($f in Get-ChildItem $Game -Recurse -Filter *.rpf | Sort-Object Length) { | 13 | foreach ($f in Get-ChildItem -LiteralPath $Game -Recurse -Filter *.rpf | Sort-Object Length) { |
| 8 | $rel = $f.FullName.Substring($Game.Length + 1) | 14 | $rel = $f.FullName.Substring($prefix.Length) |
| 9 | $dest = Join-Path $Out ([IO.Path]::GetFileNameWithoutExtension(($rel -replace "[\\/]", "_"))) | 15 | $dest = Join-Path $Out ([IO.Path]::GetFileNameWithoutExtension(($rel -replace "[\\/]", "_"))) |
| 10 | if (-not (Test-Path (Join-Path $dest "index.json"))) { | 16 | if (-not (Test-Path -LiteralPath (Join-Path $dest "index.json"))) { |
| 11 | Write-Host ("{0:HH:mm:ss} carving {1} ({2:N1} GiB)" -f (Get-Date), $rel, ($f.Length / 1GB)) | 17 | Write-Host ("{0:HH:mm:ss} carving {1} ({2:N1} GiB)" -f (Get-Date), $rel, ($f.Length / 1GB)) |
| 12 | python -I $tool $f.FullName $dest | Select-Object -Last 1 | 18 | python -I $tool $f.FullName $dest | Select-Object -Last 1 |
| 13 | } | 19 | } |
| 14 | $s = (Get-Content (Join-Path $dest "index.json") -Raw | ConvertFrom-Json).summary | 20 | $s = (Get-Content -LiteralPath (Join-Path $dest "index.json") -Raw | ConvertFrom-Json).summary |
| 15 | $rows += [pscustomobject]@{ archive = $rel; files = $s.files; bink2 = $s.bink2_files; span = $s.span | 21 | $rows += [pscustomobject]@{ archive = $rel; files = $s.files; bink2 = $s.bink2_files; span = $s.span |
| 16 | readable = [math]::Round(($s.compressed_bytes) / $s.span, 4) | 22 | readable = [math]::Round(($s.compressed_bytes) / $s.span, 4) |
| 17 | unread = [math]::Round($s.unread_bytes / $s.span, 4); inflated = $s.inflated_bytes } | 23 | unread = [math]::Round($s.unread_bytes / $s.span, 4); inflated = $s.inflated_bytes } |
| 18 | } | 24 | } |
| 19 | $rows | ConvertTo-Json | Set-Content -Encoding utf8 (Join-Path $Out "coverage.json") | 25 | $rows | ConvertTo-Json | Set-Content -Encoding utf8 -LiteralPath (Join-Path $Out "coverage.json") |
| 20 | $rows | Format-Table archive, files, bink2, @{n = "GiB"; e = { [math]::Round($_.span / 1GB, 2) } }, readable, unread -AutoSize | Out-String -Width 200 | 26 | $rows | Format-Table archive, files, bink2, @{n = "GiB"; e = { [math]::Round($_.span / 1GB, 2) } }, readable, unread -AutoSize | Out-String -Width 200 |
diff --git a/scripts/first_look.ps1 b/scripts/first_look.ps1 index 913b0a9c3..66327a1dd 100644 --- a/scripts/first_look.ps1 +++ b/scripts/first_look.ps1 | |||
| @@ -30,7 +30,7 @@ Write-Host "`n== Loader dry run (map, relocate, bind imports; nothing executes)" | |||
| 30 | & $rt --dry-run $Exe --game-dir $GameDir 2>&1 | Tee-Object (Join-Path $out "dryrun.txt") | Select-Object -Last 40 | 30 | & $rt --dry-run $Exe --game-dir $GameDir 2>&1 | Tee-Object (Join-Path $out "dryrun.txt") | Select-Object -Last 40 |
| 31 | 31 | ||
| 32 | # Shim to-do list, grouped by DLL, most functions first. | 32 | # Shim to-do list, grouped by DLL, most functions first. |
| 33 | $report = Get-Content (Join-Path $out "$name.json") -Raw | ConvertFrom-Json | 33 | $report = Get-Content (Join-Path $out "$([IO.Path]::GetFileName($Exe)).json") -Raw | ConvertFrom-Json |
| 34 | $todo = $report.imports | Where-Object { $_.where -eq "shim" } | Sort-Object { -$_.functions.Count } | 34 | $todo = $report.imports | Where-Object { $_.where -eq "shim" } | Sort-Object { -$_.functions.Count } |
| 35 | $lines = foreach ($t in $todo) { "{0,-40} {1,5}" -f $t.dll, $t.functions.Count } | 35 | $lines = foreach ($t in $todo) { "{0,-40} {1,5}" -f $t.dll, $t.functions.Count } |
| 36 | $lines | Set-Content (Join-Path $out "shim-todo.txt") | 36 | $lines | Set-Content (Join-Path $out "shim-todo.txt") |
diff --git a/scripts/meta_to_xml.ps1 b/scripts/meta_to_xml.ps1 index 78e5fbbeb..2efe0c32a 100644 --- a/scripts/meta_to_xml.ps1 +++ b/scripts/meta_to_xml.ps1 | |||
| @@ -14,13 +14,13 @@ Add-Type -Path "$CodeWalker\SharpDX.dll"; Add-Type -Path "$CodeWalker\SharpDX.Ma | |||
| 14 | [void][Reflection.Assembly]::LoadFrom("$CodeWalker\CodeWalker.Core.dll") | 14 | [void][Reflection.Assembly]::LoadFrom("$CodeWalker\CodeWalker.Core.dll") |
| 15 | New-Item -ItemType Directory -Force $Out | Out-Null | 15 | New-Item -ItemType Directory -Force $Out | Out-Null |
| 16 | $fail = Join-Path $Out "failures.txt" | 16 | $fail = Join-Path $Out "failures.txt" |
| 17 | "" | Set-Content $fail | 17 | "" | Set-Content -LiteralPath $fail |
| 18 | $ok = @{ pso = 0; rbf = 0 }; $bad = @{ pso = 0; rbf = 0 }; $n = 0 | 18 | $ok = @{ pso = 0; rbf = 0 }; $bad = @{ pso = 0; rbf = 0 }; $n = 0 |
| 19 | 19 | ||
| 20 | foreach ($dir in Get-ChildItem $Carve -Directory) { | 20 | foreach ($dir in Get-ChildItem -LiteralPath $Carve -Directory) { |
| 21 | $idx = Join-Path $dir.FullName "index.json" | 21 | $idx = Join-Path $dir.FullName "index.json" |
| 22 | if (-not (Test-Path $idx)) { continue } | 22 | if (-not (Test-Path -LiteralPath $idx)) { continue } |
| 23 | $files = (Get-Content $idx -Raw | ConvertFrom-Json).files | | 23 | $files = (Get-Content -LiteralPath $idx -Raw | ConvertFrom-Json).files | |
| 24 | Where-Object { $_.head.StartsWith("5053494e") -or $_.head.StartsWith("52424630") } | 24 | Where-Object { $_.head.StartsWith("5053494e") -or $_.head.StartsWith("52424630") } |
| 25 | if (-not $files) { continue } | 25 | if (-not $files) { continue } |
| 26 | $dest = Join-Path $Out $dir.Name | 26 | $dest = Join-Path $Out $dir.Name |
| @@ -44,7 +44,7 @@ foreach ($dir in Get-ChildItem $Carve -Directory) { | |||
| 44 | } catch { | 44 | } catch { |
| 45 | $bad[$kind]++ | 45 | $bad[$kind]++ |
| 46 | $msg = $_.Exception.InnerException; if (-not $msg) { $msg = $_.Exception } | 46 | $msg = $_.Exception.InnerException; if (-not $msg) { $msg = $_.Exception } |
| 47 | "$($dir.Name)\$name $kind : $($msg.Message)" | Add-Content $fail | 47 | "$($dir.Name)\$name $kind : $($msg.Message)" | Add-Content -LiteralPath $fail |
| 48 | } | 48 | } |
| 49 | } | 49 | } |
| 50 | if ($Limit -and $n -ge $Limit) { break } | 50 | if ($Limit -and $n -ge $Limit) { break } |
diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 124bdeeb1..9693b6ac2 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py | |||
| @@ -7,6 +7,7 @@ Usage: | |||
| 7 | """ | 7 | """ |
| 8 | import argparse | 8 | import argparse |
| 9 | import json | 9 | import json |
| 10 | import math | ||
| 10 | import os | 11 | import os |
| 11 | import re | 12 | import re |
| 12 | import shutil | 13 | import shutil |
| @@ -18,12 +19,22 @@ from pathlib import Path | |||
| 18 | 19 | ||
| 19 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | 20 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 20 | SHADER_DIR = os.path.join(ROOT, "runtime", "test", "shaders") | 21 | SHADER_DIR = os.path.join(ROOT, "runtime", "test", "shaders") |
| 22 | |||
| 21 | TRANSLATOR = os.path.join(ROOT, "tools", "rdna2spirv.py") | 23 | TRANSLATOR = os.path.join(ROOT, "tools", "rdna2spirv.py") |
| 22 | sys.path.insert(0, os.path.join(ROOT, "tools")) | 24 | sys.path.insert(0, os.path.join(ROOT, "tools")) |
| 23 | import mc_command # noqa: E402 | 25 | import mc_command # noqa: E402 |
| 24 | sys.path.insert(0, SHADER_DIR) | 26 | sys.path.insert(0, SHADER_DIR) |
| 27 | from build import CLIP_CASES, clip_container, shader_source | ||
| 28 | from check import Skip, clip_test, fmt_1010102_test | ||
| 25 | from compute_fixture import compute_header | 29 | from compute_fixture import compute_header |
| 26 | from check import SAMPLER_CASES, Skip, mesh_v5_test, sampler_test | 30 | from check import SAMPLER_CASES, sampler_test # ps_ssharp: the S#/T# mip fields (vk_sampler_test) |
| 31 | from check import (CMPX_CLASS_WORDS, CVT_F32_SAT_CASES, GRADIENT_TESTS, TEST_PROGRAMS, TEXTURE_MIP_DEPENDENCIES, | ||
| 32 | TEXTURE_MIP_TEST, GATHER_LOD_TEST, MIP_TEST_PASSES, GATHER_WRAP, USER_SGPRS_ENV, USER_SGPRS_WORDS, Skip, mesh_v5_test, not_found_message, | ||
| 33 | pick_build_dir, start_failure, texture_gradient_a16_test, texture_mip_test) | ||
| 34 | from check import TEXOFF_ARGS, texoff_problem # ps_texoff's expected words and arguments live in check.py | ||
| 35 | from check import TEXOFF_FALLBACK, texoff_env # LEONIDA_TEXOFF_FALLBACK=1: texel offsets without maintenance8 | ||
| 36 | from check import gpu_test_timeout, timed_out # per-program time limit (LEONIDA_GPU_TEST_TIMEOUT) | ||
| 37 | from check import WAVE32_LANE_DUMPS, WAVE32_LANE_ENV, narrow_subgroup_skip, wave32_lane_skip # as in check.py | ||
| 27 | 38 | ||
| 28 | 39 | ||
| 29 | def make_dxbc(chunks: list[tuple[bytes, bytes]]) -> bytes: | 40 | def make_dxbc(chunks: list[tuple[bytes, bytes]]) -> bytes: |
| @@ -79,6 +90,8 @@ def assemble_to_s(llvm_mc: str, asm_path: str, s_path: str, name: str) -> None: | |||
| 79 | if m: | 90 | if m: |
| 80 | cmd.append(f"-mattr={m.group(1)}") | 91 | cmd.append(f"-mattr={m.group(1)}") |
| 81 | break | 92 | break |
| 93 | if name in CLIP_CASES: | ||
| 94 | cmd.append(f"-defsym=PARAM_SLOT={CLIP_CASES[name]}") | ||
| 82 | cmd.append("-show-encoding") | 95 | cmd.append("-show-encoding") |
| 83 | p = subprocess.run( | 96 | p = subprocess.run( |
| 84 | cmd, | 97 | cmd, |
| @@ -215,11 +228,67 @@ def unsupported_skip(msg: str) -> str: | |||
| 215 | return f"SKIP ({m.group(0) if m else 'unsupported device'})" | 228 | return f"SKIP ({m.group(0) if m else 'unsupported device'})" |
| 216 | 229 | ||
| 217 | 230 | ||
| 218 | def run_cmd(cmd: list[str], env: dict | None = None) -> tuple[int, str]: | 231 | def run_cmd(cmd: list[str], env: dict | None = None, gpu: bool = True) -> tuple[int, str]: |
| 219 | p = subprocess.run(cmd, capture_output=True, text=True, env=env) | 232 | # A hung GPU test program fails its test instead of stalling the suite (check.py, LEONIDA_GPU_TEST_TIMEOUT). |
| 233 | # gpu=False (the translator over the whole suite) runs without a limit. | ||
| 234 | limit = gpu_test_timeout() if gpu else None | ||
| 235 | try: | ||
| 236 | p = subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=limit) | ||
| 237 | except subprocess.TimeoutExpired: | ||
| 238 | return 1, timed_out(cmd[0], limit) | ||
| 239 | except OSError as e: # e.g. Smart App Control blocked a fresh build: fail this test, keep running the others | ||
| 240 | return 1, start_failure(cmd[0], e) | ||
| 220 | return p.returncode, (p.stdout + "\n" + p.stderr).strip() | 241 | return p.returncode, (p.stdout + "\n" + p.stderr).strip() |
| 221 | 242 | ||
| 222 | 243 | ||
| 244 | def bary_fallback() -> bool: | ||
| 245 | """LEONIDA_BARY_FALLBACK=1: pixel shaders that read raw barycentrics are translated with --bary-fallback and drawn | ||
| 246 | through their pass-through geometry shader (tools/bary_fallback_gs.py), so they run on a device without | ||
| 247 | VK_KHR_fragment_shader_barycentric (NVIDIA Pascal, for one).""" | ||
| 248 | return (os.environ.get("LEONIDA_BARY_FALLBACK") or "").strip().lower() in ("1", "true", "yes", "on") | ||
| 249 | |||
| 250 | |||
| 251 | def w64_emulated() -> bool: | ||
| 252 | # Wave64 emulation on: the suite runs every wave64 check without asking for a 64-wide | ||
| 253 | # subgroup, matching check.py (W64_EMULATED). Accepts "1"/"true"/"yes"/"on" and tolerates | ||
| 254 | # the trailing space cmd.exe's `set VAR=1 &` leaves in the value. | ||
| 255 | return (os.environ.get("LEONIDA_W64_EMULATE") or "").strip().lower() in ("1", "true", "yes", "on") | ||
| 256 | def wavemask_check(vk_compute: str, spv: str, env: dict | None, emulated: bool) -> tuple[bool | None, str]: | ||
| 257 | """cs_wavemask, as in check.py: (passed, detail), passed None for a skip. The native build needs a 64-wide | ||
| 258 | subgroup and skips where the device has none; with LEONIDA_W64_EMULATE=1 it was translated with | ||
| 259 | --wave64-emulate and runs on any subgroup size, so it asks for none.""" | ||
| 260 | cmd = [vk_compute, spv, "1", "wavemask"] + ([] if emulated else ["--require-wave64"]) | ||
| 261 | rc, msg = run_cmd(cmd, env=env) | ||
| 262 | if not emulated and rc == 77: | ||
| 263 | return None, "SKIP (no 64-wide compute subgroup on this device)" | ||
| 264 | if not emulated and rc == 0 and "compute subgroup size: 64" not in msg.splitlines(): | ||
| 265 | return False, "64-wide subgroup was not confirmed (rebuild vk_compute_test)" | ||
| 266 | return rc == 0, msg.splitlines()[-1] if msg else "" | ||
| 267 | def dump_words(msg: str) -> list[int] | None: | ||
| 268 | """The eight words of vk_compute_test's "out[0..7] = ..." line, or None unless it is eight decimal words (as in | ||
| 269 | check.py): trailing text, a missing word or a non-number is a malformed dump, not a result.""" | ||
| 270 | m = re.search(r"^out\[0\.\.7\] = ((?:[0-9]+ ){7}[0-9]+)$", msg, re.MULTILINE) | ||
| 271 | return [int(x) for x in m.group(1).split()] if m else None | ||
| 272 | |||
| 273 | |||
| 274 | def judge_cs_dump(rc: int, msg: str, want: list[int], *, wave64: bool, partial: bool, emulated: bool, | ||
| 275 | hexwords: bool = False) -> tuple[bool | None, str]: | ||
| 276 | """Judge one vk_compute_test "dump" run: (True, words), (False, why), or (None, why) when the device can't run it. | ||
| 277 | wave64: it was run with --require-wave64, so exit 77 is a skip and the 64-wide confirmation must be printed. | ||
| 278 | partial: a group smaller than a wave, run at subgroup size 64 without full subgroups; skipped when the device | ||
| 279 | reports no subgroup size of 64. emulated: translated with --wave64-emulate, runs on any subgroup size.""" | ||
| 280 | no64 = partial and not emulated and not any(int(x) >= 64 for x in re.findall(r"subgroup \d+\.\.(\d+)", msg)) | ||
| 281 | if (wave64 and rc == 77) or (no64 and rc == 0): | ||
| 282 | return None, "SKIP (no 64-wide compute subgroup on this device)" | ||
| 283 | if rc == 0 and wave64 and "compute subgroup size: 64" not in msg.splitlines(): | ||
| 284 | return False, "64-wide subgroup was not confirmed (rebuild vk_compute_test)" | ||
| 285 | words = dump_words(msg) | ||
| 286 | if rc != 0 or words is None: | ||
| 287 | return False, msg | ||
| 288 | vals = words[:len(want)] | ||
| 289 | return vals == want, " ".join((hex if hexwords else str)(x) for x in vals) | ||
| 290 | |||
| 291 | |||
| 223 | def check_pixel_const(raw_path: str, want: tuple[int, int, int, int]) -> tuple[bool, str]: | 292 | def check_pixel_const(raw_path: str, want: tuple[int, int, int, int]) -> tuple[bool, str]: |
| 224 | px = read_raw_u32(raw_path) | 293 | px = read_raw_u32(raw_path) |
| 225 | if len(px) != 64 * 64: | 294 | if len(px) != 64 * 64: |
| @@ -231,8 +300,17 @@ def check_pixel_const(raw_path: str, want: tuple[int, int, int, int]) -> tuple[b | |||
| 231 | return True, "4096/4096 pixels exact" | 300 | return True, "4096/4096 pixels exact" |
| 232 | 301 | ||
| 233 | 302 | ||
| 303 | def frame_problem(px) -> str: | ||
| 304 | """Why a 64x64 frame can't be judged: a short frame or a NaN passes every tolerance test (check.py rejects both).""" | ||
| 305 | if len(px) != 64 * 64: | ||
| 306 | return f"expected 4096 pixels, got {len(px)}" | ||
| 307 | return "" if all(math.isfinite(v) for p in px for v in p) else "non-finite values in the frame" | ||
| 308 | |||
| 309 | |||
| 234 | def check_bary(raw_path: str) -> tuple[bool, str]: | 310 | def check_bary(raw_path: str) -> tuple[bool, str]: |
| 235 | px = read_raw_rgba32f(raw_path) | 311 | px = read_raw_rgba32f(raw_path) |
| 312 | if problem := frame_problem(px): | ||
| 313 | return False, problem | ||
| 236 | bad = 0 | 314 | bad = 0 |
| 237 | first = "" | 315 | first = "" |
| 238 | for i, (ax, ay, bi, bj) in enumerate(px): | 316 | for i, (ax, ay, bi, bj) in enumerate(px): |
| @@ -261,9 +339,15 @@ def check_bitmask_perm(raw_path: str) -> tuple[bool, str]: | |||
| 261 | return (bad == 0 and judged > 0), (first if bad else f"{judged}/{judged} pixels in lanes 0-31 exact") | 339 | return (bad == 0 and judged > 0), (first if bad else f"{judged}/{judged} pixels in lanes 0-31 exact") |
| 262 | 340 | ||
| 263 | 341 | ||
| 264 | # Test shaders that need memory or push constants only the semantic-test interpreter sets up (tests/semantic). | 342 | # Pixel shaders that read memory: vk_harness puts this V# in s[0:3] and seeds the heap it points at, as |
| 265 | # On the GPU harness they would read an unset descriptor; ps_vcc_x2 loses the device that way. | 343 | # tests/semantic/test_value_semantics.py does for the interpreter (same table as check.py). |
| 266 | INTERPRETER_ONLY = {"ps_vcc_x2": "needs the seeded V# memory of tests/semantic; checked there"} | 344 | PIXEL_ENV = {"ps_vcc_x2": {"VKH_SGPRS": "0x1000,0,16,0", "VKH_HEAP": "0x1000=0x11223344,0x1004=0x55667788"}, |
| 345 | # float NaN / fract rows measured on RDNA2 hardware (see the .asm headers) | ||
| 346 | "ps_fnan_med3": {"VKH_SGPRS": "0x1000,0,32,0", | ||
| 347 | "VKH_HEAP": "0x1000=0x7fc10001,0x1004=0x40e00000,0x1008=0x40a00000," | ||
| 348 | "0x100c=0x7fc10001,0x1010=0x40600000,0x1014=0xc0200000"}, | ||
| 349 | "ps_fnan_fract": {"VKH_SGPRS": "0x1000,0,16,0", | ||
| 350 | "VKH_HEAP": "0x1000=0xaedbe6ff,0x1004=0x00008800,0x1008=0x7fc10001,0x100c=0xc0200000"}} | ||
| 267 | 351 | ||
| 268 | 352 | ||
| 269 | def check_flat(raw_path: str) -> tuple[bool, str]: | 353 | def check_flat(raw_path: str) -> tuple[bool, str]: |
| @@ -278,14 +362,31 @@ def check_flat(raw_path: str) -> tuple[bool, str]: | |||
| 278 | f"{wrong} pixels without the first vertex's value, uv off by {err:.3g}") | 362 | f"{wrong} pixels without the first vertex's value, uv off by {err:.3g}") |
| 279 | 363 | ||
| 280 | 364 | ||
| 365 | def check_wqm(raw_path: str) -> tuple[bool, str]: | ||
| 366 | """ps_wqm.asm: per pixel (wqm, own, wqm, own); wqm iff x%4 < 2 and y%4 >= 2, own iff x%4 == 1 and y%4 == 2.""" | ||
| 367 | px = read_raw_u32(raw_path) | ||
| 368 | if problem := frame_problem(px): | ||
| 369 | return False, problem | ||
| 370 | w = int(len(px) ** 0.5) | ||
| 371 | wrong = sum(tuple(p) != (a, b, a, b) | ||
| 372 | for i, p in enumerate(px) | ||
| 373 | for a, b in [(int(i % w % 4 < 2 and i // w % 4 >= 2), int(i % w % 4 == 1 and i // w % 4 == 2))]) | ||
| 374 | return wrong == 0, "whole-quad mask exact on every pixel" if not wrong else f"{wrong} of {len(px)} pixels differ" | ||
| 375 | |||
| 376 | |||
| 281 | def check_uniform_branch(raw_path: str) -> tuple[bool, str]: | 377 | def check_uniform_branch(raw_path: str) -> tuple[bool, str]: |
| 282 | px = read_raw_rgba32f(raw_path) | 378 | px = read_raw_rgba32f(raw_path) |
| 283 | u32 = read_raw_u32(raw_path) | 379 | u32 = read_raw_u32(raw_path) |
| 380 | """ps_uniform_branch / ps_scc_mask32: s5 = 8 wherever the lane's own bit is set; a lane with bit 0 gets 8 when | ||
| 381 | another lane of its wave has the bit (the wave-wide vote), else 7. All three kinds must occur, as in check.py: | ||
| 382 | without a (8, bit 0) pixel the vote is not shown, and a translator that decides per lane would pass.""" | ||
| 284 | bad = 0 | 383 | bad = 0 |
| 285 | n8 = 0 | 384 | n8 = 0 |
| 286 | n7 = 0 | 385 | n7 = 0 |
| 386 | n80 = 0 | ||
| 287 | first = "" | 387 | first = "" |
| 288 | for i, ((_, _, bary_i, _), (s5, bit, _, _)) in enumerate(zip(px, u32)): | 388 | for i, ((_, _, bary_i, _), (s5, bit, _, _)) in enumerate(zip(px, u32)): |
| 389 | n80 += s5 == 8 and bit == 0 | ||
| 289 | if bit == 1: | 390 | if bit == 1: |
| 290 | if bary_i <= 0.27 or s5 != 8: | 391 | if bary_i <= 0.27 or s5 != 8: |
| 291 | if not bad: | 392 | if not bad: |
| @@ -304,11 +405,18 @@ def check_uniform_branch(raw_path: str) -> tuple[bool, str]: | |||
| 304 | n8 += 1 | 405 | n8 += 1 |
| 305 | elif s5 == 7: | 406 | elif s5 == 7: |
| 306 | n7 += 1 | 407 | n7 += 1 |
| 307 | return (bad == 0 and n8 > 0 and n7 > 0), (first if bad else f"s5==8: {n8}, s5==7: {n7} (4096 px)") | 408 | if bad: |
| 409 | return False, first | ||
| 410 | detail = f"s5==8: {n8} ({n80} of them with bit 0), s5==7: {n7} ({len(u32)} px)" | ||
| 411 | if not n80: | ||
| 412 | return False, "no bit=0 pixel got s5=8: the branch was decided per lane, not by the wave; " + detail | ||
| 413 | return (n8 - n80 > 0 and n7 > 0), detail | ||
| 308 | 414 | ||
| 309 | 415 | ||
| 310 | def check_grad(raw_path: str, want_b: float, want_a: float) -> tuple[bool, str]: | 416 | def check_grad(raw_path: str, want_b: float, want_a: float) -> tuple[bool, str]: |
| 311 | px = read_raw_rgba32f(raw_path) | 417 | px = read_raw_rgba32f(raw_path) |
| 418 | if problem := frame_problem(px): | ||
| 419 | return False, problem | ||
| 312 | bad = 0 | 420 | bad = 0 |
| 313 | first = "" | 421 | first = "" |
| 314 | for i, (r, g, b, a) in enumerate(px): | 422 | for i, (r, g, b, a) in enumerate(px): |
| @@ -352,23 +460,83 @@ def check_clip_half(raw_path: str, want_b: float, want_a: float) -> tuple[bool, | |||
| 352 | return ok, detail | 460 | return ok, detail |
| 353 | 461 | ||
| 354 | 462 | ||
| 463 | # Shaders a selected test draws with, built even when the filter leaves them out (#192). | ||
| 464 | DRAWN_WITH = {GATHER_LOD_TEST: "vs_ids.asm", "ps_flat": "vs_ids.asm", "ps_texture_sample": "vs_ids.asm", "ps_cube_sample": "vs_ids.asm", | ||
| 465 | "ps_texture_sample_d16": "vs_ids.asm", "ps_sample_c_lz": "vs_ids.asm", "ps_sample_c_lz_a16": "vs_ids.asm", | ||
| 466 | "ps_gather_wrap": "vs_ids.asm", "ps_ssharp": "vs_ids.asm", | ||
| 467 | **{name: "vs_ids.asm" for name in GRADIENT_TESTS}, "vs_clip": "ps_ops.asm"} | ||
| 468 | |||
| 469 | |||
| 470 | def with_draw_shaders(asm_files: list[str]) -> list[str]: | ||
| 471 | build = list(asm_files) | ||
| 472 | for f in asm_files: | ||
| 473 | extra = DRAWN_WITH.get(shader_source(os.path.splitext(f)[0])) | ||
| 474 | if extra and extra not in build: | ||
| 475 | build.append(extra) | ||
| 476 | if TEXTURE_MIP_TEST + ".asm" in asm_files: | ||
| 477 | for name in TEXTURE_MIP_DEPENDENCIES: | ||
| 478 | if name + ".asm" not in build: | ||
| 479 | build.append(name + ".asm") | ||
| 480 | return build | ||
| 481 | |||
| 482 | |||
| 483 | REQUIRED_TEST_PROGRAMS = ("vk_compute_test", "vk_store_test", "vk_harness") | ||
| 484 | BUILD_CONFIGS = ("RelWithDebInfo", "Release") | ||
| 485 | |||
| 486 | |||
| 487 | def find_test_programs(build: str, ext: str) -> str | None: | ||
| 488 | """Return the directory containing all required GPU test programs. | ||
| 489 | |||
| 490 | Single-configuration generators (Ninja, Makefiles) put executables directly | ||
| 491 | in the build directory. Visual Studio and other multi-configuration | ||
| 492 | generators put them in a configuration subdirectory. | ||
| 493 | """ | ||
| 494 | candidates = [build, *(os.path.join(build, config) for config in BUILD_CONFIGS)] | ||
| 495 | for directory in candidates: | ||
| 496 | if all(os.path.isfile(os.path.join(directory, name + ext)) for name in REQUIRED_TEST_PROGRAMS): | ||
| 497 | return directory | ||
| 498 | return None | ||
| 499 | |||
| 500 | |||
| 355 | def main() -> int: | 501 | def main() -> int: |
| 356 | ap = argparse.ArgumentParser() | 502 | ap = argparse.ArgumentParser() |
| 357 | ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc"), | 503 | ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc"), |
| 358 | help="llvm-mc path, or a whole command such as 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc'") | 504 | help="llvm-mc path, or a whole command such as 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc'") |
| 359 | ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build")) | 505 | ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"), |
| 506 | help="CMake build folder; with the Visual Studio generator the RelWithDebInfo/Release/... " | ||
| 507 | "subfolder that has the test programs is found by itself") | ||
| 360 | ap.add_argument("--work", default=None) | 508 | ap.add_argument("--work", default=None) |
| 361 | ap.add_argument("--filter", default="") | 509 | ap.add_argument("--filter", default="") |
| 362 | a = ap.parse_args() | 510 | a = ap.parse_args() |
| 511 | # Some test programs run with their working directory in <work>/spirv (vk_texture_test), so a relative path | ||
| 512 | # given here would point somewhere else for them. | ||
| 513 | a.build = os.path.abspath(a.build) | ||
| 514 | if a.work: | ||
| 515 | a.work = os.path.abspath(a.work) | ||
| 363 | 516 | ||
| 364 | ext = ".exe" if os.name == "nt" else "" | 517 | ext = ".exe" if os.name == "nt" else "" |
| 365 | missing = [t + ext for t in ("vk_compute_test", "vk_store_test", "vk_harness") | 518 | required = tuple(t + ext for t in TEST_PROGRAMS) |
| 366 | if not os.path.isfile(os.path.join(a.build, t + ext))] | 519 | a.build = pick_build_dir(a.build, required) |
| 520 | missing = [t for t in required if not os.path.isfile(os.path.join(a.build, t))] | ||
| 367 | if missing: | 521 | if missing: |
| 368 | sys.exit(f"Test programs not found in {os.path.abspath(a.build)}: {', '.join(missing)}\n" | 522 | sys.exit(not_found_message(a.build, missing)) |
| 523 | requested_build = a.build | ||
| 524 | resolved_build = find_test_programs(requested_build, ext) | ||
| 525 | if resolved_build is None: | ||
| 526 | searched = [requested_build, *(os.path.join(requested_build, config) for config in BUILD_CONFIGS)] | ||
| 527 | details = [] | ||
| 528 | for directory in searched: | ||
| 529 | missing = [name + ext for name in REQUIRED_TEST_PROGRAMS | ||
| 530 | if not os.path.isfile(os.path.join(directory, name + ext))] | ||
| 531 | details.append(f" {directory}: {', '.join(missing)}") | ||
| 532 | sys.exit("Required GPU test programs were not found together in one build directory.\n" | ||
| 533 | "Missing files by searched directory:\n" + "\n".join(details) + "\n" | ||
| 369 | "Build them with cmake -S runtime -B runtime/build, then cmake --build runtime/build.\n" | 534 | "Build them with cmake -S runtime -B runtime/build, then cmake --build runtime/build.\n" |
| 535 | "For Visual Studio, use: cmake --build <build-dir> --config RelWithDebInfo " | ||
| 536 | "--target vk_compute_test vk_store_test vk_harness.\n" | ||
| 370 | "CMake only builds them when it finds Vulkan. If it printed \"Vulkan SDK not found\", install the " | 537 | "CMake only builds them when it finds Vulkan. If it printed \"Vulkan SDK not found\", install the " |
| 371 | "Vulkan headers (vulkan-headers on Arch) and configure again.") | 538 | "Vulkan headers (vulkan-headers on Arch) and configure again.") |
| 539 | a.build = resolved_build | ||
| 372 | 540 | ||
| 373 | work = a.work or tempfile.mkdtemp(prefix="leonida_gpu_tests_") | 541 | work = a.work or tempfile.mkdtemp(prefix="leonida_gpu_tests_") |
| 374 | try: | 542 | try: |
| @@ -379,6 +547,14 @@ def main() -> int: | |||
| 379 | 547 | ||
| 380 | 548 | ||
| 381 | def run_suite(a, work: str) -> int: | 549 | def run_suite(a, work: str) -> int: |
| 550 | asm_files = sorted({f for f in os.listdir(SHADER_DIR) if f.endswith(".asm")} | {n + ".asm" for n in CLIP_CASES}) | ||
| 551 | if a.filter: | ||
| 552 | asm_files = [f for f in asm_files if a.filter in f] | ||
| 553 | if not asm_files: | ||
| 554 | print(f"error: --filter {a.filter!r} matched no GPU test cases", file=sys.stderr) | ||
| 555 | return 2 | ||
| 556 | build_files = with_draw_shaders(asm_files) | ||
| 557 | |||
| 382 | fssm_dir = os.path.join(work, "fssm") | 558 | fssm_dir = os.path.join(work, "fssm") |
| 383 | disasm_dir = os.path.join(work, "disasm") | 559 | disasm_dir = os.path.join(work, "disasm") |
| 384 | spirv_dir = os.path.join(work, "spirv") | 560 | spirv_dir = os.path.join(work, "spirv") |
| @@ -386,23 +562,18 @@ def run_suite(a, work: str) -> int: | |||
| 386 | for d in (fssm_dir, disasm_dir, spirv_dir, raw_dir): | 562 | for d in (fssm_dir, disasm_dir, spirv_dir, raw_dir): |
| 387 | os.makedirs(d, exist_ok=True) | 563 | os.makedirs(d, exist_ok=True) |
| 388 | 564 | ||
| 389 | asm_files = sorted(f for f in os.listdir(SHADER_DIR) if f.endswith(".asm")) | ||
| 390 | if a.filter: | ||
| 391 | asm_files = [f for f in asm_files if a.filter in f] | ||
| 392 | # Shaders a selected test draws with are built even when the filter leaves them out (#192): ps_flat and ps_ssharp use vs_ids. | ||
| 393 | build_files = list(asm_files) | ||
| 394 | if any(f.startswith(("ps_flat", "ps_ssharp")) for f in asm_files) and "vs_ids.asm" not in build_files: | ||
| 395 | build_files.append("vs_ids.asm") | ||
| 396 | |||
| 397 | # 1. Create synthetic DXBC / FSSM metadata + assemble .asm -> .s | 565 | # 1. Create synthetic DXBC / FSSM metadata + assemble .asm -> .s |
| 566 | disasm_files = [] | ||
| 398 | for fname in build_files: | 567 | for fname in build_files: |
| 399 | name = os.path.splitext(fname)[0] | 568 | name = os.path.splitext(fname)[0] |
| 400 | if name == "gs_tri": | 569 | if name in CLIP_CASES and name != "vs_clip_undeclared": |
| 570 | dxbc = clip_container() | ||
| 571 | elif name == "gs_tri": | ||
| 401 | dxbc = make_dxbc([ | 572 | dxbc = make_dxbc([ |
| 402 | (b"ISG1", make_sig_chunk([(1, 3, 0, 0xF, 0xF), (0, 3, 1, 0xF, 0xF)])), | 573 | (b"ISG1", make_sig_chunk([(1, 3, 0, 0xF, 0xF), (0, 3, 1, 0xF, 0xF)])), |
| 403 | (b"OSG1", make_sig_chunk([(1, 3, 0, 0xF, 0xF), (0, 3, 1, 0xF, 0xF)])), | 574 | (b"OSG1", make_sig_chunk([(1, 3, 0, 0xF, 0xF), (0, 3, 1, 0xF, 0xF)])), |
| 404 | ]) | 575 | ]) |
| 405 | elif name in ("ms_tri", "ms_w64x_ballot"): | 576 | elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3"): |
| 406 | dxbc = make_dxbc([(b"PSV0", make_ms_psv0(128, 64, 64, 2))]) | 577 | dxbc = make_dxbc([(b"PSV0", make_ms_psv0(128, 64, 64, 2))]) |
| 407 | elif name == "ms_v5_workgroup": | 578 | elif name == "ms_v5_workgroup": |
| 408 | dxbc = make_dxbc([(b"PSV0", make_ms_psv0(32, 3, 1, group_shared=128))]) | 579 | dxbc = make_dxbc([(b"PSV0", make_ms_psv0(32, 3, 1, group_shared=128))]) |
| @@ -419,19 +590,33 @@ def run_suite(a, work: str) -> int: | |||
| 419 | if name.startswith("cs_"): | 590 | if name.startswith("cs_"): |
| 420 | with open(os.path.join(fssm_dir, f"{name}.fssm"), "wb") as f: | 591 | with open(os.path.join(fssm_dir, f"{name}.fssm"), "wb") as f: |
| 421 | f.write(compute_header(os.path.join(SHADER_DIR, fname))) | 592 | f.write(compute_header(os.path.join(SHADER_DIR, fname))) |
| 422 | assemble_to_s(a.llvm_mc, os.path.join(SHADER_DIR, fname), os.path.join(disasm_dir, f"{name}.s"), name) | 593 | fname = shader_source(name) + ".asm" |
| 594 | disasm_path = os.path.join(disasm_dir, f"{name}.s") | ||
| 595 | assemble_to_s(a.llvm_mc, os.path.join(SHADER_DIR, fname), disasm_path, name) | ||
| 596 | disasm_files.append(disasm_path) | ||
| 423 | # A failed translation must not run an old binary left in a reused --work directory. | 597 | # A failed translation must not run an old binary left in a reused --work directory. |
| 424 | Path(spirv_dir, f"{name}.spv").unlink(missing_ok=True) | 598 | Path(spirv_dir, f"{name}.spv").unlink(missing_ok=True) |
| 425 | 599 | ||
| 426 | # 2. Translate all .s -> .spv | 600 | # 2. Translate this run's inputs only. The translator looks for metadata one level above the input directory. |
| 427 | cmd = [sys.executable, "-I", TRANSLATOR, disasm_dir, "--out", spirv_dir] | 601 | with tempfile.TemporaryDirectory(prefix="disasm-", dir=work) as selected_disasm: |
| 428 | if os.environ.get("LEONIDA_W64_EMULATE") == "1": # wave64 compute/mesh exact on any subgroup size | 602 | for path in disasm_files: |
| 429 | cmd.append("--wave64-emulate") | 603 | shutil.copyfile(path, os.path.join(selected_disasm, os.path.basename(path))) |
| 430 | rc, out = run_cmd(cmd) | 604 | cmd = [sys.executable, "-I", TRANSLATOR, selected_disasm, "--out", spirv_dir] |
| 605 | if w64_emulated(): # wave64 compute/mesh exact on any subgroup size | ||
| 606 | cmd.append("--wave64-emulate") | ||
| 607 | if bary_fallback(): # raw barycentrics from an interpolated input, fed by a pass-through GS | ||
| 608 | cmd.append("--bary-fallback") | ||
| 609 | if TEXOFF_FALLBACK: # image_sample*_o: offset folded into the coordinate, no VK_KHR_maintenance8 | ||
| 610 | cmd.append("--texel-offset-fallback") | ||
| 611 | rc, out = run_cmd(cmd, gpu=False) | ||
| 431 | print("=== rdna2spirv.py ===") | 612 | print("=== rdna2spirv.py ===") |
| 432 | print(out) | 613 | print(out) |
| 433 | if rc != 0: | 614 | if rc != 0: |
| 434 | return 1 | 615 | return 1 |
| 616 | if bary_fallback(): | ||
| 617 | import bary_fallback_gs | ||
| 618 | for gs in bary_fallback_gs.build_for_index(spirv_dir): | ||
| 619 | print("bary fallback GS:", os.path.basename(gs)) | ||
| 435 | 620 | ||
| 436 | # 3. Build helper SPIR-V shaders | 621 | # 3. Build helper SPIR-V shaders |
| 437 | vs_tri = os.path.join(spirv_dir, "vs_tri.spv") | 622 | vs_tri = os.path.join(spirv_dir, "vs_tri.spv") |
| @@ -455,9 +640,6 @@ def run_suite(a, work: str) -> int: | |||
| 455 | results: list[tuple[str, bool, str]] = [] | 640 | results: list[tuple[str, bool, str]] = [] |
| 456 | for fname in asm_files: | 641 | for fname in asm_files: |
| 457 | name = os.path.splitext(fname)[0] | 642 | name = os.path.splitext(fname)[0] |
| 458 | if name in INTERPRETER_ONLY: | ||
| 459 | results.append((name, None, "SKIP (" + INTERPRETER_ONLY[name] + ")")) | ||
| 460 | continue | ||
| 461 | spv = os.path.join(spirv_dir, f"{name}.spv") | 643 | spv = os.path.join(spirv_dir, f"{name}.spv") |
| 462 | if not os.path.isfile(spv): | 644 | if not os.path.isfile(spv): |
| 463 | results.append((name, False, "missing .spv (translation failed)")) | 645 | results.append((name, False, "missing .spv (translation failed)")) |
| @@ -466,7 +648,10 @@ def run_suite(a, work: str) -> int: | |||
| 466 | cs_env = dict(os.environ, VKC_SUBGROUP_SIZE=str(sg)) if sg else None | 648 | cs_env = dict(os.environ, VKC_SUBGROUP_SIZE=str(sg)) if sg else None |
| 467 | gfx_env = dict(os.environ, VKH_SUBGROUP_SIZE=str(sg)) if sg else None | 649 | gfx_env = dict(os.environ, VKH_SUBGROUP_SIZE=str(sg)) if sg else None |
| 468 | 650 | ||
| 469 | if name == "cs_workgroup_yz": | 651 | if name in CLIP_CASES: |
| 652 | detail = clip_test(a.build, spirv_dir, name) | ||
| 653 | results.append((name, None if isinstance(detail, Skip) else not detail, detail or "four pixel masks exact")) | ||
| 654 | elif name == "cs_workgroup_yz": | ||
| 470 | rc, msg = run_cmd([vk_compute, spv, "2x3x4", "workgroup_yz"], env=cs_env) | 655 | rc, msg = run_cmd([vk_compute, spv, "2x3x4", "workgroup_yz"], env=cs_env) |
| 471 | results.append((name, rc == 0 and "2x3x4 workgroup Y/Z: 0 mismatches" in msg.splitlines(), msg)) | 656 | results.append((name, rc == 0 and "2x3x4 workgroup Y/Z: 0 mismatches" in msg.splitlines(), msg)) |
| 472 | elif name == "cs_lds": | 657 | elif name == "cs_lds": |
| @@ -478,95 +663,213 @@ def run_suite(a, work: str) -> int: | |||
| 478 | elif name == "cs_bvh": | 663 | elif name == "cs_bvh": |
| 479 | rc, msg = run_cmd([vk_compute, spv, "1", "bvh"], env=cs_env) | 664 | rc, msg = run_cmd([vk_compute, spv, "1", "bvh"], env=cs_env) |
| 480 | results.append((name, rc == 0, msg.splitlines()[-1] if msg else "")) | 665 | results.append((name, rc == 0, msg.splitlines()[-1] if msg else "")) |
| 481 | elif name == "cs_bounds": | 666 | elif name in ("cs_bounds", "cs_smem_bounds", "cs_smem_stride_align", "cs_smem_sload_neg", "cs_buf_tail", "cs_oob_select", "cs_oob_tail", |
| 667 | "cs_cmpx_class_f32"): | ||
| 482 | # num_records bounds check (cs_bounds.asm): the out-of-bounds store is dropped and the out-of-bounds | 668 | # num_records bounds check (cs_bounds.asm): the out-of-bounds store is dropped and the out-of-bounds |
| 483 | # load reads 0, so thread 0's four output words are fixed. One thread, no wave64 requirement. | 669 | # load reads 0, so thread 0's four output words are fixed. One thread, no wave64 requirement. |
| 670 | # cs_cmpx_class_f32 is per-lane and needs no particular subgroup width either. | ||
| 671 | # The other four pin the SMEM and raw MUBUF rules measured on an RX 6800 (derivations in each .asm). | ||
| 484 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=cs_env) | 672 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=cs_env) |
| 485 | want = [0x12345678, 0x12345678, 0, 0xEEEEEEEE] | 673 | want = { |
| 486 | dump = next((ln for ln in msg.splitlines() if "out[0..7] =" in ln), "") | 674 | "cs_bounds": [0x12345678, 0x12345678, 0, 0xEEEEEEEE], |
| 487 | vals = [int(x) for x in dump.partition("=")[2].split()[:len(want)]] if dump else [] | 675 | "cs_smem_bounds": [0, 0x5EED0010, 0x5EED000C, 0, 0x5EED000C, 0x5EED0010, 0, 0], |
| 676 | "cs_smem_stride_align": [0x5EED0010, 0, 0, 0x5EED0000, 0x5EED0000, 0x5EED0000, 0x5EED0000, | ||
| 677 | 0x5EED0004], | ||
| 678 | # never run with a translator that zero-extends the s_load immediate (reads 4 GiB past the heap) | ||
| 679 | "cs_smem_sload_neg": [0x5EED0004, 0x5EED0000, 0x5EED0004, 0x5EED0004, 0x5EED0008, 0x5EED000C, | ||
| 680 | 0xEEEEEEEE, 0xEEEEEEEE], | ||
| 681 | "cs_buf_tail": [0, 0x5EED000C, 0x5EED0008, 0x5EED000C, 0, 0, 0x5EED0010, 0], | ||
| 682 | "cs_oob_select": [0x5EED000C, 0, 0x5EED0014, 0, 0x5EED0018, 0xEEEEEEEE, 0, 0], | ||
| 683 | "cs_oob_tail": [0, 0, 0x5EED0010, 0, 0xBEEF0000, 0xEEEEEEEE, 0, 0x5EED0010], | ||
| 684 | "cs_cmpx_class_f32": CMPX_CLASS_WORDS, | ||
| 685 | }[name] | ||
| 686 | words = dump_words(msg) | ||
| 687 | vals = words[:len(want)] if words else [] | ||
| 488 | results.append((name, rc == 0 and vals == want, | 688 | results.append((name, rc == 0 and vals == want, |
| 489 | " ".join(hex(x) for x in vals) if vals else msg)) | 689 | " ".join(hex(x) for x in vals) if vals else msg)) |
| 690 | elif name == "cs_fmt_1010102": | ||
| 691 | problem = fmt_1010102_test(a.build, spirv_dir, cs_env) | ||
| 692 | results.append((name, not problem, problem or "64/64 dumped words exact")) | ||
| 693 | elif name == "cs_global_neg_offset": | ||
| 694 | # Negative global_load/global_store offsets (cs_global_neg_offset.asm): 40 groups give a 0x2800-byte | ||
| 695 | # heap holding both the right addresses and the 4096-lower ones. One thread, no wave64 requirement. | ||
| 696 | rc, msg = run_cmd([vk_compute, spv, "40", "dump"], env=cs_env) | ||
| 697 | want = [0x5EED1FFC, 0x8BAD1800, 0x5EED1FF0, 0x5EED1FF4, 0x9E, 0xFFFF8BAD, 0x57023FFC, 0xEEEEEEEE] | ||
| 698 | ok, detail = judge_cs_dump(rc, msg, want, wave64=False, partial=False, emulated=False, hexwords=True) | ||
| 699 | results.append((name, ok, detail)) | ||
| 700 | elif name == "cs_user_sgprs": | ||
| 701 | # vk_compute_test seeds s4..s7 from VKC_SGPRS; the shader stores them back. | ||
| 702 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=dict(cs_env or os.environ, **USER_SGPRS_ENV)) | ||
| 703 | words = dump_words(msg) | ||
| 704 | vals = words[:len(USER_SGPRS_WORDS)] if words else [] | ||
| 705 | results.append((name, rc == 0 and vals == USER_SGPRS_WORDS, | ||
| 706 | " ".join(hex(x) for x in vals) if vals else msg)) | ||
| 707 | elif name == "cs_cvt_f32_sat": | ||
| 708 | # #300's saturating float -> int conversions: one dispatch per input word in s4 (VKC_SGPRS). | ||
| 709 | wrong = [] | ||
| 710 | for bits, unsigned, signed in CVT_F32_SAT_CASES: | ||
| 711 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"], | ||
| 712 | env=dict(cs_env or os.environ, VKC_SGPRS=f"{bits:#010x}")) | ||
| 713 | words = dump_words(msg) | ||
| 714 | if rc != 0 or not words or words[:2] != [unsigned, signed]: | ||
| 715 | got = " ".join(hex(x) for x in words[:2]) if words else msg.splitlines()[-1] if msg else "no output" | ||
| 716 | wrong.append(f"{bits:#010x} gave {got}, want {unsigned:#x} {signed:#x}") | ||
| 717 | n = len(CVT_F32_SAT_CASES) | ||
| 718 | results.append((name, not wrong, f"{n}/{n} inputs exact" if not wrong | ||
| 719 | else f"{len(wrong)}/{n} inputs wrong, first {wrong[0]}")) | ||
| 490 | elif name == "cs_wavemask": | 720 | elif name == "cs_wavemask": |
| 491 | # Whole-wave mask test, as in check.py: needs a 64-wide subgroup, skipped where the device has none. | 721 | # Whole-wave mask test, as in check.py: needs a 64-wide subgroup, skipped where the device has none. |
| 492 | # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size. | 722 | # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size. |
| 493 | emulated = os.environ.get("LEONIDA_W64_EMULATE") == "1" | 723 | results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated())) |
| 494 | args = [] if emulated else ["--require-wave64"] | 724 | elif name in ("cs_store", "cs_smem_soffset_imm", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", "cs_exec_const", "cs_w32_lds_u8_d16", "cs_wave64_ballot", "cs_wm_half_ops", "cs_wm_half_cmp", "cs_wm_bfm64", "cs_wm_scc_rfl", "cs_wqm_w64", "cs_wqm_w32", "cs_wqm_w64_half", |
| 495 | rc, msg = run_cmd([vk_compute, spv, "1", "wavemask", *args], env=cs_env) | 725 | |
| 496 | if not emulated and rc == 77: | ||
| 497 | results.append((name, None, "SKIP (no 64-wide compute subgroup on this device)")) | ||
| 498 | elif not emulated and rc == 0 and "compute subgroup size: 64" not in msg.splitlines(): | ||
| 499 | results.append((name, False, "64-wide subgroup was not confirmed (rebuild vk_compute_test)")) | ||
| 500 | else: | ||
| 501 | results.append((name, rc == 0, msg.splitlines()[-1] if msg else "")) | ||
| 502 | elif name in ("cs_store", "cs_smem_soffset_imm", "cs_wave64_ballot", "cs_wm_half_ops", "cs_wm_half_cmp", "cs_wm_bfm64", "cs_wm_scc_rfl", | ||
| 503 | "cs_w64_mask_detect", | 726 | "cs_w64_mask_detect", |
| 504 | "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_readfirstlane", "cs_w64x_bpermute", | 727 | "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_readfirstlane", "cs_w64x_bpermute", "cs_w64x_permute", |
| 505 | "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw", | 728 | "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw", |
| 506 | "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load"): | 729 | "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load", |
| 730 | "cs_w64x_mask_reuse", "cs_w64x_mask_reuse2", "cs_w64x_chain_barrier", "cs_barrier_divergent", | ||
| 731 | "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w32_partial_scmp", "cs_barrier_early_end", | ||
| 732 | "cs_barrier_loop"): | ||
| 507 | cs_dump_wants = { | 733 | cs_dump_wants = { |
| 508 | "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800], | 734 | "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800], |
| 509 | # base + soffset + imm (cs_smem_soffset_imm.asm); out[4..7] are seeds the shader leaves alone | 735 | # base + soffset + imm (cs_smem_soffset_imm.asm); out[4..7] are seeds the shader leaves alone |
| 510 | "cs_smem_soffset_imm": [0x5EED0024, 0x5EED0028, 0x5EED002C, 0x5EED0030, | 736 | "cs_smem_soffset_imm": [0x5EED0024, 0x5EED0028, 0x5EED002C, 0x5EED0030, |
| 511 | 0x5EED0010, 0x5EED0014, 0x5EED0018, 0x5EED001C], | 737 | 0x5EED0010, 0x5EED0014, 0x5EED0018, 0x5EED001C], |
| 738 | # SHADER-52: wave32 lane select & 31 (40 → 8) | ||
| 739 | "cs_w32_lane_wrap": [25, 16, 777, 777], | ||
| 740 | # v_movrelsd_2_b32: VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]] (cs_movrelsd_2.asm) | ||
| 741 | "cs_movrelsd_2": [11, 33, 33, 55, 1717, 77, 1515, 1717], | ||
| 742 | # SHADER-90: ds_permute_b32 (cs_w32_permute.asm): scatter, unwritten lane = 0, EXEC gates the write | ||
| 743 | "cs_w32_permute": [218, 29, 8, 211, 0, 15, 99, 15], | ||
| 744 | # SHADER-85: ds_read_u8/i8_d16[_hi] (cs_w32_lds_u8_d16.asm header) | ||
| 745 | "cs_w32_lds_u8_d16": [0xBEEF00FF, 0x00FF1234, 0xBEEFFF80, 0xFF801234, 0xBEEF007F, 0x007F1234, 0xBEEF0080, 0xFFFF1234], | ||
| 746 | # constant EXEC masks (cs_exec_const.asm): each lane takes its own bit of the constant | ||
| 747 | "cs_exec_const": [16, 8, 2, 16, 0, 16], | ||
| 512 | "cs_wave64_ballot": [32, 16, 24, 40, 8, 48], | 748 | "cs_wave64_ballot": [32, 16, 24, 40, 8, 48], |
| 513 | "cs_wm_half_ops": [32, 16, 16, 0, 16], | 749 | "cs_wm_half_ops": [32, 16, 16, 0, 16], |
| 514 | "cs_wm_half_cmp": [1, 0, 1, 1], | 750 | "cs_wm_half_cmp": [1, 0, 1, 1], |
| 515 | "cs_wm_bfm64": [16, 8, 8, 40], | 751 | "cs_wm_bfm64": [16, 8, 8, 40], |
| 516 | "cs_wm_scc_rfl": [55, 48], | 752 | "cs_wm_scc_rfl": [55, 48], |
| 517 | "cs_w64_mask_detect": [48], | 753 | "cs_w64_mask_detect": [48], |
| 754 | "cs_wqm_w64": [20, 4, 12, 8, 1, 0, 15728895, 20], # cs_wqm_w64.asm / cs_wqm_w32.asm headers | ||
| 755 | "cs_wqm_w32": [12, 1, 4, 0, 8, 15728880, 4, 32], | ||
| 756 | "cs_wqm_w64_half": [11, 14, 0, 1, 6, 8, 12, 2], | ||
| 518 | # cross-half tests (derivations in each .asm); need exact wave64 or its emulation | 757 | # cross-half tests (derivations in each .asm); need exact wave64 or its emulation |
| 519 | "cs_w64x_readlane": [121, 121, 16, 97, 16, 100, 100, 121], | 758 | "cs_w64x_readlane": [121, 121, 16, 97, 16, 100, 100, 121], |
| 520 | "cs_w64x_writelane": [4660, 77, 99, 2748, 0, 0, 4660, 99], | 759 | "cs_w64x_writelane": [4660, 77, 99, 2748, 0, 0, 4660, 99], |
| 521 | "cs_w64x_readfirstlane": [140, 140, 163, 132, 100, 105, 133, 48], | 760 | "cs_w64x_readfirstlane": [140, 140, 163, 132, 100, 105, 133, 48], |
| 522 | "cs_w64x_bpermute": [36, 316, 253, 218, 435, 225, 0, 442], | 761 | "cs_w64x_bpermute": [36, 316, 253, 218, 435, 225, 0, 442], |
| 762 | "cs_w64x_permute": [218, 442, 435, 239, 0, 99, 239, 232], # SHADER-90, cs_w64x_permute.asm | ||
| 523 | "cs_w64x_branch": [0, 0, 0, 0, 5, 5, 9, 9], | 763 | "cs_w64x_branch": [0, 0, 0, 0, 5, 5, 9, 9], |
| 764 | "cs_w64x_mask_reuse": [8, 40, 8, 40, 2, 20, 10, 64], | ||
| 765 | "cs_w64x_mask_reuse2": [10, 20, 8, 8, 5, 2, 132, 131], | ||
| 766 | "cs_w64x_chain_barrier": [564, 563, 500, 627], | ||
| 524 | "cs_w64x_ballot": [2053, 2061, 2069, 2077, 2085, 2093, 2101, 2109], | 767 | "cs_w64x_ballot": [2053, 2061, 2069, 2077, 2085, 2093, 2101, 2109], |
| 525 | "cs_w64x_wg128_branches": [121, 121, 343, 343, 14, 31, 19812, 22728], | 768 | "cs_w64x_wg128_branches": [121, 121, 343, 343, 14, 31, 19812, 22728], |
| 526 | "cs_w64x_lds_raw": [132, 137, 100, 108, 131, 101, 149, 118], | 769 | "cs_w64x_lds_raw": [132, 137, 100, 108, 131, 101, 149, 118], |
| 527 | "cs_w64x_lds_war": [1032, 1063, 1000, 1031, 2032, 2063, 2000, 2031], | 770 | "cs_w64x_lds_war": [1032, 1063, 1000, 1031, 2032, 2063, 2000, 2031], |
| 528 | "cs_w64x_partial": [40, 40, 528, 0, 0, 532, 539, 524820], | 771 | "cs_w64x_partial": [40, 40, 528, 0, 0, 532, 539, 524820], |
| 772 | "cs_w64x_partial_scmp": [0, 1, 0, 1, 1, 1, 1, 0], # s_cmp mask, -1 in a partial wave | ||
| 773 | "cs_w32_partial_scmp": [0, 1, 1, 0, 1, 1, 1, 1], # the same in a 20-thread wave32 | ||
| 529 | "cs_w64x_sbarrier": [605, 605, 686, 686, 3032, 3013, 3032, 3031], | 774 | "cs_w64x_sbarrier": [605, 605, 686, 686, 3032, 3013, 3032, 3031], |
| 530 | "cs_w64x_load_ballot_load": [43, 74, 75, 42, 42, 18, 41, 32], | 775 | "cs_w64x_load_ballot_load": [43, 74, 75, 42, 42, 18, 41, 32], |
| 776 | "cs_bpermute32": [0, 50, 162, 99, 36, 218, 183, 15], # wave32: needs 32 lanes | ||
| 777 | # SHADER-91: s_barrier sites in different wave-uniform branches meet (cs_barrier_divergent.asm) | ||
| 778 | "cs_barrier_divergent": [127, 126, 125, 124, 123, 122, 121, 120], | ||
| 779 | # SHADER-91: other waves end without s_barrier (cs_barrier_early_end.asm); a loop whose trip count | ||
| 780 | # differs per wave (cs_barrier_loop.asm) | ||
| 781 | "cs_barrier_early_end": [127, 126, 125, 124, 123, 122, 121, 120], | ||
| 782 | "cs_barrier_loop": [128, 96, 64, 32, 128, 96, 64, 0xEEEEEEEE], | ||
| 531 | } | 783 | } |
| 532 | want = cs_dump_wants[name] | 784 | want = cs_dump_wants[name] |
| 533 | # Every dump but cs_store and cs_smem_soffset_imm is a whole-wave (wave64) mask test: ask for a 64-wide subgroup and skip, as | 785 | # Every dump but cs_store / cs_smem_soffset_imm / cs_w32_lane_wrap / cs_movrelsd_2 / cs_w32_permute / |
| 534 | # check.py does, where the device has none (vk_compute_test exits 77) instead of reporting a failure. | 786 | # cs_w32_lds_u8_d16 and the wave32 cs_wqm_w32 / cs_bpermute32 is a whole-wave (wave64) mask test: |
| 535 | # With LEONIDA_W64_EMULATE=1 they were translated with --wave64-emulate and run on any subgroup size. | 787 | # ask for a 64-wide subgroup and skip, as check.py does, where the device has none (vk_compute_test |
| 536 | # cs_w64x_partial (a 40-thread group) can't have full subgroups: it asks for size 64 without them. | 788 | # exits 77) instead of reporting a failure. With LEONIDA_W64_EMULATE=1 they were translated with |
| 537 | emulated = os.environ.get("LEONIDA_W64_EMULATE") == "1" | 789 | # --wave64-emulate and run on any subgroup size. |
| 538 | partial = name == "cs_w64x_partial" | 790 | # cs_w64x_partial and cs_w64x_partial_scmp (40-thread groups) can't have full subgroups: they ask for |
| 539 | wave64 = name not in ("cs_store", "cs_smem_soffset_imm") and not emulated and not partial | 791 | # size 64 without them. |
| 792 | emulated = w64_emulated() | ||
| 793 | partial = name in ("cs_w64x_partial", "cs_w64x_partial_scmp") | ||
| 794 | wave64 = name not in ("cs_store", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", | ||
| 795 | "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", | ||
| 796 | "cs_w32_lds_u8_d16", "cs_bpermute32", "cs_w32_partial_scmp", | ||
| 797 | "cs_exec_const") and not emulated and not partial | ||
| 798 | |||
| 540 | if partial and not emulated: | 799 | if partial and not emulated: |
| 541 | cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="64") | 800 | cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="64") |
| 801 | if name in WAVE32_LANE_DUMPS: # 32 lanes even without index.json, as check.py requests (#774) | ||
| 802 | cs_env = dict(os.environ, **WAVE32_LANE_ENV) | ||
| 542 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"] + (["--require-wave64"] if wave64 else []), env=cs_env) | 803 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"] + (["--require-wave64"] if wave64 else []), env=cs_env) |
| 543 | dump_line = next((ln for ln in msg.splitlines() if "out[0..7] =" in ln), "") | 804 | skip = wave32_lane_skip(msg) if name in WAVE32_LANE_DUMPS else None |
| 544 | no64 = partial and not emulated and not any(int(x) >= 64 for x in re.findall(r"subgroup \d+\.\.(\d+)", msg)) | 805 | if skip: # e.g. Mesa llvmpipe's 8-wide subgroups: these 32-lane masks can't come out right |
| 545 | if (wave64 and rc == 77) or (no64 and rc == 0): | 806 | ok, detail = None, str(skip) |
| 546 | results.append((name, None, "SKIP (no 64-wide compute subgroup on this device)")) | ||
| 547 | elif rc == 0 and dump_line: | ||
| 548 | vals = [int(x) for x in dump_line.split("=")[1].split()[:len(want)]] | ||
| 549 | ok = vals == want | ||
| 550 | fmt = hex if name in ("cs_store", "cs_smem_soffset_imm") else str | ||
| 551 | results.append((name, ok, " ".join(fmt(x) for x in vals))) | ||
| 552 | else: | 807 | else: |
| 553 | results.append((name, False, msg)) | 808 | ok, detail = judge_cs_dump(rc, msg, want, wave64=wave64, partial=partial, emulated=emulated, |
| 809 | hexwords=name in ("cs_store", "cs_smem_soffset_imm", "cs_w32_lds_u8_d16")) | ||
| 810 | results.append((name, ok, detail)) | ||
| 554 | elif name == "cs_imgstore": | 811 | elif name == "cs_imgstore": |
| 555 | rc, msg = run_cmd([vk_store, spv]) | 812 | rc, msg = run_cmd([vk_store, spv]) |
| 556 | results.append((name, rc == 0, msg.splitlines()[-1] if msg else "")) | 813 | results.append((name, rc == 0, msg.splitlines()[-1] if msg else "")) |
| 557 | elif name == "cs_imgload": | 814 | elif name in ("cs_imgload", "cs_imgload_d16"): |
| 558 | rc, msg = run_cmd([vk_store, spv, "load"]) | 815 | rc, msg = run_cmd([vk_store, spv, "load"]) |
| 559 | results.append((name, rc == 0, msg.splitlines()[-1] if msg else "")) | 816 | results.append((name, rc == 0, msg.splitlines()[-1] if msg else "")) |
| 560 | elif name == "ps_texture_sample": | 817 | elif name in MIP_TEST_PASSES: |
| 561 | # #167's bindless texture test: vk_texture_test finds vs_ids.spv and this shader in its working directory. | 818 | problem = texture_mip_test(a.build, spirv_dir, name) |
| 819 | ok = None if isinstance(problem, Skip) else not problem | ||
| 820 | results.append((name, ok, problem or "two passes, 4096 RGBA32F pixels each exact; wrong mip and UV rejected")) | ||
| 821 | elif name in GRADIENT_TESTS: | ||
| 822 | problem = texture_gradient_a16_test(a.build, spirv_dir, name) | ||
| 823 | ok = None if isinstance(problem, Skip) else not problem | ||
| 824 | results.append((name, ok, problem or "4096 RGBA pixels matched")) | ||
| 825 | elif name in ("ps_texture_sample", "ps_cube_sample", "ps_texture_sample_d16", "ps_sample_c_lz", | ||
| 826 | "ps_sample_c_lz_a16"): | ||
| 827 | # Bindless texture tests: vk_texture_test finds vs_ids.spv and the shader in its working directory. | ||
| 828 | tool = os.path.join(a.build, "vk_texture_test" + ext) | ||
| 829 | raw = os.path.join(raw_dir, f"{name}.raw") | ||
| 830 | if name == "ps_texture_sample_d16": | ||
| 831 | cmd = [tool, os.path.join(spirv_dir, "vs_ids.spv"), spv, raw, "0", "0", "0", "0", "0"] | ||
| 832 | else: | ||
| 833 | mode = {"ps_cube_sample": ["cube"], "ps_sample_c_lz": ["dref"], | ||
| 834 | "ps_sample_c_lz_a16": ["dref_a16"]}.get(name, []) | ||
| 835 | cmd = [tool, *mode, raw] | ||
| 836 | try: | ||
| 837 | p = subprocess.run(cmd, capture_output=True, text=True, cwd=spirv_dir) | ||
| 838 | rc, msg = p.returncode, (p.stdout + "\n" + p.stderr).strip() | ||
| 839 | except FileNotFoundError: | ||
| 840 | rc, msg = 1, f"missing {tool}" | ||
| 841 | except OSError as e: | ||
| 842 | rc, msg = 1, start_failure(tool, e) | ||
| 843 | if rc == UNSUPPORTED: # e.g. fewer push constant bytes than the texture tests need | ||
| 844 | results.append((name, None, unsupported_skip(msg))) | ||
| 845 | elif name == "ps_texture_sample_d16" and rc == 0 and os.path.isfile(raw): | ||
| 846 | with open(raw, "rb") as f: | ||
| 847 | f.seek((32 * 64 + 32) * 16) | ||
| 848 | r, g, b, alpha = struct.unpack("<4f", f.read(16)) | ||
| 849 | exp_b = struct.unpack("<e", struct.pack("<e", 128.0 / 255.0))[0] | ||
| 850 | ok = abs(r - exp_b) <= 0.05 and abs(g - exp_b) <= 0.05 and abs(b - exp_b) == 0.0 and alpha == 1.0 | ||
| 851 | results.append((name, ok, f"center(32,32)=({r:.6f}, {g:.6f}, {b:.6f}, {alpha:.1f})")) | ||
| 852 | else: | ||
| 853 | results.append((name, rc == 0 and "PASSED" in msg, msg.splitlines()[-1] if msg else "")) | ||
| 854 | elif name == "ps_gather_wrap": | ||
| 855 | # SHADER-36: image_gather4_l_o under wrap/mirror/clamp/mirror-once S#s; every pixel holds GATHER_WRAP. | ||
| 562 | tool = os.path.join(a.build, "vk_texture_test" + ext) | 856 | tool = os.path.join(a.build, "vk_texture_test" + ext) |
| 563 | raw = os.path.join(raw_dir, f"{name}.raw") | 857 | raw = os.path.join(raw_dir, f"{name}.raw") |
| 564 | try: | 858 | try: |
| 565 | p = subprocess.run([tool, raw], capture_output=True, text=True, cwd=spirv_dir) | 859 | p = subprocess.run([tool, os.path.join(spirv_dir, "vs_ids.spv"), spv, raw, "0", "92", "c00000", |
| 860 | "14500000", "0"], capture_output=True, text=True, cwd=spirv_dir) | ||
| 566 | rc, msg = p.returncode, (p.stdout + "\n" + p.stderr).strip() | 861 | rc, msg = p.returncode, (p.stdout + "\n" + p.stderr).strip() |
| 567 | except FileNotFoundError: | 862 | except FileNotFoundError: |
| 568 | rc, msg = 1, f"missing {tool}" | 863 | rc, msg = 1, f"missing {tool}" |
| 569 | results.append((name, rc == 0 and "PASSED" in msg, msg.splitlines()[-1] if msg else "")) | 864 | bad = 4096 |
| 865 | if rc == 0 and os.path.isfile(raw): | ||
| 866 | data = Path(raw).read_bytes() | ||
| 867 | bad = 4096 if len(data) != 64 * 64 * 16 else sum(q != GATHER_WRAP for q in struct.iter_unpack("<4f", data)) | ||
| 868 | if rc == UNSUPPORTED: | ||
| 869 | results.append((name, None, unsupported_skip(msg))) | ||
| 870 | else: | ||
| 871 | results.append((name, rc == 0 and bad == 0, "4096/4096 pixels exact" if bad == 0 else | ||
| 872 | f"{bad} pixels differ from {GATHER_WRAP}: {msg.splitlines()[-1] if msg else ''}")) | ||
| 570 | elif name == "ps_tex": | 873 | elif name == "ps_tex": |
| 571 | # A texture through the descriptor hash table and the bindless set. vk_bindless_test compares the | 874 | # A texture through the descriptor hash table and the bindless set. vk_bindless_test compares the |
| 572 | # pixels itself, and exits 77 where the device lacks a feature the set or the shader needs. | 875 | # pixels itself, and exits 77 where the device lacks a feature the set or the shader needs. |
| @@ -582,12 +885,30 @@ def run_suite(a, work: str) -> int: | |||
| 582 | problem = sampler_test(a.build, spirv_dir) | 885 | problem = sampler_test(a.build, spirv_dir) |
| 583 | results.append((name, None if isinstance(problem, Skip) else not problem, | 886 | results.append((name, None if isinstance(problem, Skip) else not problem, |
| 584 | problem or f"{len(SAMPLER_CASES)} S#/T# cases, 4096 pixels each exact")) | 887 | problem or f"{len(SAMPLER_CASES)} S#/T# cases, 4096 pixels each exact")) |
| 888 | elif name in ("ps_texoff", "ps_texoff_implicit"): | ||
| 889 | # Texel offsets: needs vk_texture_test's texture, sampler and descriptor table (vk_harness binds none), | ||
| 890 | # and VK_KHR_maintenance8 for the non-constant Offset; the tool exits 77 without it. | ||
| 891 | raw = os.path.join(raw_dir, f"{name}.raw") | ||
| 892 | rc, msg = run_cmd([os.path.join(a.build, "vk_texture_test" + ext), vs_tri, spv, raw, *TEXOFF_ARGS], | ||
| 893 | env=texoff_env()) | ||
| 894 | if rc == UNSUPPORTED: | ||
| 895 | results.append((name, None, unsupported_skip(msg))) | ||
| 896 | elif rc != 0: | ||
| 897 | results.append((name, False, msg)) | ||
| 898 | else: | ||
| 899 | with open(raw, "rb") as f: | ||
| 900 | problem, covered = texoff_problem(f.read(), msg) | ||
| 901 | results.append((name, not problem, problem or f"4096/4096 pixels exact ({covered})")) | ||
| 585 | elif name.startswith("ps_"): | 902 | elif name.startswith("ps_"): |
| 586 | raw = os.path.join(raw_dir, f"{name}.raw") | 903 | raw = os.path.join(raw_dir, f"{name}.raw") |
| 587 | vs = os.path.join(spirv_dir, "vs_ids.spv") if name == "ps_flat" else vs_tri # check.py draws ps_flat with vs_ids | 904 | vs = os.path.join(spirv_dir, "vs_ids.spv") if name == "ps_flat" else vs_tri # check.py draws ps_flat with vs_ids |
| 588 | rc, msg = run_cmd([vk_harness, vs, spv, raw], env=gfx_env) | 905 | env = dict(gfx_env or os.environ, **PIXEL_ENV[name]) if name in PIXEL_ENV else gfx_env |
| 906 | bary_gs = os.path.join(spirv_dir, f"{name}.bary_gs.spv") | ||
| 907 | if bary_fallback() and os.path.isfile(bary_gs): # --bary-fallback PS: barycentrics from this GS | ||
| 908 | env = dict(env or os.environ, VKH_GS=bary_gs, VKH_GS_HELPER="1") | ||
| 909 | rc, msg = run_cmd([vk_harness, vs, spv, raw], env=env) | ||
| 589 | if rc == 77: # vk_harness: the device lacks a feature this shader needs (e.g. barycentrics) | 910 | if rc == 77: # vk_harness: the device lacks a feature this shader needs (e.g. barycentrics) |
| 590 | results.append((name, None, "SKIP (unsupported device)")) | 911 | results.append((name, None, unsupported_skip(msg))) |
| 591 | continue | 912 | continue |
| 592 | if rc != 0: | 913 | if rc != 0: |
| 593 | results.append((name, False, msg)) | 914 | results.append((name, False, msg)) |
| @@ -604,6 +925,25 @@ def run_suite(a, work: str) -> int: | |||
| 604 | "ps_ops6": (0xF800FFFF, 0x01000010, 0x00800800, 0x8000FFF0), | 925 | "ps_ops6": (0xF800FFFF, 0x01000010, 0x00800800, 0x8000FFF0), |
| 605 | "ps_ops7": (0x00FF8077, 0xFF0000FF, 0x89ABCDEF, 0x00070003), | 926 | "ps_ops7": (0x00FF8077, 0xFF0000FF, 0x89ABCDEF, 0x00070003), |
| 606 | "ps_ops8": (0x80000000, 0xFFFFFFFF, 0x000F100E, 0x0F0F0F1F), | 927 | "ps_ops8": (0x80000000, 0xFFFFFFFF, 0x000F100E, 0x0F0F0F1F), |
| 928 | "ps_f32_mods": (0xC0256A01, 0x3F800000, 0x41E00000, 0x3FC00000), | ||
| 929 | "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0), | ||
| 930 | "ps_med3_mods": (0x3F800000, 0x40400000, 0x40C00000, 0x3F400000), | ||
| 931 | "ps_scc_minmax": (0x00030205, 0x00030207, 0x00030209, 0x00030203), | ||
| 932 | "ps_fma_literal": (0x41B80000, 0x41800000, 0x40E00000, 0x41A40000), | ||
| 933 | "ps_f64_mods": (0x40040000, 0x3FF00000, 0x3FE40000, 0x3FF00000), # needs shaderFloat64 | ||
| 934 | # f16 op_sel / partial writes / inline constants: RDNA2 hardware words (see the .asm headers) | ||
| 935 | "ps_f16_med3_opsel": (0xAAAA4100, 0xAAAA4200, 0xAAAA3E00, 0x40005555), | ||
| 936 | "ps_f16_med3_mods": (0x41005555, 0x3C005555, 0x41003800, 0xAAAABA00), | ||
| 937 | "ps_f16_vop2": (0xAAAA4000, 0xAAAAC000, 0xAAAA3A00, 0x42003F00), | ||
| 938 | "ps_f16_vop2b": (0xAAAA3E00, 0xAAAAB800, 0xAAAA3C00, 0x42003400), | ||
| 939 | "ps_f16_vop1": (0xAAAA4000, 0xAAAABC00, 0xAAAAC000, 0xAAAA8000), | ||
| 940 | "ps_f16_vop1b": (0xAAAA3400, 0xAAAA4000, 0xAAAAB400, 0xAAAA3800), | ||
| 941 | "ps_f16_const": (0xAAAA3D00, 0x38005555, 0xAAAA3800, 0x3F000000), | ||
| 942 | "ps_f16_const2": (0x42003D00, 0x3D004200, 0xAAAABC00, 3), | ||
| 943 | "ps_f16_pack": (0x34003C00, 0x38003400, 0x34000000, 0x44004200), | ||
| 944 | "ps_sff_imm": (2, 1, 20, 16), # SHADER-46: s_ff0/s_ff1 of an immediate | ||
| 945 | "ps_fnan_med3": (0x40A00000, 0xC0200000, 0xC0200000, 0x40600000), # measured on RDNA2 hardware | ||
| 946 | "ps_fnan_fract": (0x3F7FFFFF, 0x00003BFF, 0xC0200000, 0xC0200000), | ||
| 607 | } | 947 | } |
| 608 | if name in const_wants: | 948 | if name in const_wants: |
| 609 | ok, detail = check_pixel_const(raw, const_wants[name]) | 949 | ok, detail = check_pixel_const(raw, const_wants[name]) |
| @@ -615,8 +955,10 @@ def run_suite(a, work: str) -> int: | |||
| 615 | ok, detail = None, f"SKIP (subgroup {m.group(1)} is narrower than 32 lanes)" | 955 | ok, detail = None, f"SKIP (subgroup {m.group(1)} is narrower than 32 lanes)" |
| 616 | else: | 956 | else: |
| 617 | ok, detail = check_bitmask_perm(raw) | 957 | ok, detail = check_bitmask_perm(raw) |
| 618 | elif name == "ps_uniform_branch": | 958 | elif name in ("ps_uniform_branch", "ps_scc_mask32"): # same expected pattern (see the .asm headers) |
| 619 | ok, detail = check_uniform_branch(raw) | 959 | ok, detail = check_uniform_branch(raw) |
| 960 | elif name == "ps_wqm": | ||
| 961 | ok, detail = check_wqm(raw) | ||
| 620 | elif name == "ps_flat": | 962 | elif name == "ps_flat": |
| 621 | ok, detail = check_flat(raw) | 963 | ok, detail = check_flat(raw) |
| 622 | else: | 964 | else: |
| @@ -641,13 +983,13 @@ def run_suite(a, work: str) -> int: | |||
| 641 | problem = mesh_v5_test(a.build, spirv_dir, Path(raw_dir) / f"{name}.raw") | 983 | problem = mesh_v5_test(a.build, spirv_dir, Path(raw_dir) / f"{name}.raw") |
| 642 | results.append((name, None if isinstance(problem, Skip) else not problem, | 984 | results.append((name, None if isinstance(problem, Skip) else not problem, |
| 643 | problem or "24/24 workgroup coordinates exact (2 x 3 x 4)")) | 985 | problem or "24/24 workgroup coordinates exact (2 x 3 x 4)")) |
| 644 | elif name in ("ms_tri", "ms_w64x_ballot"): | 986 | elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3"): |
| 645 | raw = os.path.join(raw_dir, f"{name}.raw") | 987 | raw = os.path.join(raw_dir, f"{name}.raw") |
| 646 | env = dict(gfx_env or os.environ, VKH_MESH="1") | 988 | env = dict(gfx_env or os.environ, VKH_MESH="1") |
| 647 | rc, msg = run_cmd([vk_harness, spv, fs_passthru, raw], env=env) | 989 | rc, msg = run_cmd([vk_harness, spv, fs_passthru, raw], env=env) |
| 648 | # ms_w64x_ballot needs exact wave64 (a 64-wide subgroup, or --wave64-emulate): skip it elsewhere, as | 990 | # ms_w64x_ballot needs exact wave64 (a 64-wide subgroup, or --wave64-emulate): skip it elsewhere, as |
| 649 | # the wave64 compute dumps are. | 991 | # the wave64 compute dumps are. |
| 650 | no64 = (name == "ms_w64x_ballot" and os.environ.get("LEONIDA_W64_EMULATE") != "1" and | 992 | no64 = (name == "ms_w64x_ballot" and not w64_emulated() and |
| 651 | not any(int(x) >= 64 for x in re.findall(r"subgroup \d+\.\.(\d+)", msg))) | 993 | not any(int(x) >= 64 for x in re.findall(r"subgroup \d+\.\.(\d+)", msg))) |
| 652 | if rc == UNSUPPORTED: | 994 | if rc == UNSUPPORTED: |
| 653 | results.append((name, None, unsupported_skip(msg))) | 995 | results.append((name, None, unsupported_skip(msg))) |
| @@ -670,6 +1012,17 @@ def run_suite(a, work: str) -> int: | |||
| 670 | ok, detail = check_clip_half(raw, 0.5, 1.0) | 1012 | ok, detail = check_clip_half(raw, 0.5, 1.0) |
| 671 | results.append((name, ok, detail)) | 1013 | results.append((name, ok, detail)) |
| 672 | 1014 | ||
| 1015 | if a.filter and not results: # the filter matched only inputs/partners: say so rather than "0/0 passed" | ||
| 1016 | names = [os.path.splitext(f)[0] for f in asm_files] | ||
| 1017 | partners = {os.path.splitext(f)[0] for f in DRAWN_WITH.values()} | set(TEXTURE_MIP_DEPENDENCIES) | ||
| 1018 | shown = ", ".join(names[:5]) + (", ..." if len(names) > 5 else "") | ||
| 1019 | role = "partners built for other tests" if partners.issuperset(names) else "inputs without a GPU test row" | ||
| 1020 | hint = ("; cs_bench_* shaders are benchmark inputs, run them with the benchmark tool" | ||
| 1021 | if all(n.startswith("cs_bench_") for n in names) else "") | ||
| 1022 | print(f"error: --filter {a.filter!r} selected {shown} but no runnable GPU test cases ({role}){hint}", | ||
| 1023 | file=sys.stderr) | ||
| 1024 | return 2 | ||
| 1025 | |||
| 673 | print("\n=== GPU TEST RESULTS ===") | 1026 | print("\n=== GPU TEST RESULTS ===") |
| 674 | passed = skipped = 0 | 1027 | passed = skipped = 0 |
| 675 | for name, ok, detail in results: | 1028 | for name, ok, detail in results: |
diff --git a/scripts/run_wine_tests.py b/scripts/run_wine_tests.py new file mode 100644 index 000000000..445310663 --- /dev/null +++ b/scripts/run_wine_tests.py | |||
| @@ -0,0 +1,166 @@ | |||
| 1 | """Run the Windows build's CTest tests under Wine, on Linux. | ||
| 2 | |||
| 3 | Usage: | ||
| 4 | python -I scripts/run_wine_tests.py --tests ctest.json --windows-root D:/a/Leonida/Leonida | ||
| 5 | [--root DIR] [--wine CMD] [--require NAME ...] [--timeout SECONDS] [--summary FILE] [--label TEXT] | ||
| 6 | |||
| 7 | --tests is the output of `ctest --show-only=json-v1` from the Windows build, and --windows-root the checkout it was | ||
| 8 | made in (forward slashes, as `cygpath -m` prints it). Paths under it are mapped to --root, the Linux checkout (default: | ||
| 9 | this repository), which must hold the Windows build's runtime/build folder at the same place. | ||
| 10 | |||
| 11 | Every test is run and reported. The exit code is 1 if a test named by --require fails or is missing, else 0: the | ||
| 12 | others show what does and doesn't work under Wine yet without failing the job. | ||
| 13 | """ | ||
| 14 | import argparse | ||
| 15 | import json | ||
| 16 | import os | ||
| 17 | import shlex | ||
| 18 | import subprocess | ||
| 19 | import sys | ||
| 20 | import time | ||
| 21 | |||
| 22 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 23 | |||
| 24 | |||
| 25 | def norm(path: str) -> str: | ||
| 26 | return path.replace("\\", "/").rstrip("/") | ||
| 27 | |||
| 28 | |||
| 29 | def map_path(arg: str, windows_root: str, root: str) -> str | None: | ||
| 30 | """The Linux path for a path under the Windows checkout, or None if it isn't one.""" | ||
| 31 | a = norm(arg) | ||
| 32 | w = norm(windows_root) | ||
| 33 | if a.lower() == w.lower(): | ||
| 34 | return root | ||
| 35 | if a.lower().startswith(w.lower() + "/"): | ||
| 36 | return os.path.join(root, *a[len(w) + 1:].split("/")) | ||
| 37 | return None | ||
| 38 | |||
| 39 | |||
| 40 | def wine_path(path: str) -> str: | ||
| 41 | """Wine's Z: drive is the Unix root, so a Windows program reads /x/y as Z:\\x\\y.""" | ||
| 42 | return "Z:" + os.path.abspath(path).replace("/", "\\") | ||
| 43 | |||
| 44 | |||
| 45 | def properties(test: dict) -> dict: | ||
| 46 | return {p["name"]: p["value"] for p in test.get("properties", [])} | ||
| 47 | |||
| 48 | |||
| 49 | def truthy(value) -> bool: | ||
| 50 | """A ctest boolean property. The JSON carries it as a string, so "0" must stay false.""" | ||
| 51 | return str(value).strip().lower() in ("1", "on", "true", "yes") | ||
| 52 | |||
| 53 | |||
| 54 | def run_test(test: dict, args, wine: list[str]) -> tuple[str, str]: | ||
| 55 | """Returns (status, detail): status is pass, fail or skip.""" | ||
| 56 | command = test.get("command") | ||
| 57 | if not command: | ||
| 58 | return "fail", "no command (target not built?)" | ||
| 59 | exe = map_path(command[0], args.windows_root, args.root) | ||
| 60 | if exe is None: | ||
| 61 | # A test that runs a tool of the Windows runner (cmake -P, python) rather than one this build made. | ||
| 62 | return "skip", f"runs {command[0]}, not a program from the build" | ||
| 63 | if not os.path.isfile(exe): | ||
| 64 | return "fail", f"executable not in the artifact: {command[0]}" | ||
| 65 | argv = list(wine) + [exe] | ||
| 66 | for a in command[1:]: | ||
| 67 | mapped = map_path(a, args.windows_root, args.root) | ||
| 68 | argv.append(wine_path(mapped) if mapped is not None else a) | ||
| 69 | props = properties(test) | ||
| 70 | cwd = props.get("WORKING_DIRECTORY") | ||
| 71 | cwd = map_path(cwd, args.windows_root, args.root) if cwd else os.path.dirname(exe) | ||
| 72 | if not cwd or not os.path.isdir(cwd): | ||
| 73 | cwd = os.path.dirname(exe) | ||
| 74 | start = time.monotonic() | ||
| 75 | try: | ||
| 76 | proc = subprocess.run(argv, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, | ||
| 77 | timeout=args.timeout) | ||
| 78 | except subprocess.TimeoutExpired as e: | ||
| 79 | out = (e.stdout or b"").decode("utf-8", "replace") | ||
| 80 | return "fail", f"timed out after {args.timeout} s\n{out}" | ||
| 81 | except OSError as e: # a mistyped --wine, or a missing one: report the test, do not abort the run | ||
| 82 | return "fail", f"could not start {argv[0]}: {e.strerror or e}" | ||
| 83 | elapsed = time.monotonic() - start | ||
| 84 | out = proc.stdout.decode("utf-8", "replace") | ||
| 85 | code = proc.returncode | ||
| 86 | skip_code = props.get("SKIP_RETURN_CODE") | ||
| 87 | if skip_code is not None and code == int(skip_code): | ||
| 88 | return "skip", f"exit {code} (skip) in {elapsed:.1f} s\n{out}" | ||
| 89 | passed = (code != 0) if truthy(props.get("WILL_FAIL")) else (code == 0) | ||
| 90 | return ("pass" if passed else "fail"), f"exit {code} in {elapsed:.1f} s\n{out}" | ||
| 91 | |||
| 92 | |||
| 93 | def positive_seconds(text: str) -> float: | ||
| 94 | """--timeout: a value of 0 or less made subprocess.run raise ValueError before the test could be reported.""" | ||
| 95 | try: | ||
| 96 | value = float(text) | ||
| 97 | except ValueError: | ||
| 98 | raise argparse.ArgumentTypeError(f"invalid float value: {text!r}") from None | ||
| 99 | if value <= 0: | ||
| 100 | raise argparse.ArgumentTypeError("must be greater than 0") | ||
| 101 | return value | ||
| 102 | |||
| 103 | |||
| 104 | def read_tests(path: str) -> list[dict] | None: | ||
| 105 | """The tests in a `ctest --show-only=json-v1` file, or None when it is not one.""" | ||
| 106 | try: | ||
| 107 | with open(path, encoding="utf-8-sig") as f: | ||
| 108 | doc = json.load(f) | ||
| 109 | except (OSError, ValueError) as e: | ||
| 110 | print(f"ERROR: cannot read {path}: {e}", file=sys.stderr) | ||
| 111 | return None | ||
| 112 | if not isinstance(doc, dict) or not isinstance(doc.get("tests", []), list): | ||
| 113 | print(f"ERROR: {path} is not the output of ctest --show-only=json-v1", file=sys.stderr) | ||
| 114 | return None | ||
| 115 | return doc.get("tests", []) | ||
| 116 | |||
| 117 | |||
| 118 | def main() -> int: | ||
| 119 | ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | ||
| 120 | ap.add_argument("--tests", required=True, help="ctest --show-only=json-v1 output from the Windows build") | ||
| 121 | ap.add_argument("--windows-root", required=True, help="the Windows checkout the tests were listed in") | ||
| 122 | ap.add_argument("--root", default=ROOT, help="the Linux checkout (default: this repository)") | ||
| 123 | ap.add_argument("--wine", default=os.environ.get("WINE", "wine"), help="Wine command (default: $WINE or wine)") | ||
| 124 | ap.add_argument("--require", action="append", default=[], help="a test that must pass (repeatable)") | ||
| 125 | ap.add_argument("--timeout", type=positive_seconds, default=120.0, help="seconds per test (default 120)") | ||
| 126 | ap.add_argument("--summary", help="append a Markdown table to this file (e.g. $GITHUB_STEP_SUMMARY)") | ||
| 127 | ap.add_argument("--label", help="named in the summary's heading, e.g. the Wine version") | ||
| 128 | args = ap.parse_args() | ||
| 129 | |||
| 130 | tests = read_tests(args.tests) | ||
| 131 | if tests is None: | ||
| 132 | return 2 | ||
| 133 | wine = shlex.split(args.wine) | ||
| 134 | results = {} | ||
| 135 | for test in tests: | ||
| 136 | name = test.get("name", "?") | ||
| 137 | status, detail = run_test(test, args, wine) | ||
| 138 | results[name] = status | ||
| 139 | print(f"[{status.upper()}] {name}", flush=True) | ||
| 140 | if status != "pass": | ||
| 141 | for line in detail.rstrip().splitlines()[-40:]: | ||
| 142 | print(f" {line}") | ||
| 143 | |||
| 144 | missing = [n for n in args.require if n not in results] | ||
| 145 | failed_required = [n for n in args.require if results.get(n) != "pass"] | ||
| 146 | counts = {s: sum(1 for v in results.values() if v == s) for s in ("pass", "fail", "skip")} | ||
| 147 | print(f"\n{counts['pass']} passed, {counts['fail']} failed, {counts['skip']} skipped under Wine " | ||
| 148 | f"({len(results)} tests)") | ||
| 149 | for n in missing: | ||
| 150 | print(f"required test not listed by the Windows build: {n}") | ||
| 151 | if failed_required: | ||
| 152 | print("required tests that did not pass: " + ", ".join(failed_required)) | ||
| 153 | |||
| 154 | if args.summary: | ||
| 155 | with open(args.summary, "a", encoding="utf-8") as f: | ||
| 156 | f.write(f"### Windows tests under {args.label or 'Wine'}\n\n") | ||
| 157 | f.write(f"{counts['pass']} passed, {counts['fail']} failed, {counts['skip']} skipped.\n\n") | ||
| 158 | f.write("| Test | Result | Required |\n|---|---|---|\n") | ||
| 159 | for name, status in results.items(): | ||
| 160 | f.write(f"| `{name}` | {status} | {'yes' if name in args.require else ''} |\n") | ||
| 161 | f.write("\n") | ||
| 162 | return 1 if failed_required else 0 | ||
| 163 | |||
| 164 | |||
| 165 | if __name__ == "__main__": | ||
| 166 | sys.exit(main()) | ||
diff --git a/scripts/shader_stats.py b/scripts/shader_stats.py new file mode 100644 index 000000000..b50b1c309 --- /dev/null +++ b/scripts/shader_stats.py | |||
| @@ -0,0 +1,162 @@ | |||
| 1 | """How efficiently the driver compiles the translated shaders, against the game's own RDNA code. | ||
| 2 | |||
| 3 | python3 -I scripts/shader_stats.py <stats.csv> <disasm dir> [--details] | ||
| 4 | |||
| 5 | <stats.csv> comes from vk_pipeline_check <spirv dir> --stats <stats.csv> (the driver's statistics for each translated | ||
| 6 | shader); <disasm dir> holds the original <name>.s listings the translator read. For every shader in both it compares | ||
| 7 | the driver's instruction count with the original one (code growth) and its VGPRs with the highest VGPR the original | ||
| 8 | code uses, and it flags scratch memory and spills: a register file that didn't fit in registers and went to memory, | ||
| 9 | which is the expensive case (relative VGPR indexing, v_movrels/v_movreld, forces it). It prints a summary per stage and, | ||
| 10 | with --details, one line per shader. | ||
| 11 | |||
| 12 | Metrics are read only where the driver emits these exact RADV/ACO statistic names with a numeric value: Instructions, | ||
| 13 | VGPRs, SGPRs, Scratch size, Spilled VGPRs, Spilled SGPRs, Subgroups per SIMD. No equivalence is claimed for other | ||
| 14 | drivers' statistics, even similarly named ones. A metric that isn't reported is shown as - (n/a in the summary), never | ||
| 15 | as 0; a summary clause over fewer shaders than the stage has says so with (n of N), and the original VGPRs it compares | ||
| 16 | with are those of the same shaders. With only one of the two spill statistics reported, spills shows it when positive, | ||
| 17 | with >= to mark a lower bound, and - when it is 0. When a driver omits a comparison metric, --details also lists any additional driver counters under that | ||
| 18 | shader with their original names and values. A note lists those names in summary mode. | ||
| 19 | """ | ||
| 20 | import csv | ||
| 21 | import math | ||
| 22 | import os | ||
| 23 | import statistics | ||
| 24 | import sys | ||
| 25 | from collections import defaultdict | ||
| 26 | |||
| 27 | sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tools")) | ||
| 28 | import shader_ir # noqa: E402 | ||
| 29 | |||
| 30 | # (row key, RADV/ACO statistic name) of the statistics read as numbers; spills combine SPILLS. | ||
| 31 | METRICS = [("aco", "Instructions"), ("vgprs", "VGPRs"), ("sgprs", "SGPRs"), ("scratch", "Scratch size"), | ||
| 32 | ("waves", "Subgroups per SIMD")] | ||
| 33 | SPILLS = ("Spilled VGPRs", "Spilled SGPRs") | ||
| 34 | KNOWN = {stat for _, stat in METRICS} | set(SPILLS) | ||
| 35 | # --details columns after shader and stage: (row key, header, width, format spec). | ||
| 36 | COLUMNS = [("orig", "orig", 5, ""), ("aco", "aco", 5, ""), ("growth", "growth", 6, ".2f"), ("v_orig", "v_orig", 6, ""), | ||
| 37 | ("vgprs", "VGPRs", 5, ""), ("sgprs", "SGPRs", 5, ""), ("scratch", "scratch", 7, ""), | ||
| 38 | ("spill_detail", "spills", 6, ""), ("waves", "waves", 5, "")] | ||
| 39 | |||
| 40 | |||
| 41 | def original(path): | ||
| 42 | """(instruction count, VGPRs used) of an original RDNA listing.""" | ||
| 43 | insns = shader_ir.parse_file(path)["insns"] | ||
| 44 | top = max((a["r"] + a.get("n", 1) for i in insns for a in i["args"] if a.get("k") == "vgpr"), default=0) | ||
| 45 | return len(insns), top | ||
| 46 | |||
| 47 | |||
| 48 | def load_stats(path): | ||
| 49 | """Counter names and raw values by (shader, stage), as written by vk_pipeline_check --stats.""" | ||
| 50 | out = defaultdict(dict) | ||
| 51 | with open(path, newline="", encoding="utf-8") as f: | ||
| 52 | for row in csv.DictReader(f): | ||
| 53 | out[row["name"], row["stage"]][row["statistic"]] = row["value"] | ||
| 54 | return out | ||
| 55 | |||
| 56 | |||
| 57 | def number(raw): | ||
| 58 | """The exact int, or else the finite float, a raw value holds; None if it is missing or not such a number.""" | ||
| 59 | if raw is None: | ||
| 60 | return None | ||
| 61 | for parse in (int, float): | ||
| 62 | try: | ||
| 63 | value = parse(raw) | ||
| 64 | if not math.isfinite(value): | ||
| 65 | return None | ||
| 66 | return int(value) if isinstance(value, float) and value.is_integer() else value | ||
| 67 | except (TypeError, ValueError, OverflowError): | ||
| 68 | pass | ||
| 69 | return None | ||
| 70 | |||
| 71 | |||
| 72 | def shader_row(name, stage, st, src): | ||
| 73 | n_orig, v_orig = original(src) | ||
| 74 | r = {"name": name, "stage": stage, "orig": n_orig, "v_orig": v_orig} | ||
| 75 | for key, stat in METRICS: | ||
| 76 | r[key] = number(st.get(stat)) | ||
| 77 | r["growth"] = None if r["aco"] is None else r["aco"] / max(n_orig, 1) | ||
| 78 | |||
| 79 | spill_counts = [number(st.get(stat)) for stat in SPILLS] | ||
| 80 | known_spills = [v for v in spill_counts if v is not None] | ||
| 81 | complete_spills = len(known_spills) == len(SPILLS) | ||
| 82 | total = sum(known_spills) | ||
| 83 | r["spills"] = total if complete_spills or total > 0 else None | ||
| 84 | r["spill_detail"] = f">={total}" if total > 0 and not complete_spills else r["spills"] | ||
| 85 | |||
| 86 | complete = complete_spills and all(r[key] is not None for key, _ in METRICS) | ||
| 87 | r["raw"] = {} if complete else {stat: value for stat, value in st.items() if stat not in KNOWN} | ||
| 88 | return r | ||
| 89 | |||
| 90 | |||
| 91 | def cell(value, spec=""): | ||
| 92 | """A details cell: the value, or - when it isn't reported.""" | ||
| 93 | return "-" if value is None else format(value, spec) | ||
| 94 | |||
| 95 | |||
| 96 | def reported(rs, key): | ||
| 97 | return [r for r in rs if r[key] is not None] | ||
| 98 | |||
| 99 | |||
| 100 | def coverage(n, total): | ||
| 101 | return f" ({n} of {total})" if n < total else "" | ||
| 102 | |||
| 103 | |||
| 104 | def count_clause(rs, key, label): | ||
| 105 | """How many of the shaders reporting key have it above 0.""" | ||
| 106 | known = reported(rs, key) | ||
| 107 | if not known: | ||
| 108 | return f"{label} n/a" | ||
| 109 | return f"{label} in {sum(r[key] > 0 for r in known)}{coverage(len(known), len(rs))}" | ||
| 110 | |||
| 111 | |||
| 112 | def median_clause(rs, key, label): | ||
| 113 | known = reported(rs, key) | ||
| 114 | if not known: | ||
| 115 | return f"{label} n/a" | ||
| 116 | return f"{label} median {statistics.median(r[key] for r in known):g}{coverage(len(known), len(rs))}" | ||
| 117 | |||
| 118 | |||
| 119 | def main(): | ||
| 120 | args = [a for a in sys.argv[1:] if not a.startswith("--")] | ||
| 121 | if len(args) != 2: | ||
| 122 | sys.exit(__doc__) | ||
| 123 | stats, disasm = load_stats(args[0]), args[1] | ||
| 124 | rows = [] | ||
| 125 | for (name, stage), st in sorted(stats.items()): | ||
| 126 | src = os.path.join(disasm, name + ".s") | ||
| 127 | if os.path.isfile(src): | ||
| 128 | rows.append(shader_row(name, stage, st, src)) | ||
| 129 | if not rows: | ||
| 130 | sys.exit("no shader is in both the statistics and the disasm folder") | ||
| 131 | if "--details" in sys.argv: | ||
| 132 | print(f"{'shader':26} {'stage':5} " + " ".join(f"{head:>{width}}" for _, head, width, _ in COLUMNS)) | ||
| 133 | for r in rows: | ||
| 134 | print(f"{r['name']:26} {r['stage']:5} " | ||
| 135 | + " ".join(f"{cell(r[key], spec):>{width}}" for key, _, width, spec in COLUMNS)) | ||
| 136 | for stat, raw in sorted(r["raw"].items()): | ||
| 137 | print(f" {stat} = {raw}") | ||
| 138 | print() | ||
| 139 | else: | ||
| 140 | unread = sorted({stat for r in rows for stat in r["raw"]}) | ||
| 141 | if unread: | ||
| 142 | print("additional driver statistics (see --details): " + "; ".join(unread), file=sys.stderr) | ||
| 143 | for stage in sorted({r["stage"] for r in rows}): | ||
| 144 | rs = [r for r in rows if r["stage"] == stage] | ||
| 145 | g = sorted(r["growth"] for r in reported(rs, "growth")) | ||
| 146 | growth = "code growth n/a" | ||
| 147 | if g: | ||
| 148 | growth = (f"code growth median {statistics.median(g):.2f}x " | ||
| 149 | f"(p90 {g[int(0.9 * (len(g) - 1))]:.2f}x, max {g[-1]:.2f}x){coverage(len(g), len(rs))}") | ||
| 150 | v = reported(rs, "vgprs") | ||
| 151 | vgprs = "VGPRs n/a" | ||
| 152 | if v: | ||
| 153 | vgprs = (f"VGPRs median {statistics.median(r['vgprs'] for r in v):g} " | ||
| 154 | f"vs original {statistics.median(r['v_orig'] for r in v):g}{coverage(len(v), len(rs))}") | ||
| 155 | print(f"{stage}: {len(rs)} shaders, {growth}; {vgprs}; " | ||
| 156 | f"{count_clause(rs, 'scratch', 'scratch')}, {count_clause(rs, 'spills', 'spills')}; " | ||
| 157 | f"{median_clause(rs, 'waves', 'waves/SIMD')}") | ||
| 158 | return 0 | ||
| 159 | |||
| 160 | |||
| 161 | if __name__ == "__main__": | ||
| 162 | sys.exit(main()) | ||