1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
|
"""SHADER-33: which hardware vertex-shader layout the corpus uses (legacy VS or NGG), and which input VGPRs it reads.
python -I scripts/vs_input_survey.py <work>/shaders/dxbc [--json OUT]
Reads <dxbc>/index.json (stage per shader) and <dxbc>/disasm/<name>.s (shader_disasm.py) for every vertex shader and
prints counts only:
- NGG markers: `exp prim` (primitive export), `s_sendmsg` (NGG needs GS_ALLOC_REQ) and `v_mbcnt` (NGG thread ids).
A legacy (non-NGG) hardware VS has none of them and exports `pos0` / `param` only.
- Registers read before written, straight-line, from the start of the program: the same rule as #240's
scripts/audit_shader4_regs.py (by @eIBart0) uses for CS/MS/GS. In the legacy GFX10 VS layout (Mesa
radv_shader_args.c, declare_vs_input_vgprs, not is_ngg) v0 = vertex id, v1 unused, v2 = primitive id,
v3 = instance id; in an NGG VS merged with GS the VS inputs start at v5 (vertex id) / v8 (instance id).
- The fetch call: `s_swappc_b64 s[4:5], s[4:5]` at the start of a VS calls the driver's fetch program, which reads
v0 itself and leaves the attributes in v4 and up.
Standard library only. Nothing from the game is printed or written beyond counts.
"""
import argparse
import json
import ntpath
import os
import posixpath
import re
import sys
import tempfile
from collections import Counter
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, "tools"))
from file_mode import published_mode # noqa: E402
from replace_retry import replace as replace_retry # noqa: E402
from report_paths import same_report_path # noqa: E402
import shader_ir # noqa: E402
from shader_meta import SGPR_RMW # noqa: E402
NO_DEST_OPS = ("s_cmp", "s_bitcmp", "v_cmpx", "s_set", "s_rfe", "s_branch", "s_cbranch", "s_waitcnt", "s_barrier",
"s_nop", "s_endpgm", "s_sendmsg", "s_sleep", "exp", "buffer_store", "tbuffer_store", "global_store",
"flat_store", "scratch_store", "s_store", "s_buffer_store", "image_store", "ds_write")
DUAL_DST_VALU = ("v_mad_u64_u32", "v_mad_i64_i32", "v_div_scale_f32", "v_div_scale_f64")
DS_RETURNING = ("ds_read", "ds_bpermute", "ds_permute", "ds_swizzle", "ds_consume", "ds_append", "ds_ordered_count")
PRIM_EXPORT = re.compile(r"^\s*exp\s+prim\b", re.M)
POS0_EXPORT = re.compile(r"^\s*exp\s+pos0\b", re.M)
PARAM_EXPORT = re.compile(r"^\s*exp\s+param\d+\b", re.M)
SENDMSG = re.compile(r"^\s*s_sendmsg\b", re.M)
MBCNT = re.compile(r"\bv_mbcnt_(lo|hi)_u32_b32\b")
FETCH_CALL = re.compile(r"^\s*s_swappc_b64\s+s\[4:5\],\s*s\[4:5\]", re.M)
def base_op(op):
for sfx in ("_e32", "_e64", "_sdwa", "_dpp"):
if op.endswith(sfx):
return op[:-len(sfx)]
return op
def _expand_regs(a):
"""Return ('s' | 'v', iterable of register indices) for an operand, or (None, ())."""
k = a["k"]
if k == "sgpr":
return "s", range(a["r"], a["r"] + a.get("n", 1))
if k == "vgpr":
return "v", range(a["r"], a["r"] + a.get("n", 1))
if k == "slist":
return "s", (r for r in a["r"] if isinstance(r, int))
if k == "vlist":
return "v", (r for r in a["r"] if isinstance(r, int))
return None, ()
def read_before_write(insns):
"""(SGPRs, VGPRs) read before any write, straight-line from the first instruction."""
written_s, written_v, read_s, read_v = set(), set(), set(), set()
for ins in insns:
op, args = base_op(ins["op"]), ins["args"]
if not args:
continue
mods = ins.get("mods", ())
is_gf_atomic = op.startswith(("global_atomic_", "flat_atomic_"))
is_bi_atomic = op.startswith(("buffer_atomic_", "image_atomic_"))
is_ds_no_dest = op.startswith("ds_") and not op.startswith(DS_RETURNING) and "_rtn" not in op
no_dest = (
op.startswith(NO_DEST_OPS)
or ((is_gf_atomic or is_bi_atomic) and "glc" not in mods)
or is_ds_no_dest
or (op.startswith("v_cmp_") and len(args) <= 2)
)
if no_dest:
dsts, srcs = [], args
elif op == "v_swap_b32" and len(args) >= 2:
dsts, srcs = args[:2], args[:2]
elif (op.startswith("v_") and ("_co_" in op or op in DUAL_DST_VALU)
and len(args) >= 2 and args[1]["k"] in ("sgpr", "special", "slist")
# the short form v_add_co_ci_u32 vD, src0, src1 (also sub/subrev): carry out and in are an
# implicit VCC, and args[1] is src0, a read
and not (op.endswith("_co_ci_u32") and len(args) == 3)):
dsts, srcs = args[:2], args[2:] # vdst + scalar carry/scale-out dst
else:
dst_read = (
op in SGPR_RMW or "fmac" in op or "mac_" in op
or op.startswith(("v_dot2c_", "v_dot4c_", "v_dot8c_"))
or op == "v_writelane_b32" or is_bi_atomic
)
dsts, srcs = args[:1], (args[:1] if dst_read else []) + args[1:]
for a in srcs:
kind, regs = _expand_regs(a)
for r in regs:
if kind == "s" and r not in written_s:
read_s.add(r)
elif kind == "v" and r not in written_v:
read_v.add(r)
for a in dsts:
kind, regs = _expand_regs(a)
if kind == "s":
written_s.update(regs)
elif kind == "v":
written_v.update(regs)
return read_s, read_v
def _safe_shader_stem(value):
"""Validate an index.json 'file' basename against path traversal and return its stem."""
if (
not isinstance(value, str)
or not value
or any(ord(c) < 32 or ord(c) == 127 for c in value)
or ":" in value
or "/" in value
or "\\" in value
or ntpath.splitdrive(value)[0]
or ntpath.basename(value) != value
or posixpath.basename(value) != value
):
raise ValueError(f"index.json has an invalid shader filename: {value!r}")
stem = os.path.splitext(value)[0]
if not stem or stem in (".", ".."):
raise ValueError(f"index.json has an invalid shader filename: {value!r}")
return stem
def _write_json_atomic(path, payload):
"""Write JSON to a sibling staging file and rename atomically, cleaning up read-only staging on error."""
dest = os.path.abspath(path)
parent = os.path.dirname(dest) or "."
staged = None
try:
with tempfile.NamedTemporaryFile(
mode="w", encoding="utf-8", newline="\n", delete=False,
dir=parent, prefix=".vs_input_survey-", suffix=".tmp",
) as f:
staged = f.name
json.dump(payload, f, indent=1)
f.write("\n")
os.chmod(staged, published_mode(dest))
replace_retry(staged, dest)
staged = None
finally:
if staged is not None:
try:
os.chmod(staged, 0o600)
except OSError:
pass
try:
os.unlink(staged)
except OSError:
pass
def _survey_detail(dxbc_dir):
with open(os.path.join(dxbc_dir, "index.json"), encoding="utf-8-sig") as f:
index = json.load(f)
if not isinstance(index, list) or not all(isinstance(e, dict) for e in index):
raise ValueError("index.json is not a list of shader entries")
names = [_safe_shader_stem(e.get("file")) for e in index if e.get("stage") == "vs"]
markers, vgprs, families = Counter(), Counter(), Counter()
missing = 0
disasm_paths = []
for n in names:
path = os.path.join(dxbc_dir, "disasm", n + ".s")
if not os.path.isfile(path):
missing += 1
continue
disasm_paths.append(path)
with open(path, encoding="utf-8", errors="replace") as f:
text = f.read()
_, read_v = read_before_write(shader_ir.parse_file(path)["insns"])
for r in read_v:
if r < 16:
vgprs[f"v{r}"] += 1
fetch = bool(FETCH_CALL.search(text))
markers["exp prim"] += bool(PRIM_EXPORT.search(text))
markers["s_sendmsg"] += bool(SENDMSG.search(text))
markers["v_mbcnt"] += bool(MBCNT.search(text))
markers["exp pos0"] += bool(POS0_EXPORT.search(text))
markers["exp param"] += bool(PARAM_EXPORT.search(text))
markers["fetch call"] += fetch
if fetch:
families["fetch call, attributes from v4 up"] += 1
elif 0 in read_v:
families["reads v0 (vertex id)" + (" and v3 (instance id)" if 3 in read_v else "")] += 1
else:
families["reads neither v0 nor a fetch call"] += 1
result = {"vertex_shaders": len(names), "missing_listings": missing, "markers": dict(markers),
"input_vgprs_read": dict(sorted(vgprs.items(), key=lambda kv: int(kv[0][1:]))),
"families": dict(families)}
return result, disasm_paths
def survey(dxbc_dir):
return _survey_detail(dxbc_dir)[0]
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("dxbc", help="<work>/shaders/dxbc from make_game.py")
ap.add_argument("--json", help="also write the counts as JSON")
a = ap.parse_args(argv)
index_path = os.path.join(a.dxbc, "index.json")
if a.json:
if os.path.isdir(a.json):
print(f"vs_input_survey: error: --json is a directory: {a.json}", file=sys.stderr)
return 2
if same_report_path(a.json, index_path) or same_report_path(a.json, a.dxbc):
print(f"vs_input_survey: error: --json would overwrite the input {index_path}", file=sys.stderr)
return 2
try:
r, disasm_paths = _survey_detail(a.dxbc)
except (OSError, ValueError) as e: # missing or non-folder <dxbc>, unreadable, non-UTF-8 or malformed index.json
print(f"vs_input_survey: error: cannot read {index_path}: {e}", file=sys.stderr)
return 2
if a.json:
for src_path in disasm_paths:
if same_report_path(a.json, src_path):
print(f"vs_input_survey: error: --json would overwrite the input {src_path}", file=sys.stderr)
return 2
m = r["markers"]
print(f"{r['vertex_shaders']} vertex shaders ({r['missing_listings']} without a listing)")
print(f"NGG markers: exp prim {m.get('exp prim', 0)}, s_sendmsg {m.get('s_sendmsg', 0)}, v_mbcnt {m.get('v_mbcnt', 0)}")
print(f"exports: pos0 {m.get('exp pos0', 0)}, param {m.get('exp param', 0)}; fetch call {m.get('fetch call', 0)}")
print("input VGPRs read before written (v0..v15):", r["input_vgprs_read"])
print("families:", r["families"])
legacy = not (m.get("exp prim") or m.get("s_sendmsg") or m.get("v_mbcnt"))
print("layout:", "legacy (non-NGG) VS" if legacy else "NGG markers present: check the VS input layout")
if a.json:
try:
_write_json_atomic(a.json, r)
except OSError as e:
print(f"vs_input_survey: error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr)
return 2
return 0
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())
|