upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/tools/root_sig_contract.py
diff options
context:
space:
mode:
Diffstat (limited to 'tools/root_sig_contract.py')
-rw-r--r--tools/root_sig_contract.py155
1 files changed, 155 insertions, 0 deletions
diff --git a/tools/root_sig_contract.py b/tools/root_sig_contract.py
new file mode 100644
index 000000000..e1a46ae86
--- /dev/null
+++ b/tools/root_sig_contract.py
@@ -0,0 +1,155 @@
1r"""Reconcile a root signature against the translator's user-SGPR reads (stdlib only).
2
3A shader is identified by its index.json entry (user_sgpr_reads from
4tools/shader_meta.py); the candidate root signature is a hand-written JSON
5file in this tool's format (see --example), never game data.
6
7Usage:
8 python -I tools/root_sig_contract.py <index.json> --rootsig <sig.json>
9 python -I tools/root_sig_contract.py <index.json> --rootsig <sig.json> --cluster
10 python -I tools/root_sig_contract.py --example
11
12Exit code is 0 when every read is compatible, 1 on the first contradiction
13(hard fail: a mismatch means every draw/dispatch with that pair is corrupt).
14"""
15import argparse
16import json
17import sys
18
19# Packing order mirrors runtime/src/root_signature.{h,cpp}: constants take
20# NumValues dwords, root descriptors and tables take 2 (VA lo/hi), static
21# samplers take none.
22KIND_TO_TYPES = {
23 "const32": {"constants"},
24 "ptr64_lo": {"descriptor", "table"},
25 "ptr64_hi": {"descriptor", "table"},
26 "ptr32_lo": {"descriptor", "table"},
27 "vsharp": {"descriptor", "table"},
28 "tsharp": {"descriptor", "table"},
29 "ssharp": {"descriptor", "table"},
30}
31
32
33def pack_layout(sig):
34 """Lay out root params into 32 dwords. Returns (dwords, error).
35
36 dwords[i] = {"param": index, "sub": sub-dword, "ptype": ptype}.
37 error is set (and dwords empty) on spill, cost overflow or bad input:
38 refuse, never truncate.
39 """
40 dwords = []
41 cost = 0
42 params = [dict(p) for p in sig.get("params", [])] # normalized copy; input untouched
43 if len(params) > 64:
44 return [], "more than 64 root parameters"
45 for index, p in enumerate(params):
46 ptype = p.get("type", "")
47 if ptype == "constants":
48 count = p.get("count", 0)
49 if not isinstance(count, int) or count < 1:
50 return [], f"param {index}: constants need count >= 1"
51 width, cost_add = count, count
52 elif ptype in ("cbv", "srv", "uav"):
53 width, cost_add = 2, 2
54 ptype = "descriptor"
55 elif ptype == "table":
56 width, cost_add = 2, 1
57 else:
58 return [], f"param {index}: unknown type {ptype!r}"
59 cost += cost_add
60 if cost > 64:
61 return [], "exceeds the 64-dword D3D12 cost limit"
62 if len(dwords) + width > 32:
63 return [], "needs more than 32 user SGPRs (spill unsupported)"
64 for sub in range(width):
65 dwords.append({"param": index, "sub": sub, "ptype": ptype})
66 return dwords, ""
67
68
69def reconcile(shader_reads, dwords):
70 """Check one shader's reads against the packed layout.
71
72 Returns a list of contradiction strings (empty = compatible).
73 """
74 issues = []
75 by_sgpr = {}
76 for read in shader_reads:
77 by_sgpr.setdefault(read["sgpr"], []).append(read["kind"])
78 for sgpr in sorted(by_sgpr):
79 kinds = by_sgpr[sgpr]
80 if sgpr >= len(dwords):
81 issues.append(f"s{sgpr} read but layout has {len(dwords)} dwords")
82 continue
83 slot = dwords[sgpr]
84 for kind in kinds:
85 allowed = KIND_TO_TYPES.get(kind)
86 if allowed is None:
87 issues.append(f"s{sgpr}: unknown read kind {kind!r}")
88 elif slot["ptype"] not in allowed:
89 issues.append(
90 f"s{sgpr} ({kind}) incompatible with param "
91 f"{slot['param']} ({slot['ptype']})")
92 if kind == "ptr64_hi":
93 lo = dwords[sgpr - 1] if sgpr > 0 else None
94 if slot["sub"] != 1 or lo is None or lo["param"] != slot["param"] \
95 or lo["sub"] != 0:
96 issues.append(f"s{sgpr} (ptr64_hi) without paired lo dword")
97 return issues
98
99
100def cluster(shaders):
101 """Group shaders by read-set shape. Returns [(shape, count, names)]."""
102 groups = {}
103 for name, entry in shaders.items():
104 reads = entry.get("user_sgpr_reads", [])
105 shape = tuple(sorted((r["sgpr"], r["kind"]) for r in reads))
106 groups.setdefault(shape, []).append(name)
107 ranked = sorted(groups.items(), key=lambda kv: -len(kv[1]))
108 return [(shape, len(names), names) for shape, names in ranked]
109
110
111def main():
112 ap = argparse.ArgumentParser(description="Root-signature vs shader-reads reconciler.")
113 ap.add_argument("index", nargs="?", help="spirv/index.json")
114 ap.add_argument("--rootsig", default=None, help="hand-written root-signature JSON")
115 ap.add_argument("--cluster", action="store_true", help="print read-set shape clustering")
116 ap.add_argument("--example", action="store_true", help="print an empty hand-written sig template")
117 a = ap.parse_args()
118 if a.example:
119 print(json.dumps({"version": "1.1", "flags": 0, "params": [
120 {"type": "constants", "count": 4, "visibility": "all"},
121 {"type": "cbv", "visibility": "vertex"},
122 {"type": "table", "ranges": [{"kind": "srv", "count": 8}],
123 "visibility": "pixel"}],
124 "static_samplers": []}, indent=2))
125 return 0
126 if not a.index or not a.rootsig:
127 ap.error("index.json and --rootsig are required (or --example)")
128 with open(a.index, encoding="utf-8") as f:
129 index = json.load(f)
130 with open(a.rootsig, encoding="utf-8") as f:
131 sig = json.load(f)
132 dwords, error = pack_layout(sig)
133 if error:
134 print(f"root signature refused: {error}")
135 return 1
136 print(f"packed {len(dwords)} dwords from {len(sig.get('params', []))} params")
137 bad = 0
138 for name in sorted(index):
139 reads = index[name].get("user_sgpr_reads", [])
140 issues = reconcile(reads, dwords)
141 if issues:
142 bad += 1
143 print(f"CONTRADICTION {name}:")
144 for issue in issues:
145 print(f" - {issue}")
146 if a.cluster:
147 print("read-set shapes (shape -> shaders):")
148 for shape, count, names in cluster(index)[:20]:
149 print(f" {count:6} {shape} e.g. {names[0]}")
150 print(f"{len(index)} shaders: {len(index) - bad} compatible, {bad} contradictory")
151 return 1 if bad else 0
152
153
154if __name__ == "__main__":
155 sys.exit(main())