From 0951b67fb7fe62550bf274442a1b187a6e469938 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:12:30 +0100 Subject: [PATCH 1/3] shader: add a native translator corpus hash check --- docs/experiments/translator-corpus.md | 31 ++++ tests/cmake/translator_corpus.cmake | 8 + tests/native_compile_dxil_refusals_check.py | 26 ++- tests/native_compile_dxil_watch_check.py | 11 +- tests/native_direct_mesh_check.py | 18 +- tests/translator_corpus_hash.py | 177 ++++++++++++++++++++ 6 files changed, 253 insertions(+), 18 deletions(-) create mode 100644 docs/experiments/translator-corpus.md create mode 100644 tests/cmake/translator_corpus.cmake create mode 100644 tests/translator_corpus_hash.py diff --git a/docs/experiments/translator-corpus.md b/docs/experiments/translator-corpus.md new file mode 100644 index 0000000000..c4b43718d7 --- /dev/null +++ b/docs/experiments/translator-corpus.md @@ -0,0 +1,31 @@ +# Compare native translator output + +The source-built corpus exercises graphics pairs, RTV variants, compute requests, +and raw mesh shaders. The TSV records one row per request key. It contains the +status and either a SHA-256 fingerprint of the published DXIL or the refusal reason. +For a request with several stages, the fingerprint hashes each stage name, a NUL +byte, and its binary SHA-256 digest in stage name order. + +Build `compile_dxil` in two separate build directories with the same preset and +DXC version. From the checkout containing the corpus script, use that same copy +of the script and the same DXC directory for both builds. + +```powershell +python -B tests/translator_corpus_hash.py $baseCompiler $sdk --out out/translator-base.tsv +python -B tests/translator_corpus_hash.py $headCompiler $sdk --out out/translator-head.tsv +git diff --no-index --exit-code -- out/translator-base.tsv out/translator-head.tsv +``` + +An empty diff means the fixture outputs and refusal reasons match. The script +uses fresh caches on each run and the default translator settings. For a local +corpus, pass `--corpus-dir` with a directory of `req_.*` inputs in both +commands. Supported request markers are `.a`, `.rtv`, `.c67`, and `.m57`. +The raw mesh profile reads the `.mslayout` sidecar and hashes the mesh stage. + +```powershell +cmake --build --preset dev --target compile_dxil +ctest --preset dev --no-tests=error -R '^native_translator_corpus_dxil$' --output-on-failure +``` + +The test checks known compilations and refusals, then compares the two cold +snapshots byte for byte. diff --git a/tests/cmake/translator_corpus.cmake b/tests/cmake/translator_corpus.cmake new file mode 100644 index 0000000000..e1c508d974 --- /dev/null +++ b/tests/cmake/translator_corpus.cmake @@ -0,0 +1,8 @@ +if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxc.exe" + AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_translator_corpus_dxil COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/translator_corpus_hash.py" + "$" "${DXC_BIN_DIR}" --check-repeat + --out "${CMAKE_CURRENT_BINARY_DIR}/translator_corpus_dxil.tsv") + set_tests_properties(native_translator_corpus_dxil PROPERTIES TIMEOUT 120) +endif() diff --git a/tests/native_compile_dxil_refusals_check.py b/tests/native_compile_dxil_refusals_check.py index 7185e27032..988bcb5d63 100644 --- a/tests/native_compile_dxil_refusals_check.py +++ b/tests/native_compile_dxil_refusals_check.py @@ -53,6 +53,21 @@ def put_mesh_request(directory, words, pixel, root, *, layout=None, wrong_key=Fa return key +def put_batch_graphics_requests(cache, root): + return ( + put_graphics_request(cache, VS_WORDS, ps_words(4), root, TARGET_MASKS), + put_graphics_request(cache, VS_WORDS, ps_words(2), root, (0x0002, 0x8002)), + put_graphics_request(cache, VS_WORDS, struct.pack("<2I", 0xFFFFFFFF, 0xBF810000), root, DECOY_MASKS), + ) + + +def put_batch_compute_requests(cache, code, root, state): + return ( + put_compute_request(cache, code, root, state), + put_compute_request(cache, code[:-4] + struct.pack("<2I", 0xFFFFFFFF, 0xBF810000), root, state), + ) + + def check_mesh_report(parsed, report, translated, refusals, caller_layout=None): mesh = parsed["mesh57"] assert mesh["examined"] == 7, mesh @@ -88,11 +103,7 @@ def main(argv: list[str]) -> int: # 1. Batch --requests writes .fail on refusal and removes stale .fail on subsequent success. cache = work / "batch_cache" cache.mkdir() - valid_gfx = put_graphics_request(cache, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) - bad_vgpr2 = put_graphics_request(cache, VS_WORDS, ps_words(2), g_root, (0x0002, 0x8002)) - bad_decode_gfx = put_graphics_request( - cache, VS_WORDS, struct.pack("<2I", 0xFFFFFFFF, 0xBF810000), g_root, DECOY_MASKS - ) + valid_gfx, bad_vgpr2, bad_decode_gfx = put_batch_graphics_requests(cache, g_root) # Pre-seed a stale .fail beside a valid request to verify --requests deletes it upon success. stale_fail = cache / f"{valid_gfx:016x}.fail" stale_fail.write_text("stale failure\n", encoding="utf-8") @@ -116,10 +127,7 @@ def main(argv: list[str]) -> int: assert not (cache / f"{bad_key:016x}.vs.cso").exists() assert not (cache / f"{bad_key:016x}.ps.cso").exists() - valid_cs = put_compute_request(cache, c_code, c_root, c_sa) - bad_cs_decode = put_compute_request( - cache, c_code[:-4] + struct.pack("<2I", 0xFFFFFFFF, 0xBF810000), c_root, c_sa - ) + valid_cs, bad_cs_decode = put_batch_compute_requests(cache, c_code, c_root, c_sa) stale_cs_fail = cache / f"{valid_cs:016x}.fail" stale_cs_fail.write_text("stale compute failure\n", encoding="utf-8") diff --git a/tests/native_compile_dxil_watch_check.py b/tests/native_compile_dxil_watch_check.py index 67b1ab2c9a..2ebb99b1ef 100644 --- a/tests/native_compile_dxil_watch_check.py +++ b/tests/native_compile_dxil_watch_check.py @@ -60,6 +60,12 @@ def run_once(cli: Path, sdk: Path, frontend: Path, req_dir: Path, jobs: int = 1) ) +def put_watch_rtv_requests(directory, root): + base = put_graphics_request(directory, VS_WORDS, ps_words(4), root, TARGET_MASKS) + return (base, put_variant(directory, base, (UINT16, UNORM8)), + put_variant(directory, base, (FLOAT32,)), put_variant(directory, base, (7,))) + + def main(argv: list[str]) -> int: if len(argv) != 2: raise SystemExit(__doc__) @@ -251,10 +257,7 @@ def main(argv: list[str]) -> int: # RTV variants in --once: compile base + variants, publish rtv1 manifest + .psdep, and recheck on base .psin update. d_rtv = work / "once_rtv" d_rtv.mkdir() - rtv_base = put_graphics_request(d_rtv, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) - rtv_u16, rtv_u16_line = put_variant(d_rtv, rtv_base, (UINT16, UNORM8)) - rtv_f32, rtv_f32_line = put_variant(d_rtv, rtv_base, (FLOAT32,)) - rtv_bad, _ = put_variant(d_rtv, rtv_base, (7,)) + rtv_base, (rtv_u16, rtv_u16_line), (rtv_f32, rtv_f32_line), (rtv_bad, _) = put_watch_rtv_requests(d_rtv, g_root) r_rtv = run_once(cli, sdk, frontend, d_rtv, jobs=2) assert r_rtv.returncode == 0, (r_rtv.returncode, r_rtv.stdout, r_rtv.stderr) for vkey, vline in ((rtv_u16, rtv_u16_line), (rtv_f32, rtv_f32_line)): diff --git a/tests/native_direct_mesh_check.py b/tests/native_direct_mesh_check.py index 4d69d0f40c..f133fc98fb 100644 --- a/tests/native_direct_mesh_check.py +++ b/tests/native_direct_mesh_check.py @@ -8,6 +8,9 @@ import tempfile +TRIANGLE_LAYOUT = 'mesh1 128 3 1 2 128 64' + + def triangle(): return [ 0xbefc03ff, 0x1003, 0xbf900009, # m0 = (1 primitive << 12) | 3 vertices; GS_ALLOC_REQ @@ -112,6 +115,13 @@ def v_cmpx_ne_u32_words(program, compare): return program[:7] + body + program[7:] +def cmpx_ne_cases(program): + return ( + ('v-cmpx-ne-narrow', v_cmpx_ne_u32_words(program, 0x7DAA0080), r'icmp ne i32 0, %[\w.]+'), + ('v-cmpx-ne-empty', v_cmpx_ne_u32_words(program, 0x7DAA0100), r'icmp ne i32 (?P%[\w.]+), (?P=same)'), + ) + + def _v_mov_b32(dst, src): return (63 << 25) | ((dst & 0xFF) << 17) | (1 << 9) | (src & 0x1FF) @@ -433,7 +443,7 @@ def main(): checked_pixel_entry(root, compiler, sdk) raw = root / 'fixture.m57' layout = raw.with_suffix('.mslayout') - layout.write_text('mesh1 128 3 1 2 128 64') + layout.write_text(TRIANGLE_LAYOUT) def compile_mesh(name, words): raw.write_bytes(struct.pack('<%dI' % len(words), *words)) out = root / (name + '.dxil') @@ -520,10 +530,8 @@ def run(name, words, expected=None): signed_le[7] = 0xBF051514 # s_cmp_le_i32 s20, s21 stays refused run('s-cmp-le-i32-refused', signed_le, 'unsupported mesh instruction or EXEC state: s_cmp_le_i32') # V_CMPX replaces EXEC with the per-lane predicate and does not write a VCC ballot. - assert_cmpx_ne(run('v-cmpx-ne-narrow', v_cmpx_ne_u32_words(program, 0x7DAA0080)), - r'icmp ne i32 0, %[\w.]+') - assert_cmpx_ne(run('v-cmpx-ne-empty', v_cmpx_ne_u32_words(program, 0x7DAA0100)), - r'icmp ne i32 (?P%[\w.]+), (?P=same)') + for name, words, predicate in cmpx_ne_cases(program): + assert_cmpx_ne(run(name, words), predicate) # v_cmpx_lt_u32 writes EXEC from icmp ult and leaves VCC unused. # Lane id < 2 is true for the lower lanes, false when the lane is equal or greater. lane = r'%[\w.]+' diff --git a/tests/translator_corpus_hash.py b/tests/translator_corpus_hash.py new file mode 100644 index 0000000000..553fe18b06 --- /dev/null +++ b/tests/translator_corpus_hash.py @@ -0,0 +1,177 @@ +"""Fingerprint native shader output and refusals for a source-built request corpus.""" + +import argparse +from difflib import unified_diff +from hashlib import sha256 +import os +from pathlib import Path +import re +import subprocess +import tempfile + +import native_compile_dxil_refusals_check as refusals +import native_compile_dxil_rekey_check as rekey +import native_compile_dxil_watch_check as watch +import native_direct_mesh_check as mesh +import native_rtv_variant_check as rtv +import native_startup_request_cache_check as native +import startup_compute_translate_check as startup + + +def build_corpus(requests, sdk): + requests.mkdir() + graphics_root = native.compile_graphics_table_root(sdk, requests.parent) + compute_root = native.compile_compute_root(sdk, requests.parent) + compiled, vgpr, undecodable = refusals.put_batch_graphics_requests(requests, graphics_root) + accepted, refused = [compiled], [vgpr, undecodable] + + _, uint, floating, bad_format = watch.put_watch_rtv_requests(requests, graphics_root) + accepted.extend((uint[0], floating[0])) + refused.append(bad_format[0]) + + base = native.put_graphics_request(requests, native.stream_vertex_container(), rtv.pixel_stage(), graphics_root) + accepted.append(base) + for _, formats, *_ in rtv.VARIANTS: + accepted.append(rtv.put_variant(requests, base, formats)[0]) + accepted.append(rtv.put_variant(requests, base, (rtv.UINT16_RG, rtv.UNORM8))[0]) + + # The rekey fixture uses synthetic parts that satisfy the key format and are refused as shaders. + parts = rekey.graphics(1) + key = rekey.gkey(rekey.G, parts) + rekey.write_request(requests, key, parts) + refused.append(key) + + state = startup.state_a(native.COMPUTE_GROUP, native.COMPUTE_RSRC2) + compiled, undecodable = refusals.put_batch_compute_requests(requests, native.compute_program_words(), compute_root, state) + accepted.append(compiled) + refused.append(undecodable) + _, code, rsrc2, group, _ = startup.C.CASES['A'] + startup.write_request(requests, code, startup.state_a(group, rsrc2)) + + program = mesh.triangle() + for words in (program, *(words for _, words, _ in mesh.cmpx_ne_cases(program))): + key = refusals.put_mesh_request(requests, words, b'', graphics_root, layout=mesh.TRIANGLE_LAYOUT + '\n') + accepted.append(int(key, 16)) + key = refusals.put_mesh_request(requests, program, native.ps_words(4), graphics_root) + refused.append(int(key, 16)) + return {f'{key:016x}': status for keys, status in ((accepted, 'compiled'), (refused, 'refused')) for key in keys} + + +def run_compiler(command): + env = {name: value for name, value in os.environ.items() if not name.upper().startswith('X2W_')} + return subprocess.run(command, env=env, capture_output=True, encoding='utf-8', errors='replace', timeout=60) + + +def shader_hash(paths): + stages = [] + for path in paths: + data = path.read_bytes() + if not data.startswith(b'DXBC'): + raise ValueError(f'{path.name}: expected a DXIL container') + stages.append((path.name.split('.', 1)[1], sha256(data))) + if len(stages) == 1: + return stages[0][1].hexdigest() + # Include stage names so swapping stages changes the request fingerprint. + return sha256(b''.join(name.encode('ascii') + b'\0' + digest.digest() for name, digest in stages)).hexdigest() + + +def refused_row(reason): + reason = ' '.join(reason.split()) + if not reason: + raise ValueError('missing refusal reason') + return 'refused', '', reason + + +def batch_rows(command, requests, out, keys, profile, required): + result = run_compiler([*command, profile, '--requests', requests, out]) + rows = {} + for key in keys: + stages = sorted(out.glob(f'{key}.*.cso')) + failure = out / f'{key}.fail' + if failure.is_file() and not stages: + rows[key] = refused_row(failure.read_text(encoding='utf-8', errors='backslashreplace')) + elif not failure.exists() and all((out / f'{key}.{stage}.cso').is_file() for stage in required): + rows[key] = 'compiled', shader_hash(stages), '' + else: + raise ValueError(f'{profile}: incomplete or conflicting outputs for {key}\n{result.stderr}') + rejected = sum(row[0] == 'refused' for row in rows.values()) + summary = f'requests={len(keys)} compiled={len(keys) - rejected} refused={rejected}' + if result.returncode != int(rejected != 0) or summary not in result.stdout.splitlines(): + raise ValueError(f'{profile}: expected {summary}\n{result.stdout}\n{result.stderr}') + return rows + + +def mesh_row(command, source, out): + key = source.stem.removeprefix('req_') + stage = out / f'{key}.ms.cso' + # The raw mesh profile takes a single input and its .mslayout sidecar. + result = run_compiler([*command, 'gfx1013-raw-ms', source, stage]) + if result.returncode == 0 and stage.is_file(): + return 'compiled', shader_hash([stage]), '' + if result.returncode == 1 and not stage.exists() and result.stdout.startswith('compiler_init_ms='): + return refused_row(result.stderr) + raise ValueError(f'{key}: incomplete mesh result\n{result.stdout}\n{result.stderr}') + + +def snapshot(args): + with tempfile.TemporaryDirectory(prefix='x2w-translator-corpus-') as tmp: + work = Path(tmp) + requests = args.corpus_dir or work / 'requests' + expected = {} if args.corpus_dir else build_corpus(requests, args.sdk) + if not requests.is_dir(): + raise ValueError(f'{requests}: expected a request directory') + markers = {ext: {} for ext in ('.a', '.rtv', '.c67', '.m57')} + for path in requests.iterdir(): + if path.is_file() and path.suffix in markers and re.fullmatch(r'req_[0-9a-f]{16}', path.stem): + markers[path.suffix][path.stem[4:]] = path + graphics = markers['.a'].keys() | markers['.rtv'].keys() + compute, meshes = markers['.c67'], markers['.m57'] + keys = graphics | compute.keys() | meshes.keys() + if not keys or len(keys) != len(graphics) + len(compute) + len(meshes): + raise ValueError('expected nonempty request corpus with distinct keys across profiles') + + command = [args.compile_dxil, args.sdk, work / 'cache'] + out = work / 'outputs' + out.mkdir() + rows = {} + if graphics: + rows.update(batch_rows(command, requests, out, graphics, 'gfx1013-container-pair', ('vs', 'ps'))) + if compute: + rows.update(batch_rows(command, requests, out, compute, 'gfx1013-direct-cs@0', ('cs',))) + for key, source in sorted(meshes.items()): + rows[key] = mesh_row(command, source, out) + + if args.check_repeat: + for key, status in expected.items(): + if key not in rows or rows[key][0] != status: + raise ValueError(f'{key}: expected {status}, got {rows.get(key)}') + return ('key\tstatus\tsha256\treason\n' + ''.join( + '\t'.join((key, *row)) + '\n' for key, row in sorted(rows.items()) + )).encode('utf-8') + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('compile_dxil', type=Path) + parser.add_argument('sdk', type=Path, help='directory containing the DXC executable and runtime libraries') + parser.add_argument('--out', type=Path, required=True) + parser.add_argument('--corpus-dir', type=Path, help='use local req_.* files in place of the synthetic corpus') + parser.add_argument('--check-repeat', action='store_true', help='check fixture outcomes and compare two cold runs') + args = parser.parse_args() + args.compile_dxil = args.compile_dxil.resolve() + args.sdk = args.sdk.resolve() + try: + first = snapshot(args) + if args.check_repeat: + second = snapshot(args) + if first != second: + diff = unified_diff(first.decode().splitlines(True), second.decode().splitlines(True), 'first', 'second') + raise ValueError('translator corpus changed between cold runs\n' + ''.join(diff)) + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_bytes(first) + except (OSError, ValueError, subprocess.SubprocessError) as error: + parser.exit(1, f'{error}\n') + + +if __name__ == '__main__': + main() From 4788e83b8e04e44577046311120d57aaab130930 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:16:18 +0100 Subject: [PATCH 2/3] tooling: dump shader IR beside compiled stages --- docs/experiments/translator-corpus.md | 18 +++++-- tests/cmake/translator_corpus.cmake | 6 ++- tests/translator_corpus_hash.py | 78 ++++++++++++++++++--------- tools/startup/compile_dxil.cpp | 62 +++++++++++++++------ 4 files changed, 118 insertions(+), 46 deletions(-) diff --git a/docs/experiments/translator-corpus.md b/docs/experiments/translator-corpus.md index c4b43718d7..1e12c996d8 100644 --- a/docs/experiments/translator-corpus.md +++ b/docs/experiments/translator-corpus.md @@ -8,11 +8,15 @@ byte, and its binary SHA-256 digest in stage name order. Build `compile_dxil` in two separate build directories with the same preset and DXC version. From the checkout containing the corpus script, use that same copy -of the script and the same DXC directory for both builds. +of the script and the same DXC directory for both builds. Set `$baseCompiler` +and `$headCompiler` to the two executable paths. ```powershell +$sdk = (Get-Content out/build/dev/x2w-dxc-dir.txt -Raw).Trim() python -B tests/translator_corpus_hash.py $baseCompiler $sdk --out out/translator-base.tsv +if ($LASTEXITCODE -ne 0) { throw 'Base corpus run failed' } python -B tests/translator_corpus_hash.py $headCompiler $sdk --out out/translator-head.tsv +if ($LASTEXITCODE -ne 0) { throw 'Head corpus run failed' } git diff --no-index --exit-code -- out/translator-base.tsv out/translator-head.tsv ``` @@ -22,10 +26,16 @@ corpus, pass `--corpus-dir` with a directory of `req_.*` inputs in both commands. Supported request markers are `.a`, `.rtv`, `.c67`, and `.m57`. The raw mesh profile reads the `.mslayout` sidecar and hashes the mesh stage. +Add `--ir` to both commands to hash each successful stage's pre-DXC text. Both +compiler builds must support `--dump-ir`. DXC still validates the stages and +supplies the root signature fixtures. Use DXIL mode when comparing builds that +predate `--dump-ir`. + ```powershell cmake --build --preset dev --target compile_dxil -ctest --preset dev --no-tests=error -R '^native_translator_corpus_dxil$' --output-on-failure +ctest --preset dev --no-tests=error -R '^native_translator_corpus_(dxil|ir)$' --output-on-failure ``` -The test checks known compilations and refusals, then compares the two cold -snapshots byte for byte. +Each test checks known compilations and refusals and compares two cold snapshots +byte for byte. The IR test also compares DXIL from runs with and without the dump +flag. diff --git a/tests/cmake/translator_corpus.cmake b/tests/cmake/translator_corpus.cmake index e1c508d974..10de5baf5d 100644 --- a/tests/cmake/translator_corpus.cmake +++ b/tests/cmake/translator_corpus.cmake @@ -4,5 +4,9 @@ if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/ "${CMAKE_CURRENT_SOURCE_DIR}/tests/translator_corpus_hash.py" "$" "${DXC_BIN_DIR}" --check-repeat --out "${CMAKE_CURRENT_BINARY_DIR}/translator_corpus_dxil.tsv") - set_tests_properties(native_translator_corpus_dxil PROPERTIES TIMEOUT 120) + add_test(NAME native_translator_corpus_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/translator_corpus_hash.py" + "$" "${DXC_BIN_DIR}" --ir --check-repeat + --out "${CMAKE_CURRENT_BINARY_DIR}/translator_corpus_ir.tsv") + set_tests_properties(native_translator_corpus_dxil native_translator_corpus_ir PROPERTIES TIMEOUT 120) endif() diff --git a/tests/translator_corpus_hash.py b/tests/translator_corpus_hash.py index 553fe18b06..4231664eb1 100644 --- a/tests/translator_corpus_hash.py +++ b/tests/translator_corpus_hash.py @@ -62,12 +62,14 @@ def run_compiler(command): return subprocess.run(command, env=env, capture_output=True, encoding='utf-8', errors='replace', timeout=60) -def shader_hash(paths): +def shader_hash(paths, ir): stages = [] for path in paths: + if ir: + path = path.with_suffix(path.suffix + '.ir') data = path.read_bytes() - if not data.startswith(b'DXBC'): - raise ValueError(f'{path.name}: expected a DXIL container') + if not data or (not ir and not data.startswith(b'DXBC')): + raise ValueError(f'{path.name}: invalid shader output') stages.append((path.name.split('.', 1)[1], sha256(data))) if len(stages) == 1: return stages[0][1].hexdigest() @@ -76,25 +78,30 @@ def shader_hash(paths): def refused_row(reason): - reason = ' '.join(reason.split()) - if not reason: + reason = reason.rstrip('\r\n') + if not reason.strip(): raise ValueError('missing refusal reason') - return 'refused', '', reason + reason = reason.replace('\\', '\\\\').replace('\t', '\\t').replace('\r', '\\r').replace('\n', '\\n') + return [], reason def batch_rows(command, requests, out, keys, profile, required): result = run_compiler([*command, profile, '--requests', requests, out]) + stage_paths = {key: [] for key in keys} + for path in sorted(out.glob('*.cso')): + key = path.name.split('.', 1)[0] + if key in stage_paths: + stage_paths[key].append(path) rows = {} - for key in keys: - stages = sorted(out.glob(f'{key}.*.cso')) + for key, stages in stage_paths.items(): failure = out / f'{key}.fail' if failure.is_file() and not stages: rows[key] = refused_row(failure.read_text(encoding='utf-8', errors='backslashreplace')) elif not failure.exists() and all((out / f'{key}.{stage}.cso').is_file() for stage in required): - rows[key] = 'compiled', shader_hash(stages), '' + rows[key] = stages, '' else: raise ValueError(f'{profile}: incomplete or conflicting outputs for {key}\n{result.stderr}') - rejected = sum(row[0] == 'refused' for row in rows.values()) + rejected = sum(not stages for stages, _ in rows.values()) summary = f'requests={len(keys)} compiled={len(keys) - rejected} refused={rejected}' if result.returncode != int(rejected != 0) or summary not in result.stdout.splitlines(): raise ValueError(f'{profile}: expected {summary}\n{result.stdout}\n{result.stderr}') @@ -107,13 +114,25 @@ def mesh_row(command, source, out): # The raw mesh profile takes a single input and its .mslayout sidecar. result = run_compiler([*command, 'gfx1013-raw-ms', source, stage]) if result.returncode == 0 and stage.is_file(): - return 'compiled', shader_hash([stage]), '' + return [stage], '' if result.returncode == 1 and not stage.exists() and result.stdout.startswith('compiler_init_ms='): return refused_row(result.stderr) raise ValueError(f'{key}: incomplete mesh result\n{result.stdout}\n{result.stderr}') -def snapshot(args): +def status(stages): + return 'compiled' if stages else 'refused' + + +def render(rows, ir=False): + lines = ['key\tstatus\tsha256\treason\n'] + for key, (stages, reason) in sorted(rows.items()): + digest = shader_hash(stages, ir) if stages else '' + lines.append(f'{key}\t{status(stages)}\t{digest}\t{reason}\n') + return ''.join(lines).encode('utf-8') + + +def snapshot(args, dump_ir): with tempfile.TemporaryDirectory(prefix='x2w-translator-corpus-') as tmp: work = Path(tmp) requests = args.corpus_dir or work / 'requests' @@ -131,6 +150,9 @@ def snapshot(args): raise ValueError('expected nonempty request corpus with distinct keys across profiles') command = [args.compile_dxil, args.sdk, work / 'cache'] + if dump_ir: + command.append('--dump-ir') + command.extend(('--jobs', '2')) out = work / 'outputs' out.mkdir() rows = {} @@ -142,12 +164,17 @@ def snapshot(args): rows[key] = mesh_row(command, source, out) if args.check_repeat: - for key, status in expected.items(): - if key not in rows or rows[key][0] != status: - raise ValueError(f'{key}: expected {status}, got {rows.get(key)}') - return ('key\tstatus\tsha256\treason\n' + ''.join( - '\t'.join((key, *row)) + '\n' for key, row in sorted(rows.items()) - )).encode('utf-8') + for key, outcome in expected.items(): + actual = status(rows[key][0]) if key in rows else 'missing' + if actual != outcome: + raise ValueError(f'{key}: expected {outcome}, got {actual}') + return render(rows), render(rows, ir=True) if dump_ir else None + + +def check_same(first, second, before, after): + if first != second: + diff = unified_diff(first.decode().splitlines(True), second.decode().splitlines(True), before, after) + raise ValueError('translator corpus changed\n' + ''.join(diff)) def main(): @@ -155,20 +182,23 @@ def main(): parser.add_argument('compile_dxil', type=Path) parser.add_argument('sdk', type=Path, help='directory containing the DXC executable and runtime libraries') parser.add_argument('--out', type=Path, required=True) + parser.add_argument('--ir', action='store_true', help='hash shader text from compile_dxil --dump-ir') parser.add_argument('--corpus-dir', type=Path, help='use local req_.* files in place of the synthetic corpus') parser.add_argument('--check-repeat', action='store_true', help='check fixture outcomes and compare two cold runs') args = parser.parse_args() args.compile_dxil = args.compile_dxil.resolve() args.sdk = args.sdk.resolve() try: - first = snapshot(args) + dxil, ir = snapshot(args, dump_ir=args.ir) if args.check_repeat: - second = snapshot(args) - if first != second: - diff = unified_diff(first.decode().splitlines(True), second.decode().splitlines(True), 'first', 'second') - raise ValueError('translator corpus changed between cold runs\n' + ''.join(diff)) + repeated_dxil, repeated_ir = snapshot(args, dump_ir=args.ir) + check_same(dxil, repeated_dxil, 'first DXIL', 'second DXIL') + if args.ir: + check_same(ir, repeated_ir, 'first IR', 'second IR') + default_dxil, _ = snapshot(args, dump_ir=False) + check_same(default_dxil, dxil, 'default DXIL', 'DXIL with --dump-ir') args.out.parent.mkdir(parents=True, exist_ok=True) - args.out.write_bytes(first) + args.out.write_bytes(ir if args.ir else dxil) except (OSError, ValueError, subprocess.SubprocessError) as error: parser.exit(1, f'{error}\n') diff --git a/tools/startup/compile_dxil.cpp b/tools/startup/compile_dxil.cpp index e8819a2a04..993a1c4c1a 100644 --- a/tools/startup/compile_dxil.cpp +++ b/tools/startup/compile_dxil.cpp @@ -90,7 +90,9 @@ static CapturedViews read_captured_views(const fs::path& request_path) { static std::vector compile_to_dxil(x2w::ShaderDxilCompiler& compiler, const std::string& source, const std::wstring& profile, const fs::path& cache, bool direct, - std::ostream& report) { + std::ostream& report, const fs::path& ir_dump = {}) { + if (!ir_dump.empty()) + publish_atomic(ir_dump, source.data(), source.size()); auto start=Clock::now(); auto output=compiler.compile(source,profile,cache,direct?x2w::ShaderSourceFormat::dxil_ir:x2w::ShaderSourceFormat::hlsl); report << (output.cache_hit?"cache_hit_ms=":"cold_compile_and_publish_ms=") @@ -99,8 +101,9 @@ static std::vector compile_to_dxil(x2w::ShaderDxilCompiler& compi } static void compile_source(x2w::ShaderDxilCompiler& compiler,const std::string& source,const std::wstring& profile, - const fs::path& destination,const fs::path& cache,bool direct,std::ostream& report) { - auto dxil = compile_to_dxil(compiler, source, profile, cache, direct, report); + const fs::path& destination,const fs::path& cache,bool direct,std::ostream& report, + const fs::path& ir_dump) { + auto dxil = compile_to_dxil(compiler, source, profile, cache, direct, report, ir_dump); publish_atomic(destination, dxil.data(), dxil.size()); } @@ -218,7 +221,8 @@ static std::optional compile_one(x2w::ShaderDxilCompiler& compiler, const fs::path& input_path, const fs::path& destination, const fs::path& cache, std::ostream& report, const x2w::NativeComputeShader *linked=nullptr, - bool emit_manifest=false, std::string *manifest_reason=nullptr) { + bool emit_manifest=false, std::string *manifest_reason=nullptr, + const fs::path& ir_dump = {}) { Clock::time_point start; std::string source; std::optional manifest; @@ -407,12 +411,12 @@ static std::optional compile_one(x2w::ShaderDxilCompiler& compiler, #if defined(_MSC_VER) #pragma warning(suppress: 4996) // Read-only CRT environment lookup. #endif - if (const char *dump=std::getenv("X2W_DUMP_SHADER_IR")) { + if (const char *dump=ir_dump.empty() ? std::getenv("X2W_DUMP_SHADER_IR") : nullptr) { std::ofstream file(dump,std::ios::binary); file << source; if (!file) throw std::runtime_error("could not write the shader IR dump"); } - compile_source(compiler,source,profile,destination,cache,direct,report); + compile_source(compiler,source,profile,destination,cache,direct,report,ir_dump); return manifest; } @@ -1653,12 +1657,14 @@ int wmain(int argc, wchar_t** argv) { return 1; } } - const bool parallel = argc > 3 && std::wstring_view(argv[3]) == L"--jobs"; - const int profile_index = parallel ? 5 : 3; + const bool dump_ir = argc > 3 && std::wstring_view(argv[3]) == L"--dump-ir"; + const int options = dump_ir ? 4 : 3; + const bool parallel = argc > options && std::wstring_view(argv[options]) == L"--jobs"; + const int profile_index = options + (parallel ? 2 : 0); const int first = profile_index+1; const bool directory = argc > first && std::wstring_view(argv[first]) == L"--requests"; if (directory ? argc != first+3 : (argc < first+2 || (argc-first)%2)) { - std::cerr << "usage: compile_dxil SDK_DIRECTORY CACHE_DIRECTORY [--jobs N] PROFILE INPUT OUTPUT.cso [INPUT OUTPUT ...]\n" + std::cerr << "usage: compile_dxil SDK_DIRECTORY CACHE_DIRECTORY [--dump-ir] [--jobs N] PROFILE INPUT OUTPUT.cso [INPUT OUTPUT ...]\n" "Use a DXC profile for HLSL, gfx1013-constant-ps or gfx1013-rgb11-r16-ps for a raw pixel program, or\n" "gfx1013-vertex-id-vs or gfx1013-buffered-vs for a raw vertex program. gfx1013-sampled-pair takes one VS and one PS (in order).\n" "gfx1013-buffered-pair takes a buffered vertex program and a pixel HLSL source.\n" @@ -1674,6 +1680,7 @@ int wmain(int argc, wchar_t** argv) { "For capture directories use PROFILE --requests DIRECTORY OUTPUT_DIRECTORY. " "gfx1013-container-pair also takes each req_.rtv (rtv1 BASE_KEY FORMAT ...) and publishes it under its key.\n" "gfx1013-container-rect also emits the rectangle geometry stage.\n" + "Use --dump-ir to write the pre-compiler shader text beside each stage as OUTPUT.cso.ir.\n" "Use --refusals REQUEST_DIRECTORY [--jobs N] [--json] [--mesh-layout FILE] for a read-only refusal summary.\n" "Use --watch SDK_DIRECTORY CACHE_DIRECTORY REQUEST_DIRECTORY [--jobs N] [--interval MS] [--once] to translate pending requests.\n" "Set X2W_DUMP_SHADER_IR=FILE to write the HLSL or DXIL text handed to the compiler.\n" @@ -1740,7 +1747,7 @@ int wmain(int argc, wchar_t** argv) { }; int jobs=1; if (parallel) - jobs = (std::min)(parse_jobs_count(argv[4]), count); + jobs = (std::min)(parse_jobs_count(argv[options+1]), count); auto start=Clock::now(); std::set occupied(inputs.begin(),inputs.end()); if(profile==L"gfx1013-raw-ms" || profile==L"gfx1013-raw-mesh-ps") { @@ -1766,8 +1773,11 @@ int wmain(int argc, wchar_t** argv) { if(!occupied.insert(path).second) throw std::runtime_error("parallel outputs must be distinct from all inputs and other outputs"); }; + auto ir_path = [](const fs::path& path) -> fs::path { return fs::path(path) += L".ir"; }; + auto ir_dump = [&](const fs::path& path) { return dump_ir ? ir_path(path) : fs::path{}; }; for(int i=0;idata(), manifest->size()); // Not a .fail: that file is the watchers' retry marker, and this compile succeeded. if (!manifest && !reason.empty()) @@ -1816,22 +1842,24 @@ int wmain(int argc, wchar_t** argv) { // A base pair without a manifest still publishes its stages. A variant is of use to the runtime only. if (!manifest && !input.rtv_request.empty()) throw std::runtime_error("RTV variant has no runtime manifest: its vertex inputs, target types or bindings are not described"); + const fs::path ps_path = fs::path(stems[i]) += L".ps.cso"; + const fs::path gs_path = fs::path(stems[i]) += L".gs.cso"; std::vector gs_dxil; if (rectangles || (manifest && !pair.input_layout.empty())) { std::string ir; try { ir = x2w::native_rectangle_geometry(pair.vertex.outputs, pair.pixel.inputs); } catch (const x2w::UnsupportedComputeShader&) { if (rectangles) throw; } if (!ir.empty()) { - gs_dxil = compile_to_dxil(compiler, ir, L"gs_6_6", argv[2], true, report); + gs_dxil = compile_to_dxil(compiler, ir, L"gs_6_6", argv[2], true, report, ir_dump(gs_path)); if (manifest) *manifest += "fixedrectgs\n"; } } - auto vs_dxil = compile_to_dxil(compiler, pair.vertex.dxil_ir, L"vs_6_6", argv[2], true, report); - auto ps_dxil = compile_to_dxil(compiler, pair.pixel.dxil_ir, L"ps_6_6", argv[2], true, report); + auto vs_dxil = compile_to_dxil(compiler, pair.vertex.dxil_ir, L"vs_6_6", argv[2], true, report, ir_dump(outputs[i])); + auto ps_dxil = compile_to_dxil(compiler, pair.pixel.dxil_ir, L"ps_6_6", argv[2], true, report, ir_dump(ps_path)); if (!gs_dxil.empty()) - publish_atomic(fs::path(stems[i]) += L".gs.cso", gs_dxil.data(), gs_dxil.size()); + publish_atomic(gs_path, gs_dxil.data(), gs_dxil.size()); publish_atomic(outputs[i], vs_dxil.data(), vs_dxil.size()); - publish_atomic(fs::path(stems[i]) += L".ps.cso", ps_dxil.data(), ps_dxil.size()); + publish_atomic(ps_path, ps_dxil.data(), ps_dxil.size()); if (manifest) { if (!input.pixel_input_description.empty()) publish_atomic(psdep_path, input.pixel_input_description.data(), input.pixel_input_description.size()); From 13625d24c59bc5c82e7999c4181f0c84b2c6b67b Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:22:50 +0100 Subject: [PATCH 3/3] shader: fix raw mesh fixtures in the translator corpus --- docs/experiments/translator-corpus.md | 3 ++- tests/cmake/translator_corpus.cmake | 3 ++- tests/native_direct_mesh_check.py | 11 ++++++++--- tests/translator_corpus_hash.py | 28 +++++++++++++++++++-------- 4 files changed, 32 insertions(+), 13 deletions(-) diff --git a/docs/experiments/translator-corpus.md b/docs/experiments/translator-corpus.md index 1e12c996d8..14abe0756e 100644 --- a/docs/experiments/translator-corpus.md +++ b/docs/experiments/translator-corpus.md @@ -24,7 +24,8 @@ An empty diff means the fixture outputs and refusal reasons match. The script uses fresh caches on each run and the default translator settings. For a local corpus, pass `--corpus-dir` with a directory of `req_.*` inputs in both commands. Supported request markers are `.a`, `.rtv`, `.c67`, and `.m57`. -The raw mesh profile reads the `.mslayout` sidecar and hashes the mesh stage. +For `req_.m57`, the raw mesh profile reads `req_.mslayout` and the +corpus hashes the resulting mesh stage. Add `--ir` to both commands to hash each successful stage's pre-DXC text. Both compiler builds must support `--dump-ir`. DXC still validates the stages and diff --git a/tests/cmake/translator_corpus.cmake b/tests/cmake/translator_corpus.cmake index 10de5baf5d..4050ede81a 100644 --- a/tests/cmake/translator_corpus.cmake +++ b/tests/cmake/translator_corpus.cmake @@ -8,5 +8,6 @@ if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/ "${CMAKE_CURRENT_SOURCE_DIR}/tests/translator_corpus_hash.py" "$" "${DXC_BIN_DIR}" --ir --check-repeat --out "${CMAKE_CURRENT_BINARY_DIR}/translator_corpus_ir.tsv") - set_tests_properties(native_translator_corpus_dxil native_translator_corpus_ir PROPERTIES TIMEOUT 120) + set_tests_properties(native_translator_corpus_dxil PROPERTIES TIMEOUT 120) + set_tests_properties(native_translator_corpus_ir PROPERTIES TIMEOUT 240) endif() diff --git a/tests/native_direct_mesh_check.py b/tests/native_direct_mesh_check.py index f133fc98fb..ff1f13ecfa 100644 --- a/tests/native_direct_mesh_check.py +++ b/tests/native_direct_mesh_check.py @@ -89,6 +89,12 @@ def s_cmp_le_u32_words(program, left, right): return program[:5] + moves + program[6:] +def signed_le_refusal(program): + words = s_cmp_le_u32_words(program, 1, 2) + words[7] = 0xBF051514 # s_cmp_le_i32 s20, s21 + return words, 'unsupported mesh instruction or EXEC state: s_cmp_le_i32' + + def assert_unsigned_le(text, left, right): value = r'%[\w.]+' ule = re.search(rf'(?P{value}) = icmp ule i32 {_ir_u32(left)}, {_ir_u32(right)}\n', text) @@ -526,9 +532,8 @@ def run(name, words, expected=None): ('s-cmp-le-unsigned-ones', 0xFFFFFFFF, 0), ): assert_unsigned_le(run(name, s_cmp_le_u32_words(program, left, right)), left, right) - signed_le = s_cmp_le_u32_words(program, 1, 2) - signed_le[7] = 0xBF051514 # s_cmp_le_i32 s20, s21 stays refused - run('s-cmp-le-i32-refused', signed_le, 'unsupported mesh instruction or EXEC state: s_cmp_le_i32') + signed_le, reason = signed_le_refusal(program) + run('s-cmp-le-i32-refused', signed_le, reason) # V_CMPX replaces EXEC with the per-lane predicate and does not write a VCC ballot. for name, words, predicate in cmpx_ne_cases(program): assert_cmpx_ne(run(name, words), predicate) diff --git a/tests/translator_corpus_hash.py b/tests/translator_corpus_hash.py index 4231664eb1..7e7ed3e757 100644 --- a/tests/translator_corpus_hash.py +++ b/tests/translator_corpus_hash.py @@ -18,6 +18,12 @@ import startup_compute_translate_check as startup +def put_raw_mesh_fixture(requests, words, root): + key = refusals.put_mesh_request(requests, words, b'', root) + (requests / f'req_{key}.mslayout').write_text(mesh.TRIANGLE_LAYOUT + '\n', encoding='ascii') + return key + + def build_corpus(requests, sdk): requests.mkdir() graphics_root = native.compile_graphics_table_root(sdk, requests.parent) @@ -48,13 +54,14 @@ def build_corpus(requests, sdk): _, code, rsrc2, group, _ = startup.C.CASES['A'] startup.write_request(requests, code, startup.state_a(group, rsrc2)) + expected = {f'{key:016x}': ('compiled', '') for key in accepted} + expected.update((f'{key:016x}', ('refused', '')) for key in refused) program = mesh.triangle() for words in (program, *(words for _, words, _ in mesh.cmpx_ne_cases(program))): - key = refusals.put_mesh_request(requests, words, b'', graphics_root, layout=mesh.TRIANGLE_LAYOUT + '\n') - accepted.append(int(key, 16)) - key = refusals.put_mesh_request(requests, program, native.ps_words(4), graphics_root) - refused.append(int(key, 16)) - return {f'{key:016x}': status for keys, status in ((accepted, 'compiled'), (refused, 'refused')) for key in keys} + expected[put_raw_mesh_fixture(requests, words, graphics_root)] = ('compiled', '') + signed_le, reason = mesh.signed_le_refusal(program) + expected[put_raw_mesh_fixture(requests, signed_le, graphics_root)] = ('refused', reason) + return expected def run_compiler(command): @@ -164,10 +171,15 @@ def snapshot(args, dump_ir): rows[key] = mesh_row(command, source, out) if args.check_repeat: - for key, outcome in expected.items(): - actual = status(rows[key][0]) if key in rows else 'missing' + for key, (outcome, expected_reason) in expected.items(): + if key not in rows: + raise ValueError(f'{key}: expected {outcome}, got no row') + stages, reason = rows[key] + actual = status(stages) if actual != outcome: - raise ValueError(f'{key}: expected {outcome}, got {actual}') + raise ValueError(f'{key}: expected {outcome}, got {actual} {reason}'.rstrip()) + if expected_reason not in reason: + raise ValueError(f'{key}: expected refusal containing {expected_reason!r}, got {reason!r}') return render(rows), render(rows, ir=True) if dump_ir else None