upleb.uk

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

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDadaCap <167002618+DadaCap@users.noreply.github.com>2026-11-28 12:41:59 +0100
committerGitHub <noreply@github.com>2026-11-28 12:41:59 +0100
commitfeaaa13a66528a6525ff6bc4f0d8a8bef6442e25 (patch)
tree78245010e0f7bfb99dcef9b27f9ad021d2321cea
parent23ccf1486e16dcabe35a80d4cfe7346d3d1624a2 (diff)
parent7c2de8a936897b2322caf574c991746dfe732b01 (diff)
Merge pull request #1423 from GTAVIB4GTAVI/feat/library-code-base-pairs
pso_code_base_pairs: count PSOs by code-base stage (SHADER-CODEBASE-PAIRS)
-rw-r--r--docs/boot.md2
-rw-r--r--docs/d3d12_vulkan.md24
-rw-r--r--docs/shader_library.md8
-rw-r--r--tests/test_pso_code_base_pairs.py179
-rw-r--r--tools/feature_scan.py4
-rw-r--r--tools/pso_code_base_pairs.py189
-rw-r--r--tools/shader_library.py3
7 files changed, 398 insertions, 11 deletions
diff --git a/docs/boot.md b/docs/boot.md
index bc11a2185..ecd0ddc37 100644
--- a/docs/boot.md
+++ b/docs/boot.md
@@ -264,7 +264,7 @@ order. It maps each question to the event to look for; it does not answer them.
264| 11 | `CheckFeatureSupport` answers | the call's `ok`/`failed` and the `[rt]` feature-id line; the answer itself is not logged yet | 264| 11 | `CheckFeatureSupport` answers | the call's `ok`/`failed` and the `[rt]` feature-id line; the answer itself is not logged yet |
265| 12 | Async compute / copy queues | queue creation and cross-queue fences | 265| 12 | Async compute / copy queues | queue creation and cross-queue fences |
266| 13 | 144-byte push constants | device creation `[rt]` line; `push_constants_need_fallback` when the device reports fewer | 266| 13 | 144-byte push constants | device creation `[rt]` line; `push_constants_need_fallback` when the device reports fewer |
267| 14 | Two code-base stages in one PSO | PSO creation log; the index metadata (`uses_code_base`) | 267| 14 | Two code-base stages in one PSO | answered without a trace: the pipeline library pairs the stages, and `tools/pso_code_base_pairs.py` counts 0 of 25,471 (`uses_code_base` per stage comes from the index metadata) |
268| 15 | `ExecuteIndirect` signatures | `CreateCommandSignature` and `ExecuteIndirect` calls | 268| 15 | `ExecuteIndirect` signatures | `CreateCommandSignature` and `ExecuteIndirect` calls |
269| 16 | UAV counters and typed buffer formats | UAV descs and V# format logs; formats outside `Gen.FORMATS` read 0 | 269| 16 | UAV counters and typed buffer formats | UAV descs and V# format logs; formats outside `Gen.FORMATS` read 0 |
270| 17 | Upload/readback resources reaching shaders | `CreateCommittedResource` heap types and the VB/IB/descriptor that points at one | 270| 17 | Upload/readback resources reaching shaders | `CreateCommittedResource` heap types and the VB/IB/descriptor that points at one |
diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md
index 85bee426b..3084bf06b 100644
--- a/docs/d3d12_vulkan.md
+++ b/docs/d3d12_vulkan.md
@@ -5120,20 +5120,32 @@ contract, not a runtime bug:
5120 block is still under the 256-byte limit of common desktop GPUs, but above Vulkan's 128-byte minimum; the device 5120 block is still under the 256-byte limit of common desktop GPUs, but above Vulkan's 128-byte minimum; the device
5121 requirement must be checked. 5121 requirement must be checked.
5122- A second option is a per-stage uniform/storage buffer for the code base, patched in at pipeline creation. That 5122- A second option is a per-stage uniform/storage buffer for the code base, patched in at pipeline creation. That
5123 adds a descriptor binding and a load per `s_getpc`, but avoids growing push constants. Decide after measuring 5123 adds a descriptor binding and a load per `s_getpc`, but avoids growing push constants. Not needed for the 1.0.2.1
5124 how many real PSOs have two code-base stages. 5124 package: measured over whole PSOs, none has two code-base stages (below).
5125 5125
5126Measured per stage (all 26,503, `tools/feature_scan.py`): `s_getpc_b64` is kept to read code-embedded data in 54 5126Measured per stage (all 26,503, `tools/feature_scan.py`): `s_getpc_b64` is kept to read code-embedded data in 54
5127VS, 93 PS, 266 MS and 263 CS (0 GS); the 147 VS/PS match the translator's own note. Both stages of a VS+PS or 5127VS, 93 PS, 266 MS and 263 CS (0 GS); the 147 VS/PS match the translator's own note. Both stages of a VS+PS or
5128MS+PS pipeline can therefore need a code base. 5128MS+PS pipeline can therefore need a code base.
5129 5129
5130Measured per PSO (all 25,471 graphics records of the 1.0.2.1 pipeline library, `tools/pso_code_base_pairs.py`):
5131**no PSO has two code-base stages.** The pipeline library names a program per stage slot, and a stage's
5132resource-layout blob ends with the digest of the container its code came from, which is how a record's stage joins to
5133that program's `uses_code_base` in the translation index ([shader_library.md](shader_library.md) §3). 25,027 records
5134have no code-base stage and 444 have exactly one — 343 in MS, 60 in PS, 41 in VS — in a corpus whose slots are 13,383
5135VS+PS, 10,726 MS+PS, 1,336 MS, 24 VS and 2 VS+PS+slot 6. The 21 records left unknown (19 VS+PS, 2 with slot 6) have a
5136stage whose program is not in the carve output, so its code base is unknown rather than absent. The per-stage library
5137program counts there (38 VS, 46 PS, 260 MS, 263 CS) are lower than the corpus counts above: the library holds a
5138second compiled form of 6,522 carved shaders, and a program can serve two stage slots.
5139
5130**Measured:** across the GPU test fleet (Issue #166), desktop NVIDIA (Turing, Ampere, Ada, Blackwell: 256 bytes), desktop AMD (RDNA2: 256 bytes) and Apple Silicon (MoltenVK: 4096 bytes) all satisfy the 144-byte contract natively (`maxPushConstantsSize >= 144`). Intel Arc is not uniform: the earlier fleet entries report the 128-byte specification minimum (`maxPushConstantsSize == 128`) for Arc, but an Arc B580 (Battlemage) on Windows 11, driver 32.0.101.9175, reports 256 bytes (#166, @rtrexmass), so there D3D-14's fallback never engages. The 128 figure may be specific to another OS or driver (Mesa ANV on Linux is the guess; no Arc run on Linux that records the OS is cited here, and an ANV result would settle it). So does an integrated AMD RDNA2 GPU, a Radeon 680M on the Windows driver 22.40.84.06, so the minimum is not Intel-only. That figure follows the driver as well: a Radeon 610M reports 128 on 24.10.16.14 and 256 on 26.11.2 (#166). 128 bytes cannot fit the 16-byte tail (dwords 32–35: heap base and code base) inside push constants. The runtime detects `maxPushConstantsSize < 144` at device creation (`d3d12_vulkan_device.cpp`) and flags `push_constants_need_fallback` for the uniform-buffer fallback. 5140**Measured:** across the GPU test fleet (Issue #166), desktop NVIDIA (Turing, Ampere, Ada, Blackwell: 256 bytes), desktop AMD (RDNA2: 256 bytes) and Apple Silicon (MoltenVK: 4096 bytes) all satisfy the 144-byte contract natively (`maxPushConstantsSize >= 144`). Intel Arc is not uniform: the earlier fleet entries report the 128-byte specification minimum (`maxPushConstantsSize == 128`) for Arc, but an Arc B580 (Battlemage) on Windows 11, driver 32.0.101.9175, reports 256 bytes (#166, @rtrexmass), so there D3D-14's fallback never engages. The 128 figure may be specific to another OS or driver (Mesa ANV on Linux is the guess; no Arc run on Linux that records the OS is cited here, and an ANV result would settle it). So does an integrated AMD RDNA2 GPU, a Radeon 680M on the Windows driver 22.40.84.06, so the minimum is not Intel-only. That figure follows the driver as well: a Radeon 610M reports 128 on 24.10.16.14 and 256 on 26.11.2 (#166). 128 bytes cannot fit the 16-byte tail (dwords 32–35: heap base and code base) inside push constants. The runtime detects `maxPushConstantsSize < 144` at device creation (`d3d12_vulkan_device.cpp`) and flags `push_constants_need_fallback` for the uniform-buffer fallback.
5131**Open:** the exact count of such PSOs (the pairing is in the executable), and the minimum `maxPushConstantsSize` across target GPUs. If a GPU only 5141**Open:** the minimum `maxPushConstantsSize` across target GPUs. The pair count above is measured, and zero, so the
5142168-byte block is not needed for this package. If a GPU only
5132supports 128 bytes, the current 144-byte contract already fails; the layer needs a fallback (uniform buffer for the 5143supports 128 bytes, the current 144-byte contract already fails; the layer needs a fallback (uniform buffer for the
5133tail) regardless. 5144tail) regardless.
5134 5145
5135At run time, `CreateGraphicsPipelineState` refuses a pair where both stages read their code base, with a log, so 5146At run time, `CreateGraphicsPipelineState` refuses a pair where both stages read their code base, with a log, so a
5136the first boot measures the pair count. A device whose `maxPushConstantsSize` is below 144 has every PSO refused, 5147pair the measurement missed still shows up on the first boot. A device whose `maxPushConstantsSize` is below 144
5148has every PSO refused,
5137with the limit in the log, until the uniform-buffer tail exists. 5149with the limit in the log, until the uniform-buffer tail exists.
5138 5150
5139### 5.3 Descriptor T#/S# parsing 5151### 5.3 Descriptor T#/S# parsing
@@ -5352,7 +5364,7 @@ nothing is copied from their trees.
5352| 11 | What should `CheckFeatureSupport` answer for UMA, resource binding tier, mesh tier, RT tier? | **Implemented** (D3D-11). Reports truthful host architecture (discrete desktop GPU: non-UMA), ResourceBindingTier 3 (descriptor indexing / bindless support), 48-bit GPU virtual address support matching the arena, and maps `D3D12_FEATURE_FORMAT_SUPPORT` to Vulkan format properties plus multisample render-target/resolve support and one quality level per supported sample count. | 5364| 11 | What should `CheckFeatureSupport` answer for UMA, resource binding tier, mesh tier, RT tier? | **Implemented** (D3D-11). Reports truthful host architecture (discrete desktop GPU: non-UMA), ResourceBindingTier 3 (descriptor indexing / bindless support), 48-bit GPU virtual address support matching the arena, and maps `D3D12_FEATURE_FORMAT_SUPPORT` to Vulkan format properties plus multisample render-target/resolve support and one quality level per supported sample count. |
5353| 12 | Does the game rely on async compute or copy queues for correctness? | Trace queue creation and cross-queue fences. If only performance, serialize on one queue for boot. | 5365| 12 | Does the game rely on async compute or copy queues for correctness? | Trace queue creation and cross-queue fences. If only performance, serialize on one queue for boot. |
5354| 13 | Is 144 bytes of push constants available on all target GPUs? | **Resolved / Measured** (D3D-14). Checked at device creation in `runtime/shims/d3d12_vulkan_device.cpp`. Measured across the test fleet (#166): NVIDIA (256 B), desktop AMD (256 B), and Apple M1/MoltenVK (4096 B) satisfy 144 B natively. A Radeon 680M on the Windows driver 22.40.84.06 and the earlier Intel Arc entries expose only the core minimum 128 B (`maxPushConstantsSize == 128`), but an Arc B580 on Windows 11 (driver 32.0.101.9175) reports 256 B (#166), so the 128 B figure for Arc depends on the OS or driver; an Arc result on Linux (Mesa ANV) would settle which side it is. `d3d12_vulkan_device_test` accepts either answer and checks that the fallback flag matches it. Below 144 B, the device logs a warning and marks `push_constants_need_fallback`, routing the 16-byte tail (dwords 32..35: heap base and code base) to a uniform-buffer fallback. | 5366| 13 | Is 144 bytes of push constants available on all target GPUs? | **Resolved / Measured** (D3D-14). Checked at device creation in `runtime/shims/d3d12_vulkan_device.cpp`. Measured across the test fleet (#166): NVIDIA (256 B), desktop AMD (256 B), and Apple M1/MoltenVK (4096 B) satisfy 144 B natively. A Radeon 680M on the Windows driver 22.40.84.06 and the earlier Intel Arc entries expose only the core minimum 128 B (`maxPushConstantsSize == 128`), but an Arc B580 on Windows 11 (driver 32.0.101.9175) reports 256 B (#166), so the 128 B figure for Arc depends on the OS or driver; an Arc result on Linux (Mesa ANV) would settle which side it is. `d3d12_vulkan_device_test` accepts either answer and checks that the fallback flag matches it. Below 144 B, the device logs a warning and marks `push_constants_need_fallback`, routing the 16-byte tail (dwords 32..35: heap base and code base) to a uniform-buffer fallback. |
5355| 14 | Are there PSOs with two code-base stages? | Count from the PSO/shader hash table and the index metadata. If yes, implement per-stage code-base slots (section 5.2). **Per stage, measured** (`tools/feature_scan.py`, `s_getpc_b64` kept for data rather than a far branch): 54 VS, 93 PS, 266 MS, 263 CS, 0 GS; the translator's `uses_code_base` gives the same counts (with LLVM 23 that needs #223, without which these 1,471 shaders are rejected). So VS+PS and MS+PS pipelines with two code-base stages are possible; whether any exists depends on which shaders a PSO pairs, which is in the executable, not in `shaders.rpf`. | 5367| 14 | Are there PSOs with two code-base stages? | **No: 0 of 25,471**, measured per PSO (`tools/pso_code_base_pairs.py`, section 5.2). Per stage (`tools/feature_scan.py`, `s_getpc_b64` kept for data rather than a far branch): 54 VS, 93 PS, 266 MS, 263 CS, 0 GS; the translator's `uses_code_base` gives the same counts (with LLVM 23 that needs #223, without which these 1,471 shaders are rejected). The pairing is in `shaders.rpf` after all, in the pipeline library ([shader_library.md](shader_library.md) §3): each graphics record names a program per stage slot and a stage's resource-layout blob carries the digest of the container its code came from, which joins to the translation index. So one 144-byte block with one code base at dwords 34–35 is enough for this package; the per-stage slot stays a fallback, and the runtime's refusal of a PSO whose two stages both read the code base (section 3.2) can stand. |
5356| 15 | Is `ExecuteIndirect` used with signatures Vulkan cannot express directly? | Trace `CreateCommandSignature` and `ExecuteIndirect`; implement simple signatures first, expand the complex ones with compute. The simple signatures are D3D-17 (#313). | 5368| 15 | Is `ExecuteIndirect` used with signatures Vulkan cannot express directly? | Trace `CreateCommandSignature` and `ExecuteIndirect`; implement simple signatures first, expand the complex ones with compute. The simple signatures are D3D-17 (#313). |
5357| 16 | Does the game use append/consume UAV counters or typed buffer formats the translator does not model? | **Shaders: answered** by `tools/feature_scan.py` over all 26,503 (1.0.2.1, disassembled with LLVM 21.1.8 for gfx1013; SHADER-65). **No append/consume counters:** none of the 445,394 PSV0 binding records is a structured UAV with a counter, and there is no `ds_append`/`ds_consume`/GDS instruction. Typed buffers are declared in 5,359 shaders as SRVs (17,328 records) and in 2,177 as UAVs (4,005). **MTBUF** (format in the instruction): 52,890 loads in 10,278 shaders, all in five formats the translator decodes (`16_16_SNORM` 24,881, `8_8_8_8_UNORM` 19,835, `8_8_8_8_UINT` 5,099, `2_10_10_10_UNORM` 2,648, `16_16_16_16_UINT` 427), and no MTBUF store. **MUBUF** `buffer_*_format_*` (format from V# word 3): 90,316 accesses (84,908 loads, 5,408 stores) in 11,591 shaders; word 3 comes from a scalar load in 88,924 of them, is computed in 1,390, and is a literal in 2 (FORMAT 0, INVALID, which reads 0 on the hardware and in the translator). So the shaders fix no MUBUF format: the descriptors the executable writes decide it. Still open: which formats those descriptors carry; the runtime can log a V# format outside `Gen.FORMATS` (those read 0 today) when the descriptor is created or copied. Trace UAV descs and shader `buffer_*` ops; extend the translator/runtime together. **Runtime side done, console side open:** the layer writes typed buffer V#s and a counter V# (a hypothesis for where the shader finds it, section 3.4 "Buffer UAVs"); whether the game uses either is for the trace. | 5369| 16 | Does the game use append/consume UAV counters or typed buffer formats the translator does not model? | **Shaders: answered** by `tools/feature_scan.py` over all 26,503 (1.0.2.1, disassembled with LLVM 21.1.8 for gfx1013; SHADER-65). **No append/consume counters:** none of the 445,394 PSV0 binding records is a structured UAV with a counter, and there is no `ds_append`/`ds_consume`/GDS instruction. Typed buffers are declared in 5,359 shaders as SRVs (17,328 records) and in 2,177 as UAVs (4,005). **MTBUF** (format in the instruction): 52,890 loads in 10,278 shaders, all in five formats the translator decodes (`16_16_SNORM` 24,881, `8_8_8_8_UNORM` 19,835, `8_8_8_8_UINT` 5,099, `2_10_10_10_UNORM` 2,648, `16_16_16_16_UINT` 427), and no MTBUF store. **MUBUF** `buffer_*_format_*` (format from V# word 3): 90,316 accesses (84,908 loads, 5,408 stores) in 11,591 shaders; word 3 comes from a scalar load in 88,924 of them, is computed in 1,390, and is a literal in 2 (FORMAT 0, INVALID, which reads 0 on the hardware and in the translator). So the shaders fix no MUBUF format: the descriptors the executable writes decide it. Still open: which formats those descriptors carry; the runtime can log a V# format outside `Gen.FORMATS` (those read 0 today) when the descriptor is created or copied. Trace UAV descs and shader `buffer_*` ops; extend the translator/runtime together. **Runtime side done, console side open:** the layer writes typed buffer V#s and a counter V# (a hypothesis for where the shader finds it, section 3.4 "Buffer UAVs"); whether the game uses either is for the trace. |
5358| 17 | Do upload/readback resources ever reach shaders (as vertex/index buffers or descriptors), and does the `-heap_base` bias work for them? | Trace `CreateCommittedResource` heap types and every VB/IB/descriptor that points at an upload resource; test the bias with a synthetic draw. | 5370| 17 | Do upload/readback resources ever reach shaders (as vertex/index buffers or descriptors), and does the `-heap_base` bias work for them? | Trace `CreateCommittedResource` heap types and every VB/IB/descriptor that points at an upload resource; test the bias with a synthetic draw. |
diff --git a/docs/shader_library.md b/docs/shader_library.md
index 140fe9a71..19b45e5ed 100644
--- a/docs/shader_library.md
+++ b/docs/shader_library.md
@@ -167,6 +167,9 @@ python -I tools/rdna2spirv.py <work>/library/disasm --out <work>/library/spirv
167* `--stages` limits the output to some stages. 167* `--stages` limits the output to some stages.
168* `--compute-hashes FILE` instead writes only the compute programs whose code has one of the SHA-256 digests listed 168* `--compute-hashes FILE` instead writes only the compute programs whose code has one of the SHA-256 digests listed
169 in `FILE` (`fspx_code_sha256`), with every state they are used with. A digest no compute program has is an error. 169 in `FILE` (`fspx_code_sha256`), with every state they are used with. A digest no compute program has is an error.
170* `tools/pso_code_base_pairs.py` reads the same library, in either form, and joins each graphics record's stage to
171 the translation index through that stage's source digest (§3). It counts whole PSOs by the `uses_code_base` of
172 their stages: counts only, no name or code. §6 and [d3d12_vulkan.md](d3d12_vulkan.md) §5.2 report what it says.
170 173
171The output is game data and must stay in your work folder. `tests/test_shader_library.py` builds libraries and 174The output is game data and must stay in your work folder. `tests/test_shader_library.py` builds libraries and
172archives by hand and covers the header, both tables, the size checks, the search in an archive and the digest 175archives by hand and covers the header, both tables, the size checks, the search in an archive and the digest
@@ -265,7 +268,10 @@ None of the programs has been run on a GPU.
265 268
266* **Pipeline pairing is in the package.** [d3d12_vulkan.md](d3d12_vulkan.md) question 14 asks whether a PSO pairs 269* **Pipeline pairing is in the package.** [d3d12_vulkan.md](d3d12_vulkan.md) question 14 asks whether a PSO pairs
267 two code-base stages, and says the pairing is in the executable. The graphics records give it for 25,471 270 two code-base stages, and says the pairing is in the executable. The graphics records give it for 25,471
268 pipelines: each names its VS or MS and its PS. Each source can be found through §3. 271 pipelines: each names its VS or MS and its PS, and each source can be found through §3. `tools/pso_code_base_pairs.py`
272 joins that to the FSSM translation index and counts the result: **no PSO in 1.0.2.1 has two code-base stages**.
273 25,027 have none, 444 exactly one (343 MS, 60 PS, 41 VS), and 21 stay unknown because a stage's program is not in
274 the carve output. So the one code base in the 144-byte push-constant block is enough for this package.
269* **A second compiled form of 6,522 shaders.** The pipeline builds differ from the FSSM code. Which form the game 275* **A second compiled form of 6,522 shaders.** The pipeline builds differ from the FSSM code. Which form the game
270 runs for a pipeline is not measured here (that needs the executable). Either way, a translated pipeline build can 276 runs for a pipeline is not measured here (that needs the executable). Either way, a translated pipeline build can
271 be compared with the translated FSSM shader of the same pipeline. 277 be compared with the translated FSSM shader of the same pipeline.
diff --git a/tests/test_pso_code_base_pairs.py b/tests/test_pso_code_base_pairs.py
new file mode 100644
index 000000000..39ff52437
--- /dev/null
+++ b/tests/test_pso_code_base_pairs.py
@@ -0,0 +1,179 @@
1"""Unit tests for tools/pso_code_base_pairs.py (how many real PSOs pair two code-base stages).
2
3 python -I tests/test_pso_code_base_pairs.py
4
5Zero game data: the pipeline library, the carved containers and the translation index are all built here from
6synthetic bytes, using the builders in tests/test_shader_library.py.
7"""
8import contextlib
9import io
10import json
11import os
12from pathlib import Path
13import subprocess
14import sys
15import tempfile
16import unittest
17
18ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
19sys.path.insert(0, os.path.join(ROOT, "tools"))
20sys.path.insert(0, os.path.join(ROOT, "tests"))
21
22import pso_code_base_pairs as pairs # noqa: E402
23import shader_library as sl # noqa: E402
24import test_shader_library as synth # noqa: E402
25
26TOOL = Path(ROOT) / "tools" / "pso_code_base_pairs.py"
27
28
29def library():
30 """Three graphics PSOs and one compute record: VS+PS with both stages on a code base, MS+PS with only the
31 pixel stage on one, and an MS-only record whose program cannot be resolved."""
32 blobs = [synth.layout_blob(2, synth.D_PS), synth.layout_blob(2, synth.D_VS),
33 synth.layout_blob(2, synth.D_MS), synth.layout_blob(3, synth.D_CS), b"\x05" * 8]
34 programs = [synth.prog(tag) for tag in (0x11112222, 0x33334444, 0x55556666, 0x77778888)]
35 graphics = [(4, 4, {0: (0, 0), 1: (1, 1)}), # pixel and vertex, both on a code base
36 (4, 4, {0: (0, 0), 2: (2, 2)}), # mesh without, pixel with
37 (4, 4, {2: (3, 3)})] # the mesh program of the compute record too
38 return synth.build(graphics, [(4, 4, 3, 3)], blobs, programs)
39
40
41def corpus(root: str, spirv_shape: str = "map"):
42 """<work>/shaders: a carve folder with one container per digest and a translation index over those containers.
43 The mesh container says no code base; the compute container is missing from both sides."""
44 shaders = Path(root) / "shaders"
45 dxbc = shaders / "dxbc"
46 dxbc.mkdir(parents=True)
47 entries = []
48 for stem, digest, code_base in (("PS_ONE", synth.D_PS, True), ("VS_ONE", synth.D_VS, True),
49 ("MS_ONE", synth.D_MS, False)):
50 (dxbc / f"{stem}.dxbc").write_bytes(synth.dxbc(digest))
51 entries.append({"file": f"{stem}.dxbc", "name": f"synthetic {stem.lower()}"})
52 (dxbc / "index.json").write_text(json.dumps(entries), encoding="utf-8")
53 spirv = shaders / "spirv"
54 spirv.mkdir()
55 rows = {"PS_ONE": {"uses_code_base": True}, "VS_ONE": {"uses_code_base": True},
56 "MS_ONE": {"uses_code_base": False}}
57 index = rows if spirv_shape == "map" else [dict(row, file=f"{stem}.dxbc") for stem, row in rows.items()]
58 (spirv / "index.json").write_text(json.dumps(index), encoding="utf-8")
59 return str(shaders)
60
61
62class Join(unittest.TestCase):
63 def setUp(self):
64 self._tmp = tempfile.TemporaryDirectory()
65 self.addCleanup(self._tmp.cleanup)
66 self.shaders = corpus(self._tmp.name)
67 self.lib = sl.parse(library())
68 self.code_base = pairs.read_spirv(os.path.join(self.shaders, "spirv", "index.json"))
69 self.digests = shader_carve_digests(os.path.join(self.shaders, "dxbc"))
70
71 def report(self):
72 return pairs.count_records(self.lib, pairs.code_base_flags(self.lib, self.digests, self.code_base))
73
74 def test_two_code_base_stages_are_counted_by_stage_set(self):
75 r = self.report()
76 self.assertEqual(r["stage_slots"], {"ps+vs": 1, "ms+ps": 1, "ms": 1})
77 self.assertEqual(r["psos_by_code_base_stages"], {"2": 1, "1": 1, "0": 1})
78 self.assertEqual(r["psos_with_two_code_base_stages"], {"ps+vs": 1})
79
80 def test_unresolved_stages_are_reported_separately(self):
81 # Program 3's layout digest is D_CS and no carved container carries it, so neither of the two records
82 # that name it can say whether that stage uses a code base.
83 r = self.report()
84 self.assertEqual(r["psos_unresolved"], {"ms": 1})
85 self.assertEqual(r["compute_records_by_code_base"], {"None": 1})
86 self.assertEqual(r["psos_by_code_base_stages"], {"2": 1, "1": 1, "0": 1})
87
88 def test_per_stage_program_counts_match_feature_scan(self):
89 r = self.report()
90 # Program 3 is the mesh stage of the last record and the compute record's program, so it is counted once,
91 # under the pair of stages it serves.
92 self.assertEqual(r["programs"], {"ps": 1, "vs": 1, "ms": 1, "cs+ms": 1})
93 self.assertEqual(r["programs_with_code_base"], {"ps": 1, "vs": 1})
94 self.assertEqual(r["psos_with_code_base_by_stage"], {"ps": 2, "vs": 1})
95
96 def test_a_container_carved_twice_counts_as_a_code_base_once(self):
97 dxbc = Path(self.shaders) / "dxbc"
98 (dxbc / "PS_TWICE.dxbc").write_bytes(synth.dxbc(synth.D_PS))
99 entries = json.loads((dxbc / "index.json").read_text(encoding="utf-8"))
100 entries.append({"file": "PS_TWICE.dxbc", "name": "synthetic ps again"})
101 (dxbc / "index.json").write_text(json.dumps(entries), encoding="utf-8")
102 index_path = Path(self.shaders) / "spirv" / "index.json"
103 rows = json.loads(index_path.read_text(encoding="utf-8"))
104 rows["PS_TWICE"] = {"uses_code_base": False} # the other copy says no
105 index_path.write_text(json.dumps(rows), encoding="utf-8")
106 self.digests = shader_carve_digests(str(dxbc))
107 self.code_base = pairs.read_spirv(str(index_path))
108 self.assertEqual(self.report()["psos_with_two_code_base_stages"], {"ps+vs": 1})
109
110 def test_list_shaped_translation_index_joins_by_file(self):
111 with tempfile.TemporaryDirectory() as tmp:
112 shaders = corpus(tmp, spirv_shape="list")
113 code_base = pairs.read_spirv(os.path.join(shaders, "spirv", "index.json"))
114 self.assertEqual(code_base, {"PS_ONE": True, "VS_ONE": True, "MS_ONE": False})
115 flags = pairs.code_base_flags(self.lib, self.digests, code_base)
116 self.assertEqual(pairs.count_records(self.lib, flags)["psos_with_two_code_base_stages"], {"ps+vs": 1})
117
118
119def shader_carve_digests(dxbc: str):
120 """digest -> containers, over a carve folder, with the helper's own error lines captured."""
121 with contextlib.redirect_stderr(io.StringIO()):
122 return sl.carve_digests(dxbc, errors=[])
123
124
125class CommandLine(unittest.TestCase):
126 def setUp(self):
127 self._tmp = tempfile.TemporaryDirectory()
128 self.addCleanup(self._tmp.cleanup)
129 self.root = self._tmp.name
130 self.shaders = corpus(self.root)
131
132 def run_tool(self, library_path, *extra):
133 out = os.path.join(self.root, "pairs.json")
134 proc = subprocess.run([sys.executable, "-I", str(TOOL), self.shaders, "--library", library_path,
135 *extra, "--out", out], capture_output=True, text=True)
136 return proc, (json.loads(Path(out).read_text(encoding="utf-8")) if os.path.exists(out) else None)
137
138 def test_library_blob_and_archive_are_both_accepted(self):
139 lib = library()
140 raw = os.path.join(self.root, "library.bin")
141 Path(raw).write_bytes(lib)
142 packed = os.path.join(self.root, "shaders.rpf")
143 Path(packed).write_bytes(synth.archive(lib))
144 for path in (raw, packed):
145 with self.subTest(path=os.path.basename(path)):
146 proc, report = self.run_tool(path)
147 self.assertEqual(proc.returncode, 0, proc.stderr)
148 self.assertEqual(report["psos_with_two_code_base_stages"], {"ps+vs": 1})
149 self.assertIn("stage slots per graphics PSO", proc.stdout)
150
151 def test_report_names_no_shader(self):
152 raw = os.path.join(self.root, "library.bin")
153 Path(raw).write_bytes(library())
154 proc, report = self.run_tool(raw)
155 self.assertEqual(proc.returncode, 0, proc.stderr)
156 written = proc.stdout + json.dumps(report)
157 for name in ("PS_ONE", "VS_ONE", "MS_ONE", "ps one"):
158 self.assertNotIn(name, written)
159
160 def test_out_naming_an_input_is_refused(self):
161 raw = os.path.join(self.root, "library.bin")
162 Path(raw).write_bytes(library())
163 input_path = os.path.join(self.shaders, "spirv", "index.json")
164 proc = subprocess.run([sys.executable, "-I", str(TOOL), self.shaders, "--library", raw,
165 "--out", input_path], capture_output=True, text=True)
166 self.assertEqual(proc.returncode, 2)
167 self.assertIn("is an input", proc.stderr)
168
169 def test_missing_work_folder(self):
170 raw = os.path.join(self.root, "library.bin")
171 Path(raw).write_bytes(library())
172 proc = subprocess.run([sys.executable, "-I", str(TOOL), os.path.join(self.root, "nope"),
173 "--library", raw], capture_output=True, text=True)
174 self.assertEqual(proc.returncode, 2)
175 self.assertIn("does not exist", proc.stderr)
176
177
178if __name__ == "__main__":
179 unittest.main()
diff --git a/tools/feature_scan.py b/tools/feature_scan.py
index 8045c9a9e..b1ef0d4a8 100644
--- a/tools/feature_scan.py
+++ b/tools/feature_scan.py
@@ -14,8 +14,8 @@ Reads what the shaders stage of make_game.py leaves in <work>/shaders, and print
14 accesses (#16): the MTBUF instruction formats, and for MUBUF where V# word 3 (the format) comes from, each checked 14 accesses (#16): the MTBUF instruction formats, and for MUBUF where V# word 3 (the format) comes from, each checked
15 against the translator's typed-buffer table (rdna2spirv.Gen.FORMATS). 15 against the translator's typed-buffer table (rdna2spirv.Gen.FORMATS).
16- spirv/index.json (rdna2spirv.py): uses_code_base per stage. A graphics PSO can only need two code bases 16- spirv/index.json (rdna2spirv.py): uses_code_base per stage. A graphics PSO can only need two code bases
17 (§5.2) if two of its stages use one; this gives the per-stage counts. Which stages are paired in one PSO is in 17 (§5.2) if two of its stages use one; this gives the per-stage counts. Pairing programs to the stages of a PSO is
18 the executable, not in shaders.rpf. 18 the pipeline library's job: tools/pso_code_base_pairs.py joins the two and counts whole PSOs.
19 19
20InnerCoverage metadata is cross-tabulated by stage: SFI0 set/clear/unknown versus ISG1 20InnerCoverage metadata is cross-tabulated by stage: SFI0 set/clear/unknown versus ISG1
21present/absent/unknown. Unknown includes missing or truncated parts; unreadable containers 21present/absent/unknown. Unknown includes missing or truncated parts; unreadable containers
diff --git a/tools/pso_code_base_pairs.py b/tools/pso_code_base_pairs.py
new file mode 100644
index 000000000..2f9ddf8bd
--- /dev/null
+++ b/tools/pso_code_base_pairs.py
@@ -0,0 +1,189 @@
1"""Count how many real graphics PSOs put a code base in two stages (docs/d3d12_vulkan.md §5.2).
2
3 python -I tools/pso_code_base_pairs.py <work>/shaders --library <shaders.rpf> [--out pairs.json]
4
5§5.2 leaves the push-constant shape open -- one 168-byte block per PSO or one buffer per stage -- and says to decide
6after measuring how many real PSOs have two code-base stages. `docs/boot.md` row 14 asks the same thing. The
7translation index gives `uses_code_base` per program (`tools/feature_scan.py` prints the per-stage counts), and its
8header says the pairing is not in `shaders.rpf`. It is: the pipeline library in the archive's zlib part records, for
9every graphics PSO, the program in each stage slot (`tools/shader_library.py`), so a stage of a PSO joins to that
10program's own `uses_code_base`.
11
12The join needs one step in between. A library program is not the translation index's key: the two tables name the
13same code differently. The library names a program by slot and index (`lib_ps_00042`), the translation index is keyed
14by the container it was translated from. What they have in common is the digest: a stage's resource-layout blob ends
15with the 16-byte HASH digest of the container its code came from (`shader_library.stage_digest`), and `shader_carve.py`
16leaves that same HASH part in every container it carved into `<work>/shaders/dxbc`. So
17
18 PSO -> stage slot -> program -> layout digest -> carved container -> translation-index row
19
20and the container's file stem is the translation index's key. Where a container was carved twice under two stems the
21stage counts as code-base if any of its rows does.
22
23Counts only are printed and written: no shader name, listing, code or data leaves the work folder. Standard library
24only; needs the retail package (for `shaders.rpf`) and the `shaders` stage of `make_game.py`.
25"""
26import argparse
27import json
28import mmap
29import os
30import sys
31from collections import Counter
32
33sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
34import shader_library # noqa: E402
35from report_paths import same_report_path # noqa: E402
36
37
38def container_stem(path: str) -> str:
39 """The translation index's key for a carved container: its file name without the folder and extension."""
40 return os.path.splitext(os.path.basename(path))[0]
41
42
43def read_spirv(path: str) -> dict:
44 """{container stem: True/False} for every translated program in a `spirv/index.json`.
45
46 An object maps the container stem to its row; a list of rows is the other shape `rdna2spirv.py` writes, where
47 the stem comes from the row's own file or name. Rows without a stem are skipped: they cannot be joined."""
48 with open(path, encoding="utf-8-sig") as f:
49 idx = json.load(f)
50 if isinstance(idx, dict):
51 pairs = idx.items()
52 elif isinstance(idx, list):
53 pairs = ((row.get("file") or row.get("name") or "", row) for row in idx if isinstance(row, dict))
54 else:
55 pairs = ()
56 out = {}
57 for key, row in pairs:
58 if not isinstance(row, dict) or not key:
59 continue
60 out[container_stem(str(key))] = row.get("uses_code_base") is True
61 return out
62
63
64def code_base_flags(lib: dict, digests: dict, code_base: dict) -> dict:
65 """{library program index: True / False / None} -- None when no carved container of that program is in the
66 translation index, so the program's code base is unknown rather than absent."""
67 flags = {}
68 for i in range(lib["header"]["programs"]):
69 stems = {container_stem(path) for d in lib["digest"].get(i, ()) for _, path in digests.get(d, ())}
70 known = {code_base[s] for s in stems if s in code_base}
71 flags[i] = None if not known else True in known
72 return flags
73
74
75def count_records(lib: dict, flags: dict) -> dict:
76 """The report: how the graphics PSOs and compute records split by the code-base flag of their stages.
77
78 `stages` keys are stage names joined with '+', sorted, so 'ps+vs' is one pixel and one vertex stage."""
79 slots, by_number, pairs, unresolved = Counter(), Counter(), Counter(), Counter()
80 by_stage = Counter()
81 for rec in lib["graphics"]:
82 flag = {slot: flags.get(ref["program"]) for slot, ref in rec["stages"].items()}
83 slots["+".join(sorted(flag))] += 1
84 code_base = sorted(slot for slot, known in flag.items() if known is True)
85 by_number[len(code_base)] += 1
86 by_stage.update(code_base)
87 if len(code_base) >= 2:
88 pairs["+".join(code_base)] += 1
89 missing = sorted(slot for slot, known in flag.items() if known is None)
90 if missing:
91 unresolved["+".join(missing)] += 1
92 compute = Counter(str(flags.get(rec["program"])) for rec in lib["compute"] if rec["program"] is not None)
93 programs, program_code_base = Counter(), Counter()
94 for i, stages in lib["stage"].items():
95 programs["+".join(sorted(stages))] += 1
96 if flags.get(i) is True:
97 program_code_base["+".join(sorted(stages))] += 1
98 return {
99 "library": lib["header"],
100 "stage_slots": dict(slots),
101 "psos_by_code_base_stages": {str(n): c for n, c in by_number.items()},
102 "psos_with_code_base_by_stage": dict(by_stage),
103 "psos_with_two_code_base_stages": dict(pairs),
104 "psos_unresolved": dict(unresolved),
105 "compute_records_by_code_base": dict(compute),
106 "programs": dict(programs),
107 "programs_with_code_base": dict(program_code_base),
108 }
109
110
111def print_report(report: dict, carve_errors: int) -> None:
112 h = report["library"]
113 print(f"library {h['name']} {h['version']} hash {h['hash']}: {h['graphics']} graphics + {h['compute']} "
114 f"compute records, {h['programs']} programs")
115 print("\nstage slots per graphics PSO:")
116 for name, n in sorted(report["stage_slots"].items(), key=lambda x: (-x[1], x[0])):
117 print(f" {n:7d} {name}")
118 print("\ngraphics PSOs by the number of stages that use a code base:")
119 for n in sorted(report["psos_by_code_base_stages"], key=int):
120 print(f" {report['psos_by_code_base_stages'][n]:7d} {n}")
121 print("\ngraphics PSOs with a code-base stage, counted per stage:")
122 for name, n in sorted(report["psos_with_code_base_by_stage"].items(), key=lambda x: (-x[1], x[0])):
123 print(f" {n:7d} {name}")
124 two = report["psos_with_two_code_base_stages"]
125 print("\ngraphics PSOs with two or more code-base stages, by stage:")
126 for name, n in sorted(two.items(), key=lambda x: (-x[1], x[0])):
127 print(f" {n:7d} {name}")
128 if not two:
129 print(" 0 (none)")
130 print("\nlibrary programs that use a code base, by stage (compare tools/feature_scan.py):")
131 for name in sorted(report["programs_with_code_base"]):
132 print(f" {report['programs_with_code_base'][name]:7d} of {report['programs'][name]:7d} {name}")
133 unknown = report["psos_unresolved"]
134 print(f"\ngraphics PSOs with a stage whose code base is unknown: {sum(unknown.values())}")
135 for name, n in sorted(unknown.items(), key=lambda x: (-x[1], x[0])):
136 print(f" {n:7d} {name}")
137 if carve_errors:
138 print(f"\n{carve_errors} carved containers were unreadable, above.")
139
140
141def main() -> int:
142 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
143 ap.add_argument("shaders", help="<work>/shaders from make_game.py")
144 ap.add_argument("--library", required=True,
145 help="shaders.rpf, or a pipeline library saved by tools/shader_library.py")
146 ap.add_argument("--out", help="also write the counts as JSON")
147 a = ap.parse_args()
148
149 spirv_index = os.path.join(a.shaders, "spirv", "index.json")
150 dxbc_dir = os.path.join(a.shaders, "dxbc")
151 for path, what in ((a.shaders, "folder"), (spirv_index, "file"), (dxbc_dir, "folder")):
152 if not os.path.exists(path):
153 print(f"ERROR: {path} {what} does not exist. Give the <work>/shaders folder make_game.py writes.",
154 file=sys.stderr)
155 return 2
156 for input_path in (spirv_index, os.path.join(dxbc_dir, "index.json")):
157 if a.out and same_report_path(a.out, input_path):
158 print(f"ERROR: --out {a.out} is an input ({input_path}).", file=sys.stderr)
159 return 2
160
161 with open(a.library, "rb") as f:
162 head = f.read(4)
163 f.seek(0)
164 if head == shader_library.MAGIC: # a library saved by tools/shader_library.py
165 raw = f.read()
166 else: # an archive: reassemble it from its zlib blocks
167 m = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
168 try:
169 raw = shader_library.find_library(m)
170 finally:
171 m.close()
172 lib = shader_library.parse(raw)
173
174 code_base = read_spirv(spirv_index)
175 errors = []
176 digests = shader_library.carve_digests(dxbc_dir, errors=errors)
177 report = count_records(lib, code_base_flags(lib, digests, code_base))
178 print_report(report, len(errors))
179 if a.out:
180 with open(a.out, "w", encoding="utf-8", newline="\n") as f:
181 json.dump(report, f, indent=1, sort_keys=True)
182 f.write("\n")
183 print(f"\nwrote {a.out}")
184 return 0
185
186
187if __name__ == "__main__":
188 sys.stdout.reconfigure(errors="replace")
189 sys.exit(main())
diff --git a/tools/shader_library.py b/tools/shader_library.py
index 943bdd8bb..905f7195c 100644
--- a/tools/shader_library.py
+++ b/tools/shader_library.py
@@ -14,7 +14,8 @@ stage, a table of state blobs and a table of native RDNA2 programs. Layout (docs
14 P x 8 (offset, size) into the code section, 256-byte aligned 14 P x 8 (offset, size) into the code section, 256-byte aligned
15 blob section, then code section; the file ends exactly there 15 blob section, then code section; the file ends exactly there
16 16
17A missing stage is program 0xFFFFFFFF. Stage slots: 0 pixel, 1 vertex, 2 mesh (6 is used once and not identified). 17A missing stage is program 0xFFFFFFFF. Stage slots: 0 pixel, 1 vertex, 2 mesh (slot 6 appears in the 2 records that
18have pixel, vertex and slot 6, with no stage blob, and is not identified).
18A compute state blob has the 28-byte layout of an FSPX kind-0 entry (tools/fspx_unpack.py), and every program starts 19A compute state blob has the 28-byte layout of an FSPX kind-0 entry (tools/fspx_unpack.py), and every program starts
19with the same 36-byte hash prologue as an FSPX program, so the programs are written in the layout fspx_unpack.py uses 20with the same 36-byte hash prologue as an FSPX program, so the programs are written in the layout fspx_unpack.py uses
20and tools/rdna2spirv.py reads (fspx/<name>.code, fspx/<name>.json, index.json). A compute program also gets its 21and tools/rdna2spirv.py reads (fspx/<name>.code, fspx/<name>.json, index.json). A compute program also gets its