Files
mandy/tools/shader_ir.py
Jan Trencansky 39879ce0fd Merge main into RT-PROTON-STORY-LOAD (#984)
Merges main at 1154976d4 into the integration branch at 273b3bdf9 (merge base ece4ba5b3). 42 files conflicted;
this commit is the resolution only. Build and test repairs follow in their own commits.

Rule of resolution: where both sides added different things, both stay; where both made the same change in two
forms, main's reviewed form stays and whatever #984's form did in addition is carried into it; where the two
changed the same code for different purposes, both purposes are kept.

Xbox proxy code (runtime/shims/d3d12_xs_device.cpp, d3d12_xs_device.h, d3d12_xs.cpp, d3d12_xs_alloc_size.h,
d3d12_xs_desc_clean.h, registry.cpp):
- d3d12_xs_device.cpp is #984's file with main's differing pieces ported in: env_slot and the configurable device
  routes, XboxQueueSlotRoutes, PresentationHandler / set_presentation_handler, the console caller rule for device
  slots 61 and 74 (#383, #385), route_xbox_device_slot, slot 81 as GetFrameStatisticsX, create_host_device, the
  console-form rule for slots 25 and 56, the console list IID of #359, and the forms of queue slot 18 (#403) and
  list slot 139 (#396).
- Kept from #984: the list proxy with handle translation, queue slots 16/17 as Signal/Wait, the fence's
  completed-value mirror, the shared FrameTokenSource, PresentX through queue_present_x when no handler is
  attached (slot 30, or 32 on a queue detected as the newer layout), slots 27/53/55/57/70/71/133, the wider
  pc_resource_desc, S_OK for queue slots past the PC table.
- Dropped: #984's GetFrameEventsX and LEONIDA_XS_FRAME_EVENTS_SLOT, its second-word rule for slot 61, its
  undetected-layout rule for queue slot 18, its list IID mapping to GraphicsCommandList6; main's copy of the base
  list proxy, its null-view slot 70 and its refusing slot 133.

Proxy tests (runtime/test/xs_proxy_mock_test.cpp, device_proxy_test.cpp, queue_proxy_test.cpp):
- Checks of both sides, each run once; main's forms of the render-target size and layout checks with #984's extra
  cases added; main's --env-slots-74 and #984's --env-slots-70.
- Adapted to the merged code: the queue tail answers S_OK, slot 73 answers an unknown IID with the list proxy,
  the queue slot 18 case installs a console caller. Dropped: #984's slot 81 GetFrameEventsX cases.

D3D12/Vulkan layer (runtime/shims/d3d12_com.cpp, d3d12_vulkan_device.cpp, runtime/src/command_list.h,
frame_pacer.h, shader_library.h, vulkan_backend.h, vulkan_replay.h, runtime/test/command_list_test.cpp,
d3d12_close_parity_test.cpp, d3d12_execute_indirect_validation_test.cpp, replay_texture_barrier_test.cpp,
vk_pipeline_check.cpp, vk_test_device.h):
- Resource::create_texture: #984's title images (deferred placed, pending streamed, title pool) and main's
  ordinary textures (#1413 shared blocks, #1364 staging fallback) are exclusive branches chosen by the texture's
  origin, so both pools run on disjoint sets of textures.
- frame_pacer.h is main's pacer (#402) with #984's FrameTokenSource as the token counter.
- main's forms kept for ExecuteIndirect (#1066, #377), the barrier into LAYOUT_UNDEFINED (#1055), the B4G4R4A4
  stand-in, per-face stencil masks, the unaligned tile staging (#528) and the device-lost flag (#980).
- shader_library.h: main's block inflate; #984's `bulk` parameter now defaults to true so main's callers keep it.
- Dropped: #984's B8G8R8A8 stand-in for B4G4R4A4 targets, its refusal of separate stencil masks, its zero-count
  refusal in ExecuteIndirect, its wider UNDEFINED -> UNDEFINED release and the test case for it.

Other shims (runtime/shims/dstorage.cpp, file_system.cpp, gameinput.cpp, xgameruntime_offline.cpp,
runtime/test/xgameruntime_offline_test.cpp, xmem_test.cpp):
- ReadFile and DirectStorage reads: #984's pinned kernel_writes read, then main's touch_pages retry on
  ERROR_NOACCESS. main's rt::fs::read_file is folded into #984's read_file.
- gameinput: main's strict LEONIDA_INPUT_SCRIPT parser with #984's rsup/rsdown entries.
- Speech synthesis: main's one silent voice and handle checks; #984's accept-anything form dropped.

Build, tools, docs (runtime/CMakeLists.txt, runtime/cmake/translator_deps.cmake, scripts/build_runtime.ps1,
make_game.py, tools/rdna2spirv.py, shader_disasm.py, shader_ir.py, shader_library.py,
runtime/test/shaders/cs_imgload_tfe.asm, cs_imgload_d16_tfe.asm, docs/README.md, boot.md, d3d12_vulkan.md,
runtime/README.md):
- Unions of the test, target and source lists; spirv_loop_guard.py added to translator_deps.cmake.
- rdna2spirv.py: main's DPP compare rule (#957), SMEM vcc base (#647) and widen_wave64_masks (#1021); #984's
  restore_skipped_instructions and restore_dot4_inline_sel. #984's duplicate widen_wave64_valu_masks dropped.
- shader_disasm.py and shader_ir.py: main's structure with #984's one-line-per-dword llvm-mc input and wave flags.
- shader_library.py: main's structure with #984's --compute-hashes and per-state compute variants.

One file that did not conflict is changed here: tools/rdna2_decode.py. Git kept both sides' decoders for a VOPC
compare with a DPP operand, and #984's narrower one shadowed main's; it is main's file again.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 19:38:04 -05:00

328 lines
15 KiB
Python

"""Parse LLVM AMDGPU disassembly (.s from shader_disasm.py) into a structured instruction list.
Each instruction: {"op": mnemonic, "args": [operand...], "mods": [modifier...], "enc": bytes, "pc": byte offset}
Operand kinds: sgpr s5 / s[4:7], vgpr v3 / v[0:3], special (vcc, exec, m0, scc...), inline constant, literal,
label/offset (for branches), hw register, and raw text for anything else.
As a module: parse_file(path) -> {"name", "code_start", "insns": [...], "invalid": [pc...]}
As a tool: python -I shader_ir.py <disasm dir> [--limit N] (parses everything and reports coverage)
Usage: `python -I tools/shader_ir.py --help` lists the options.
"""
import argparse
import itertools
import os
import re
import sys
from collections import Counter
ENC = re.compile(r";\s*encoding:\s*\[([^\]]*)\]")
HDR = re.compile(r"^;\s*(\S+)\s+code 0x([0-9a-f]+)\.\.0x([0-9a-f]+)")
INVALID_AT = re.compile(r"<stdin>:(\d+):(\d+): warning: invalid instruction encoding")
SPECIAL = {"vcc", "vcc_lo", "vcc_hi", "exec", "exec_lo", "exec_hi", "m0", "scc", "null", "off", "src_scc",
"src_execz", "src_vccz", "src_lds_direct", "src_shared_base", "src_shared_limit",
"src_private_base", "src_private_limit", "src_pops_exiting_wave_id", "lds", "flat_scratch",
"flat_scratch_lo", "flat_scratch_hi", "ttmp", "tba", "tma"}
# operand() runs once per operand of every instruction of every shader, so its patterns are compiled once here
# rather than looked up in re's cache on each call.
_NEG = re.compile(r"neg\((.+)\)")
_ABS = re.compile(r"abs\((.+)\)")
_SEXT = re.compile(r"sext\((.+)\)")
_REG = re.compile(r"([sv])(\d+)")
_REG_RANGE = re.compile(r"([sv])\[(\d+):(\d+)\]")
_TTMP = re.compile(r"ttmp(\d+)|ttmp\[(\d+):(\d+)\]")
_VLIST = re.compile(r"\[(v\d+(?:,\s*v\d+)+)\]")
_SLIST = re.compile(r"\[((?:s\d+|vcc_lo|vcc_hi)(?:\s*,\s*(?:s\d+|vcc_lo|vcc_hi))+)\]")
_ATTR = re.compile(r"attr(\d+)\.([xyzw])")
_TARGET = re.compile(r"(pos|param|mrt|mrtz|null|prim)(\d*)")
_INT = re.compile(r"-?(0x[0-9a-fA-F]+|\d+)")
_FLOAT = re.compile(r"-?\d+\.\d+(e[+-]?\d+)?")
# LLVM 23 prints a literal it could also show as an inline constant as lit(V), e.g. a v_fma_mix* f32 source
# `lit(0x42200000)`, where LLVM 21 printed the inline constant of the low half (0) and dropped the literal.
# Only a numeric constant is unwrapped: lit(v2) is no literal and stays raw (Unsupported), as before.
_LIT = re.compile(r"lit\((-?(?:0x[0-9a-fA-F]+|\d+(?:\.\d+(?:e[+-]?\d+)?)?))\)")
def operand(tok):
t = tok.strip()
if "lit(" in t:
# lit(V) is the constant V. A leading '-' on it is the VOP3 neg modifier, as neg(V) (not integer negation).
t = _LIT.sub(r"\1", t)
if t.startswith("-"):
t = "neg(" + t[1:] + ")"
neg = t.startswith("-")
core = t[1:] if neg else t
absm = len(core) > 2 and core.startswith("|") and core.endswith("|")
if absm:
core = core[1:-1]
# Fast path for the commonest operands: single register (v3, s12), special register, or unsigned decimal int.
if len(core) > 1 and core[0] in "sv" and core[1:].isdigit():
return {"k": core[0] + "gpr", "r": int(core[1:]), "n": 1, "neg": neg, "abs": absm}
if core in SPECIAL:
return {"k": "special", "t": core, "neg": neg, "abs": absm}
if core.isascii() and core.isdigit():
v = int(core, 10)
if absm:
out = {"k": "imm", "v": v, "abs": True}
if neg:
out["neg"] = True
return out
return {"k": "imm", "v": -v if neg else v}
if "(" in core:
m = _NEG.fullmatch(core)
if m: # VOP3 FP negation: neg(0), neg(1.0), neg(0x3f800000), neg(|1.0|), neg(v1)
inner = operand(m.group(1))
if absm:
# Outer |...| absorbs the inner neg; outer '-' (if any) negates the result.
inner["abs"] = True
if neg:
inner["neg"] = True
elif inner.get("k") in ("imm", "fimm"):
inner.pop("neg", None)
else:
inner["neg"] = False
elif not neg:
# Keep neg as a VOP3 sign-bit modifier on constants instead of integer negation:
# in LLVM AMDGPU, neg(1) flips bit 31 (0x80000001) while -1 is 0xffffffff.
new_neg = not inner.get("neg", False)
if not new_neg and inner.get("k") in ("imm", "fimm"):
inner.pop("neg", None)
else:
inner["neg"] = new_neg
return inner
m = _ABS.fullmatch(core)
if m: # VOP3 FP absolute value: abs(v0), abs(0xbf800000), neg(abs(1.0))
inner = operand(m.group(1))
inner["abs"] = True
if neg:
inner["neg"] = True
elif inner.get("k") in ("imm", "fimm"):
inner.pop("neg", None)
else:
inner["neg"] = False
return inner
m = _SEXT.fullmatch(core)
if m: # SDWA integer sign-extension of the selected source bits
inner = operand(m.group(1))
inner["sext"] = True
if absm:
inner["abs"] = True
inner["neg"] = inner.get("neg", False) or neg
return inner
if "[" in core:
m = _REG_RANGE.fullmatch(core)
if m:
lo, hi = int(m.group(2)), int(m.group(3))
return {"k": m.group(1) + "gpr", "r": lo, "n": hi - lo + 1, "neg": neg, "abs": absm}
m = _VLIST.fullmatch(core)
if m: # NSA image address: non-contiguous VGPR list
return {"k": "vlist", "r": [int(x.strip()[1:]) for x in m.group(1).split(",")]}
m = _SLIST.fullmatch(core)
if m: # LLVM VCCTuple scalar register list, e.g. [s100,s101,s102,s103,s104,s105,vcc_lo,vcc_hi]
items = [int(x[1:]) if x.startswith("s") else x for x in (t.strip() for t in m.group(1).split(","))]
return {"k": "slist", "r": items, "n": len(items)}
if core.startswith("ttmp"):
m = _TTMP.fullmatch(core)
if m:
return {"k": "ttmp", "t": core}
if core.startswith("attr"):
m = _ATTR.fullmatch(core)
if m:
return {"k": "attr", "a": int(m.group(1)), "c": "xyzw".index(m.group(2))}
if core in ("p0", "p10", "p20"):
return {"k": "interp", "t": core}
m = _TARGET.fullmatch(core)
if m and core not in ("null",):
return {"k": "target", "t": core}
if _INT.fullmatch(core):
# int(core, 0) rejects the leading-zero decimals this regex accepts ('010', '08', '0001'),
# which aborts a whole parse_file() run on one disassembly line.
neg_core = core.startswith("-")
digits = core[1:] if neg_core else core
v = int(digits, 16) if digits.lower().startswith("0x") else int(digits, 10)
if neg_core:
v = -v
if absm:
out = {"k": "imm", "v": v, "abs": True}
if neg:
out["neg"] = True
return out
return {"k": "imm", "v": -v if neg else v}
if _FLOAT.fullmatch(core):
if absm:
out = {"k": "fimm", "v": float(core), "abs": True}
if neg:
out["neg"] = True
return out
return {"k": "fimm", "v": float(core) * (-1 if neg else 1), "abs": False}
if core.startswith("hwreg(") or core.startswith("sendmsg(") or core.startswith("vmcnt(") or \
core.startswith("expcnt(") or core.startswith("lgkmcnt(") or core.startswith("vscnt(") or \
core.startswith("depctr") or core.startswith("instid") or core.startswith("quad_perm") or \
core.startswith("row_") or core.startswith("dpp") or core.startswith("sel:") or "(" in core:
return {"k": "special", "t": core}
return {"k": "raw", "t": t}
def split_args(s):
if "(" not in s and "[" not in s:
parts = s.split(",")
if parts and not parts[-1].strip():
parts.pop()
return parts
out, depth, cur = [], 0, ""
for ch in s:
if ch in "([":
depth += 1
elif ch in ")]":
depth -= 1
if ch == "," and depth == 0:
out.append(cur)
cur = ""
else:
cur += ch
if cur.strip():
out.append(cur)
return out
SENDMSG = re.compile(r"sendmsg\([^)]*\)")
MODWORDS = re.compile(r"\b(offset:(?:swizzle\([^)]*\)|\S+)|offen|idxen|glc|slc|dlc|lds|tfe|unorm|da|d16|a16|nv|r128|lwe|clamp|"
r"mul:\d+|div:\d+|op_sel(?:_hi)?:\[[^\]]*\]|neg_lo:\[[^\]]*\]|neg_hi:\[[^\]]*\]|"
r"dmask:\S+|dim:\S+|format:\S+|done|vm|compr|row_mask:\S+|bank_mask:\S+|"
r"bound_ctrl:\S+|fi:\S+|offset0:\S+|offset1:\S+|gds|inst_offset:\S+|"
r"dst_sel:\S+|dst_unused:\S+|src0_sel:\S+|src1_sel:\S+|high|dpp8:\[[^\]]*\]|"
r"row_mirror|row_half_mirror|row_shl:\d+|row_shr:\d+|row_ror:\d+|row_share:\d+|"
r"row_xmask:\d+|quad_perm:\[[^\]]*\])(?=\s|,|$)")
def parse_line(line):
code, _, comment = line.partition(";")
enc = None
if comment and "encoding" in comment:
m = ENC.search(line)
if m:
enc = bytes(int(x, 16) for x in m.group(1).split(",") if x.strip())
code = code.strip()
if not code:
return None
fields = code.split(maxsplit=1)
op = fields[0]
rest = fields[1] if len(fields) > 1 else ""
# sendmsg(MSG_GS, GS_OP_NOP) contains a comma: keep it as one operand.
if "sendmsg(" in rest:
rest = SENDMSG.sub(lambda m: m.group(0).replace(", ", "|").replace(",", "|"), rest)
mods = []
if rest:
def _take_mod(match):
mods.append(match.group(1))
return ""
rest = MODWORDS.sub(_take_mod, rest)
parts = [a for a in split_args(rest) if a.strip()]
if op in ("s_waitcnt", "s_waitcnt_depctr"):
# LLVM separates named wait counters with spaces.
parts = [token for part in parts for token in part.split()]
elif parts and len(parts[0].split()) == 2:
# 'exp pos0 v3, ...' / 'exp null off, ...': the target is space-separated from the first operand.
parts = parts[0].split() + parts[1:]
args = [operand(a) for a in parts]
if op.startswith(("v_add_f64", "v_cvt_f32_f64", "v_rcp_f64", "v_rsq_f64", "v_sqrt_f64",
"v_frexp_mant_f64", "v_frexp_exp_i32_f64", "v_ldexp_f64", "v_trunc_f64",
"v_ceil_f64", "v_rndne_f64", "v_floor_f64")):
for src, spelling in zip(args[1:], parts[1:]):
# LLVM prints inline integers in decimal and the separate literal dword in hex,
# even for two sources with the same numeric value (e.g. 0x1 and 1).
if src["k"] == "imm" and ("0x" in spelling or not -16 <= src["v"] <= 64):
src["f64_literal"] = True
# The hex digits are the operand's printed width: LLVM pads nothing, so a value that
# fits one literal dword prints in at most 8 of them (docs/design.md, f64 literal sources).
m = re.search(r"0x([0-9a-fA-F]+)", spelling)
if m:
src["literal_hex_digits"] = len(m.group(1))
return {"op": op, "args": args, "mods": mods, "enc": enc.hex() if enc else None}
def parse_file(path):
info = {"name": os.path.splitext(os.path.basename(path))[0], "insns": [], "invalid": 0}
invalid_at = set()
with open(path, encoding="utf-8", errors="replace") as f:
first = f.readline()
header = HDR.match(first)
pc = int(header.group(2), 16) if header else 0
info["code_start"] = pc
# the end of the code range the header declares (exclusive), None without a header: undecodable words can
# sit between the last printed instruction and it
info["code_end"] = int(header.group(3), 16) if header else None
body = True
# Older llvm-mc listings can have gigabytes of echoed source in their diagnostics.
for line in itertools.chain((first,), f):
info["invalid"] += line.count("invalid instruction encoding")
# Where llvm-mc rejected a word: tools/shader_disasm.py feeds it lines of "0xNN " bytes (5 characters a
# byte), one dword a line (one line of the whole code in older listings), starting at code_start, so
# the message's line and column give the byte offset. The decoder then moves on by 4 bytes.
for row, col in INVALID_AT.findall(line):
invalid_at.add(info["code_start"] + (int(row) - 1) * 4 + (int(col) - 1) // 5)
if line.startswith("; ---"):
body = False
if not body or not line.startswith("\t") or line.lstrip().startswith("."):
continue
ins = parse_line(line)
if ins:
ins["pc"] = pc
if ins["enc"]:
pc += len(ins["enc"]) // 2
info["insns"].append(ins)
info["invalid_at"] = sorted(invalid_at)
return info
def positive_int(text):
try:
value = int(text)
except ValueError:
raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None
if value < 1:
raise argparse.ArgumentTypeError("must be at least 1")
return value
def main(argv=None):
ap = argparse.ArgumentParser(description="Parse a folder of .s disassembly and report operand coverage.")
ap.add_argument("src", help="folder of .s files written by shader_disasm.py")
ap.add_argument("--limit", type=positive_int, help="parse only the first N files, sorted by name")
a = ap.parse_args(argv)
if not os.path.isdir(a.src):
ap.error(f"{a.src} is not a folder")
try:
with os.scandir(a.src) as entries:
files = sorted(entry.path for entry in entries
if entry.name.endswith(".s") and entry.is_file())[:a.limit]
except OSError as e:
print(f"ERROR: cannot list {a.src}: {e.strerror or e}", file=sys.stderr)
return 2
kinds, raw, n_ins, no_enc = Counter(), Counter(), 0, 0
for path in files:
try:
info = parse_file(path)
except OSError as e:
print(f"ERROR: cannot read {e.filename or path}: {e.strerror or e}", file=sys.stderr)
return 2
for ins in info["insns"]:
n_ins += 1
no_enc += ins["enc"] is None
for a in ins["args"]:
kinds[a["k"]] += 1
if a["k"] == "raw":
raw[a["t"]] += 1
print(f"{len(files)} shaders, {n_ins:,} instructions, {no_enc} without encoding bytes")
print("operand kinds:", dict(kinds.most_common()))
print("unparsed (raw) operands:", raw.most_common(15))
if __name__ == "__main__":
try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
sys.stdout.reconfigure(errors="replace")
except (AttributeError, ValueError, OSError):
pass
sys.exit(main())