diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cc905cb1bc..e6f7bfd5a8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -52,3 +52,7 @@ jobs: - name: Build and test shell: pwsh run: ./scripts/test.ps1 --skip test_title_runs_and_game_folder_is_untouched + + - name: Check DXIL semantic inspector + shell: pwsh + run: python -B scripts/test_dxil_semantics.py --require-dxc diff --git a/scripts/inspect_dxil_semantics.py b/scripts/inspect_dxil_semantics.py new file mode 100644 index 0000000000..11ca74c930 --- /dev/null +++ b/scripts/inspect_dxil_semantics.py @@ -0,0 +1,318 @@ +"""Print stable DXIL container semantics using DXC's disassembler. + +Usage: + python scripts/inspect_dxil_semantics.py shader.dxil [other.dxil ...] [--dxc PATH] + +The JSON intentionally omits hashes, resource names, SSA names, and instruction order so +DXC and XCL containers can be compared without harmless code-generation differences. +`disassembler_dxc_version` identifies the tool used for inspection, not the container producer. +Multiple-entry-point containers are rejected because this first version reports one entry. +""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import re +import shutil +import struct +import subprocess +import sys + + +STAGE_NAMES = { + "vs": "vertex", + "hs": "hull", + "ds": "domain", + "gs": "geometry", + "ps": "pixel", + "cs": "compute", + "ms": "mesh", + "as": "amplification", + "lib": "library", + "raygeneration": "raygeneration", + "intersection": "intersection", + "anyhit": "anyhit", + "closesthit": "closesthit", + "miss": "miss", + "callable": "callable", +} +OVERLOADS = {"i1", "i8", "i16", "i32", "i64", "f16", "f32", "f64", "void"} + + +def find_dxc(explicit: str | None = None) -> Path: + if explicit: + candidate = Path(explicit) + if candidate.is_file(): + return candidate.resolve() + raise FileNotFoundError(f"specified dxc.exe does not exist: {candidate}") + + dxc_dir = os.environ.get("XCL_DXC_DIR") + if dxc_dir: + candidate = Path(dxc_dir) / "dxc.exe" + if candidate.is_file(): + return candidate.resolve() + raise FileNotFoundError(f"XCL_DXC_DIR does not contain dxc.exe: {candidate}") + + candidates: list[Path] = [] + for name in ("dxc.exe", "dxc"): + found = shutil.which(name) + if found: + candidates.append(Path(found)) + + for root in ( + Path(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")) / "Windows Kits/10/bin", + Path(os.environ.get("ProgramFiles", r"C:\Program Files")) / "Windows Kits/10/bin", + ): + versions = [p for p in root.iterdir() if p.is_dir()] if root.is_dir() else [] + versions.sort(key=lambda p: tuple(int(n) for n in re.findall(r"\d+", p.name)), reverse=True) + candidates.extend(p / "x64/dxc.exe" for p in versions) + + for candidate in candidates: + if candidate.is_file(): + return candidate.resolve() + raise FileNotFoundError("dxc.exe not found; pass --dxc or set XCL_DXC_DIR") + + +def container_feature_flags(data: bytes) -> int: + """Read the SFI0 feature-bit mask from a DXBC/DXIL container.""" + if len(data) < 32 or data[:4] != b"DXBC": + raise ValueError("input is not a DXBC/DXIL container") + total_size = struct.unpack_from(" len(data) or 32 + chunk_count * 4 > total_size: + raise ValueError("invalid DXBC container header") + for index in range(chunk_count): + offset = struct.unpack_from(" total_size: + raise ValueError("DXBC chunk offset is outside the container") + size = struct.unpack_from(" total_size: + raise ValueError("DXBC chunk extends past the container") + if data[offset : offset + 4] == b"SFI0": + if size != 8: + raise ValueError(f"unexpected SFI0 size: {size}") + return struct.unpack_from(" dict[int, str]: + return {int(number): body for number, body in re.findall(r"^!(\d+)\s*=\s*!\{(.*)\}\s*$", text, re.M)} + + +def _root_node(text: str, name: str) -> int | None: + match = re.search(rf"^{re.escape(name)}\s*=\s*!\{{!(\d+)\}}\s*$", text, re.M) + return int(match.group(1)) if match else None + + +def _entry_point_nodes(text: str) -> list[int]: + match = re.search(r"^!dx\.entryPoints\s*=\s*!\{([^}]*)\}\s*$", text, re.M) + return [int(value) for value in re.findall(r"!(\d+)", match.group(1))] if match else [] + + +def _node_strings(node: str) -> list[str]: + return re.findall(r'!"((?:[^"\\]|\\.)*)"', node) + + +def _node_ints(node: str, width: int | None = None) -> list[int]: + pattern = r"\bi(?:32|64)\s+(-?\d+)" if width is None else rf"\bi{width}\s+(-?\d+)" + return [int(value) for value in re.findall(pattern, node)] + + +def _resource_bindings(text: str) -> list[dict[str, object]]: + row = re.compile( + r"^;\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+((?:cb|[btsu])\d+(?:,space\d+)?)(?:\s+(\S+)|(unbounded))\s*$", + re.I, + ) + resources = [] + for line in text.splitlines(): + match = row.match(line) + if not match: + continue + _, resource_type, format_name, dimension, _, binding, spaced_count, attached_unbounded = match.groups() + count = spaced_count or attached_unbounded + register = binding.split(",", 1)[0].lower() + if register.startswith(("cb", "b")): + kind = "CBUFFER" + elif register.startswith("s"): + kind = "SAMPLER" + elif register.startswith("u"): + kind = "UAV" + else: + kind = "TBUFFER" if "tbuffer" in (resource_type.lower(), dimension.lower()) else "SRV" + resources.append({ + "kind": kind, + "format": format_name, + "dimension": dimension, + "hlsl_binding": binding, + "count": int(count) if count.isdigit() else count, + }) + return sorted( + resources, + key=lambda item: ( + str(item["kind"]), + str(item["hlsl_binding"]), + str(item["format"]), + str(item["dimension"]), + ), + ) + + +def _dx_ops(text: str) -> list[dict[str, object]]: + counts: dict[tuple[str, str | None, int], int] = {} + call_re = re.compile(r"\bcall\b[^\n]*@dx\.op\.([A-Za-z_][\w.]*)\(") + for line in text.splitlines(): + match = call_re.search(line) + if not match: + continue + symbol = match.group(1) + opcode_match = re.search(r"\(i32\s+(\d+)", line[match.end() - 1 :]) + if not opcode_match: + continue + parts = symbol.rsplit(".", 1) + if len(parts) == 2 and parts[1] in OVERLOADS: + name, overload = parts[0], parts[1] + else: + name, overload = symbol, None + key = (name, overload, int(opcode_match.group(1))) + counts[key] = counts.get(key, 0) + 1 + return [ + {"name": name, "overload": overload, "opcode": opcode, "calls": count} + for (name, overload, opcode), count in sorted(counts.items(), key=lambda item: item[0]) + ] + + +def _resource_annotations(text: str) -> list[dict[str, object]]: + result = [] + for line in text.splitlines(): + if "@dx.op.annotateHandle(" not in line: + continue + properties = re.search(r"ResourceProperties\s*\{\s*i32\s+(-?\d+)\s*,\s*i32\s+(-?\d+)\s*\}", line) + if not properties: + continue + kind = re.search(r"resource:\s*([A-Za-z0-9_]+)", line) + result.append({ + "resource_type": kind.group(1) if kind else None, + "properties": [int(properties.group(1)), int(properties.group(2))], + }) + return sorted(result, key=lambda item: (str(item["resource_type"]), item["properties"])) + + +def _required_features(text: str) -> list[str]: + lines = text.splitlines() + for index, line in enumerate(lines): + if "Note: shader requires additional functionality:" not in line: + continue + features = [] + for candidate in lines[index + 1 :]: + if candidate.startswith("; Input signature:"): + break + if candidate.startswith(";"): + value = candidate[1:].strip() + if value: + features.append(value) + return sorted(set(features)) + return [] + + +def _entry_metadata(text: str, nodes: dict[int, str]) -> dict[str, object]: + roots = _entry_point_nodes(text) + if len(roots) > 1: + raise ValueError("DXIL containers with multiple entry points are not supported") + if not roots or roots[0] not in nodes: + return {} + root = roots[0] + entry = nodes[root] + function_match = re.search(r"\*\s*@([A-Za-z_.$][\w.$]*)", entry) + names = _node_strings(entry) + entry: dict[str, object] = { + "function": function_match.group(1) if function_match else None, + "name": names[0] if names else None, + } + refs = [int(value) for value in re.findall(r"!(\d+)", nodes[root])] + if refs: + props = nodes.get(refs[-1], "") + flags = re.search(r"i32\s+0\s*,\s*i64\s+(\d+)", props) + group = re.search(r"i32\s+4\s*,\s*!(\d+)", props) + if flags: + entry["shader_flags"] = int(flags.group(1)) + if group: + entry["thread_group_size"] = _node_ints(nodes.get(int(group.group(1)), ""), 32) + return entry + + +def inspect_dxil(path: Path, dxc: Path) -> dict[str, object]: + path = path.resolve(strict=True) + data = path.read_bytes() + dump = subprocess.run([str(dxc), "-dumpbin", str(path)], check=True, capture_output=True, text=True).stdout + nodes = _metadata(dump) + + def version(field: str) -> list[int] | None: + node_id = _root_node(dump, field) + return _node_ints(nodes.get(node_id, ""), 32) if node_id is not None else None + + model_id = _root_node(dump, "!dx.shaderModel") + model_node = nodes.get(model_id, "") if model_id is not None else "" + model_values = _node_ints(model_node, 32) + model_strings = _node_strings(model_node) + profile = None + stage = None + if model_strings and len(model_values) >= 2: + stage_code = model_strings[0] + profile = f"{stage_code}_{model_values[0]}_{model_values[1]}" + stage = STAGE_NAMES.get(stage_code, stage_code) + + triple_match = re.search(r'^target triple = "([^"]+)"', dump, re.M) + layout_match = re.search(r'^target datalayout = "([^"]+)"', dump, re.M) + threads = re.search(r"NumThreads=\((\d+),(\d+),(\d+)\)", dump) + entry = _entry_metadata(dump, nodes) + if threads and "thread_group_size" not in entry: + entry["thread_group_size"] = [int(value) for value in threads.groups()] + + sfi0 = container_feature_flags(data) + return { + "input": path.name, + "stage": stage, + "shader_model": profile, + "dxil_module_version": version("!dx.version"), + "validator_version": version("!dx.valver"), + "entry": entry, + "sfi0_feature_flags": f"0x{sfi0:016x}", + "required_features": _required_features(dump), + "dx_ops": _dx_ops(dump), + "resource_bindings": _resource_bindings(dump), + "resource_annotations": _resource_annotations(dump), + "target_triple": triple_match.group(1) if triple_match else None, + "data_layout": layout_match.group(1) if layout_match else None, + } + + +def dxc_version(dxc: Path) -> str: + result = subprocess.run([str(dxc), "--version"], check=True, capture_output=True, text=True) + text = result.stdout + result.stderr + match = re.search(r"(? int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("containers", nargs="+", type=Path, help="DXIL container(s) to inspect") + parser.add_argument("--dxc", help="path to dxc.exe (or use XCL_DXC_DIR / Windows SDK)") + args = parser.parse_args() + try: + dxc = find_dxc(args.dxc) + results = [inspect_dxil(path, dxc) for path in args.containers] + tool_version = dxc_version(dxc) + except (OSError, ValueError, subprocess.CalledProcessError) as exc: + print(f"dxil semantics: {exc}", file=sys.stderr) + return 1 + print(json.dumps({"schema_version": 1, "disassembler_dxc_version": tool_version, "shaders": results}, indent=2, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/test_dxil_semantics.py b/scripts/test_dxil_semantics.py new file mode 100644 index 0000000000..83e094b70a --- /dev/null +++ b/scripts/test_dxil_semantics.py @@ -0,0 +1,131 @@ +"""Compile and inspect the minimal DXIL semantic-audit compute fixture.""" + +from __future__ import annotations + +import argparse +import importlib.util +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + + +HERE = Path(__file__).resolve().parent +FIXTURE = HERE.parent / "tests/data/dxil_semantic/compute_store.hlsl" +RESOURCE_FIXTURE = HERE.parent / "tests/data/dxil_semantic/resource_bindings.hlsl" +SPEC = importlib.util.spec_from_file_location("inspect_dxil_semantics", HERE / "inspect_dxil_semantics.py") +assert SPEC and SPEC.loader +INSPECTOR = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(INSPECTOR) + + +class SemanticFixtureTests(unittest.TestCase): + def test_explicit_missing_dxc_does_not_fall_back(self) -> None: + with self.assertRaisesRegex(FileNotFoundError, "specified dxc.exe does not exist"): + INSPECTOR.find_dxc(str(HERE / "missing-dxc.exe")) + + def test_invalid_dxc_directory_does_not_fall_back(self) -> None: + with mock.patch.dict("os.environ", {"XCL_DXC_DIR": str(HERE / "missing-dxc-dir")}): + with self.assertRaisesRegex(FileNotFoundError, "XCL_DXC_DIR does not contain dxc.exe"): + INSPECTOR.find_dxc() + + def test_multiple_entry_points_are_rejected(self) -> None: + with self.assertRaisesRegex(ValueError, "multiple entry points"): + INSPECTOR._entry_metadata("!dx.entryPoints = !{!1, !2}", {1: "!{}", 2: "!{}"}) + + @classmethod + def setUpClass(cls) -> None: + try: + cls.dxc = INSPECTOR.find_dxc(DXC_OVERRIDE) + except FileNotFoundError as exc: + if REQUIRE_DXC: + raise + raise unittest.SkipTest(str(exc)) from exc + cls.temp = tempfile.TemporaryDirectory(prefix="xcl-dxil-semantics-") + cls.container = Path(cls.temp.name) / "compute_store.dxil" + subprocess.run( + [str(cls.dxc), "-E", "main", "-T", "cs_6_6", "-O3", "-Fo", str(cls.container), str(FIXTURE)], + check=True, + capture_output=True, + text=True, + ) + cls.dump = subprocess.run( + [str(cls.dxc), "-dumpbin", str(cls.container)], + check=True, + capture_output=True, + text=True, + ).stdout + cls.report = INSPECTOR.inspect_dxil(cls.container, cls.dxc) + + @classmethod + def tearDownClass(cls) -> None: + if hasattr(cls, "temp"): + cls.temp.cleanup() + + def test_stage_model_versions_and_entry_metadata(self) -> None: + self.assertEqual(self.report["stage"], "compute") + self.assertEqual(self.report["shader_model"], "cs_6_6") + self.assertEqual(self.report["dxil_module_version"], [1, 6]) + self.assertEqual(len(self.report["validator_version"]), 2) + self.assertEqual(self.report["entry"]["function"], "main") + self.assertEqual(self.report["entry"]["name"], "main") + self.assertIn("shader_flags", self.report["entry"]) + self.assertEqual(self.report["entry"]["thread_group_size"], [8, 4, 2]) + + def test_entry_metadata_contains_thread_group_size(self) -> None: + nodes = INSPECTOR._metadata(self.dump) + entry = INSPECTOR._entry_metadata(self.dump, nodes) + self.assertEqual(entry["thread_group_size"], [8, 4, 2]) + + def test_features_operations_and_resource_semantics(self) -> None: + self.assertEqual(self.report["sfi0_feature_flags"], "0x0000000000004000") + self.assertIn("Wave level operations", self.report["required_features"]) + operations = {(op["name"], op["overload"]): op["opcode"] for op in self.report["dx_ops"]} + self.assertEqual(operations["waveActiveOp", "i32"], 119) + self.assertEqual(operations["rawBufferStore", "i32"], 140) + resources = self.report["resource_bindings"] + self.assertEqual(len(resources), 1) + self.assertEqual(resources[0]["kind"], "UAV") + self.assertEqual(resources[0]["hlsl_binding"], "u0") + self.assertEqual(resources[0]["count"], 1) + self.assertIn( + {"resource_type": "RWByteAddressBuffer", "properties": [4107, 0]}, + self.report["resource_annotations"], + ) + + def test_resource_bindings_include_constant_buffers_textures_and_tbuffers(self) -> None: + container = Path(self.temp.name) / "resource_bindings.dxil" + subprocess.run( + [str(self.dxc), "-E", "main", "-T", "cs_6_6", "-O3", "-Fo", str(container), str(RESOURCE_FIXTURE)], + check=True, + capture_output=True, + text=True, + ) + bindings = INSPECTOR.inspect_dxil(container, self.dxc)["resource_bindings"] + self.assertEqual( + {(entry["kind"], entry["hlsl_binding"], entry["count"]) for entry in bindings}, + {("CBUFFER", "cb2,space3", 1), ("SRV", "t1,space3", 2), ("SRV", "t11,space15", "unbounded"), ("SAMPLER", "s4,space3", 1), ("UAV", "u5,space3", 1), ("TBUFFER", "t2,space12", 1)}, + ) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--dxc", help="path to dxc.exe; otherwise use XCL_DXC_DIR or Windows SDK") + parser.add_argument("--require-dxc", action="store_true", help="fail instead of skipping if dxc.exe is unavailable") + args = parser.parse_args() + global DXC_OVERRIDE + DXC_OVERRIDE = args.dxc + global REQUIRE_DXC + REQUIRE_DXC = args.require_dxc + suite = unittest.defaultTestLoader.loadTestsFromTestCase(SemanticFixtureTests) + result = unittest.TextTestRunner(verbosity=2).run(suite) + return 0 if result.wasSuccessful() else 1 + + +DXC_OVERRIDE: str | None = None +REQUIRE_DXC = False + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/data/dxil_semantic/compute_store.hlsl b/tests/data/dxil_semantic/compute_store.hlsl new file mode 100644 index 0000000000..262db1076a --- /dev/null +++ b/tests/data/dxil_semantic/compute_store.hlsl @@ -0,0 +1,6 @@ +RWByteAddressBuffer output : register(u0, space0); + +[numthreads(8, 4, 2)] +void main(uint3 dispatch_id : SV_DispatchThreadID) { + output.Store(dispatch_id.x * 4, WaveActiveSum(dispatch_id.x)); +} diff --git a/tests/data/dxil_semantic/resource_bindings.hlsl b/tests/data/dxil_semantic/resource_bindings.hlsl new file mode 100644 index 0000000000..a53757f5a8 --- /dev/null +++ b/tests/data/dxil_semantic/resource_bindings.hlsl @@ -0,0 +1,11 @@ +cbuffer Params : register(b2, space3) { float gain; }; +Texture2D InputTex[2] : register(t1, space3); +Texture2D Unbounded[] : register(t11, space15); +SamplerState InputSampler : register(s4, space3); +RWTexture2D OutputTex : register(u5, space3); +tbuffer Legacy : register(t2, space12) { float4 legacyValue; }; + +[numthreads(1, 1, 1)] +void main(uint3 tid : SV_DispatchThreadID) { + OutputTex[tid.xy] = InputTex[NonUniformResourceIndex(tid.x & 1)].SampleLevel(InputSampler, float2(0.5, 0.5), 0) * gain + legacyValue + Unbounded[NonUniformResourceIndex(tid.x)].Load(int3(0, 0, 0)); +}