From 7c47fd946ba19461ed7ff0b12383b55e23bf79c7 Mon Sep 17 00:00:00 2001 From: Moriz82 <72836413+Moriz82@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:13:09 -0600 Subject: [PATCH 1/3] d3d12: supply directly indexed heaps to compute dispatches (RT-DIRECT-HEAP-COMPUTE) Compute shaders using direct resource indexing received a zero heap pointer. Snapshot each bound heap offset after the explicit inline root arguments on direct and indirect dispatches, so each command retains the bindings it had when recorded. When the explicit arguments leave no SGPR, keep them and report the missing heap slot once. The placement is a hypothesis with partial evidence. Of 2,959 direct-indexing compute entries, seven could be paired with recorded layouts. All seven resource reads agree with the predicted slot. The other 2,952 have no paired layout, and no paired sampler read establishes the relative heap order. tools/compute_heap_layout_census.py reproduces the count, with synthetic tests for agreement, disagreement and missing evidence. Built gta6rt and d3d12_compute_test with clang-cl. The Proton Vulkan fixture passed 64 buffer reads and 64 null controls on an RTX 4070. With the rollback switch, all 128 controls read zero. Both runs check the recorded arguments for bundle inheritance, indirect heap rebinding and the last inline SGPR. The synthetic SPIR-V fixture passed validation. AI-assisted (Codex and Claude Code agents). Co-authored-by: Plaaasma <47513553+Plaaasma@users.noreply.github.com> Co-Authored-By: Claude Fable 5.2 --- docs/d3d12_vulkan.md | 18 ++- runtime/shims/d3d12_com.cpp | 48 +++++-- runtime/shims/d3d12_com.h | 1 + runtime/shims/d3d12_vulkan_device.cpp | 1 + runtime/test/d3d12_compute_test.cpp | 121 ++++++++++++++++ runtime/test/glsl/cs_user_data.comp | 15 ++ tests/test_compute_heap_layout_census.py | 64 +++++++++ tools/compute_heap_layout_census.py | 168 +++++++++++++++++++++++ 8 files changed, 422 insertions(+), 14 deletions(-) create mode 100644 tests/test_compute_heap_layout_census.py create mode 100644 tools/compute_heap_layout_census.py diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 8bf2bd38ea..6916cf5313 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1609,8 +1609,22 @@ The game can use D3D12 descriptors in three ways, and the layer must handle all translator input. No stride is read at run time: static offsets of T# loads are multiples of 32 and of S# loads multiples of 16, so the stride is compiled into the code. In the runtime shim, `CreateRootSignature` records the `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` and `SAMPLER_HEAP_DIRECTLY_INDEXED` root-signature flags and `SetDescriptorHeaps` - tracks the bound shader-visible heap GPU bases (`d3d12_set_descriptor_heaps`), while placing those bases into - per-stage user SGPRs remains open on question 3. + tracks the bound shader-visible heap GPU bases (`d3d12_set_descriptor_heaps`). + + **Inline compute layout (integration #984).** Run + `python -I tools/compute_heap_layout_census.py /disasm` on each compute carve. Of 5,450 indexed compute + entries, 2,959 advertise direct indexing and none of those embeds its root signature. Adding + `--group fspx_compute --dispatch-log ` joined seven resource-indexing entries to independently + recorded layouts. In all seven, a dynamically indexed resource descriptor used the first SGPR after the explicit + arguments. There were zero mismatches and zero cases without room **among those seven**. For the remaining + 2,952 entries the layout is unknown. These are entries across carves, which can contain the same program. + No sampler-indexing entry had a matched layout. Putting the resource heap first when both flags are set, then the + sampler in the next dword, remains a hypothesis. D3D-329's adjacent SGPR examples alone do not establish it. + + Each direct or indirect compute dispatch records the 32-bit arena offsets at those positions. An unbound heap + contributes zero. Rebinding affects subsequent commands. A heap that cannot fit in the inline user data is + reported once. `LEONIDA_COMPUTE_DIRECT_HEAPS=0` restores the previous arguments. Spilled signatures and graphics + stages remain open on question 3. 3. **Game-built descriptor memory.** The game writes raw T#/S# bytes into a heap itself, without calling `CreateShaderResourceView`. The shaders then read those bytes exactly as in case 1. diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 4f4904e965..125ce4c005 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -858,7 +858,7 @@ class GraphicsCommandList final if (kind == leonida::IndirectKind::dispatch && max_command_count) { // the pipeline and root arguments a Dispatch would record if (!compute_pipeline_ || !compute_.layout) return check(false); cmd.pipeline = compute_pipeline_; - cmd.user_data = compute_.data; + cmd.user_data = compute_user_data(); } check(list_.execute_indirect(cmd)); } @@ -1339,19 +1339,20 @@ class GraphicsCommandList final if ((cbv && cbv != cbv_srv_uav_heap_) || (smp && smp != sampler_heap_)) check(false); } - void note_direct_heap_indexing(const RootArgumentLayout* layout) const { - if (!layout) return; + void note_direct_heap_indexing(const RootArgumentLayout* layout, bool compute) const { if (layout->flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) { if (!cbv_srv_uav_heap_) - note_once("draw/dispatch uses CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED with no CBV/SRV/UAV heap bound"); - else - note_once("CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED heap base tracked on list (SGPR slot open, section 3.4)"); + note_once(compute ? "dispatch uses direct resource indexing with no CBV/SRV/UAV heap bound" + : "draw uses direct resource indexing with no CBV/SRV/UAV heap bound"); + else if (!compute) + note_once("draw uses direct resource indexing; graphics heap-base SGPR is not supplied"); } if (layout->flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) { if (!sampler_heap_) - note_once("draw/dispatch uses SAMPLER_HEAP_DIRECTLY_INDEXED with no sampler heap bound"); - else - note_once("SAMPLER_HEAP_DIRECTLY_INDEXED heap base tracked on list (SGPR slot open, section 3.4)"); + note_once(compute ? "dispatch uses direct sampler indexing with no sampler heap bound" + : "draw uses direct sampler indexing with no sampler heap bound"); + else if (!compute) + note_once("draw uses direct sampler indexing; graphics heap-base SGPR is not supplied"); } } @@ -1389,10 +1390,33 @@ class GraphicsCommandList final : leonida::IndexBufferView{}; } + // Section 3.4 documents the observed resource-heap slot. Appending flagged heaps in this + // order is a working hypothesis for signatures without a matched program and layout. + // Snapshot them for each command so rebinding a heap cannot change a recorded dispatch. + std::array compute_user_data() const { + note_direct_heap_indexing(compute_.layout, true); + auto data = compute_.data; + static const bool enabled = [] { + char value[2]{}; + return GetEnvironmentVariableA("LEONIDA_COMPUTE_DIRECT_HEAPS", value, 2) != 1 || value[0] != '0'; + }(); + if (!enabled) return data; + const auto flags = compute_.layout->flags; + auto slot = compute_.layout->compute_arguments_end; + if (flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) { + if (slot < data.size()) data[slot++] = static_cast(cbv_srv_uav_base_); + else note_once("compute root arguments leave no inline SGPR for the resource heap"); + } + if (flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) { + if (slot < data.size()) data[slot] = static_cast(sampler_base_); + else note_once("compute root arguments leave no inline SGPR for the sampler heap"); + } + return data; + } + void record_dispatch(UINT x, UINT y, UINT z) { if (!compute_pipeline_ || !compute_.layout) return check(false); - note_direct_heap_indexing(compute_.layout); - check(list_.dispatch({compute_pipeline_, compute_.data, x, y, z})); + check(list_.dispatch({compute_pipeline_, compute_user_data(), x, y, z})); } // The views block a draw records. Rebuilt only when the render targets or the bound vertex buffers change. @@ -1411,7 +1435,7 @@ class GraphicsCommandList final // A draw needs a graphics pipeline, a graphics root signature and a topology. void record_draw(bool indexed, UINT count, UINT instances, UINT first, INT base_vertex, UINT first_instance) { if (!graphics_pipeline_ || !graphics_.layout || !topology_) return check(false); - note_direct_heap_indexing(graphics_.layout); + note_direct_heap_indexing(graphics_.layout, false); // No viewport (never set, or unbound with RSSetViewports(0)) or an empty one: D3D12 rasterizes nothing, // and Vulkan forbids a 0x0 viewport, so the draw is not recorded. if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index c0ff3cf8da..8b641e3921 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -397,6 +397,7 @@ struct RootArgumentLayout { std::uint32_t flags = 0; // D3D12_ROOT_SIGNATURE_FLAGS from the serialized blob bool graphics_ok = true; bool compute_ok = true; + std::uint32_t compute_arguments_end = rt::rootsig::kNoSgpr; }; // For the command list: the argument layout of a root signature from a Vulkan device, and the id it records for a diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 97ed334a11..ef743c654b 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -6044,6 +6044,7 @@ class Device final layout.flags = parsed.sig.flags; layout.graphics_ok = packed.ok; layout.compute_ok = compute.ok; + if (compute.ok) layout.compute_arguments_end = compute.end_sgpr; for (std::size_t i = 0; i < parsed.sig.params.size(); ++i) { std::uint32_t first = UINT32_MAX; for (std::uint32_t d = 0; packed.ok && d < packed.dword_count; ++d) diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp index 5ba3ded525..1f5d534819 100644 --- a/runtime/test/d3d12_compute_test.cpp +++ b/runtime/test/d3d12_compute_test.cpp @@ -559,6 +559,127 @@ int main() { IID_PPV_ARGS(&list.p)))); EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + // Direct and indirect compute commands snapshot the bound shader heaps after s4..s8. + // Rebinding just the resource heap clears the sampler for the later command. + { + auto direct_desc = root_desc; + direct_desc.Desc_1_0.Flags = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | + D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED; + const auto direct_blob = serialize(direct_desc); + Ref direct_root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, direct_blob.data(), direct_blob.size(), IID_PPV_ARGS(&direct_root.p)))); + auto pipeline_desc = pso_desc; + pipeline_desc.pRootSignature = direct_root.p; + Ref direct_pso; + EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pipeline_desc, IID_PPV_ARGS(&direct_pso.p)))); + Ref sampler; + auto sampler_desc = heap_desc; + sampler_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&sampler_desc, IID_PPV_ARGS(&sampler.p)))); + const auto smp = reinterpret_cast(slot(sampler.p, 10))(sampler.p); + const D3D12_INDIRECT_ARGUMENT_DESC arg{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH}; + const D3D12_COMMAND_SIGNATURE_DESC signature_desc{12, 1, &arg, 0}; + Ref signature; + EXPECT(SUCCEEDED(device->CreateCommandSignature(&signature_desc, nullptr, IID_PPV_ARGS(&signature.p)))); + list->SetPipelineState(direct_pso.p); + list->SetComputeRootSignature(direct_root.p); + ID3D12DescriptorHeap* both[] = {sampler.p, heap.p}; + list->SetDescriptorHeaps(2, both); + list->SetComputeRootDescriptorTable(2, {gpu + 32}); + list->Dispatch(1, 1, 1); + Ref bundle_allocator; + Ref bundle; + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_BUNDLE, IID_PPV_ARGS(&bundle_allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_BUNDLE, bundle_allocator.p, nullptr, + IID_PPV_ARGS(&bundle.p)))); + bundle->Dispatch(1, 1, 1); + EXPECT(SUCCEEDED(bundle->Close())); + list->ExecuteBundle(bundle.p); + list->SetDescriptorHeaps(1, &heap.p); + list->ExecuteIndirect(signature.p, 1, out_a.p, 0, nullptr, 0); + list->SetDescriptorHeaps(1, &sampler.p); + list->ExecuteIndirect(signature.p, 1, out_a.p, 0, nullptr, 0); + // 27 constants starting at s4 leave room for one heap. At 28, s31 is explicit too. + for (UINT count : {27u, 28u}) { + auto constants_param = params[0]; + constants_param.Constants.Num32BitValues = count; + auto full_desc = direct_desc; + full_desc.Desc_1_0.NumParameters = 1; + full_desc.Desc_1_0.pParameters = &constants_param; + const auto blob = serialize(full_desc); + Ref full; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&full.p)))); + pipeline_desc.pRootSignature = full.p; + Ref full_pso; + EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pipeline_desc, IID_PPV_ARGS(&full_pso.p)))); + list->SetPipelineState(full_pso.p); + list->SetComputeRootSignature(full.p); + list->SetComputeRoot32BitConstant(0, 123, count - 1); + list->SetDescriptorHeaps(2, both); + list->Dispatch(1, 1, 1); + } + EXPECT(SUCCEEDED(list->Close())); + std::vector commands; + EXPECT(rt::d3d12::recorded_commands(list.p, commands) && commands.size() == 6); + const auto& before = std::get(commands[0]).user_data; + const auto& after = std::get(commands[2]).user_data; + char setting[2]{}; + const bool enabled = GetEnvironmentVariableA("LEONIDA_COMPUTE_DIRECT_HEAPS", setting, 2) != 1 || + setting[0] != '0'; + EXPECT(before[8] == gpu + 32 && before[9] == (enabled ? gpu : 0) && before[10] == (enabled ? smp : 0)); + EXPECT(after[8] == gpu + 32 && after[9] == (enabled ? gpu : 0) && after[10] == 0); + EXPECT(std::get(commands[1]).user_data == before); + const auto& sampler_only = std::get(commands[3]).user_data; + EXPECT(sampler_only[9] == 0 && sampler_only[10] == (enabled ? smp : 0)); + const auto& one_slot = std::get(commands[4]).user_data; + EXPECT(one_slot[30] == 123 && one_slot[31] == (enabled ? gpu : 0)); + EXPECT(std::get(commands[5]).user_data[31] == 123); + EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); + // The shader follows the V# at the heap index in s4. Slot 1 and the unrelated explicit table are null. + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Buffer.NumElements = 4; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(nullptr, &srv, {cpu + 32}); + device->CreateShaderResourceView(constants.p, &srv, {cpu + 2 * 32}); + list->SetComputeRootSignature(direct_root.p); + list->SetPipelineState(direct_pso.p); + list->SetDescriptorHeaps(2, both); + list->SetComputeRootDescriptorTable(2, {gpu + 32}); + list->SetComputeRootUnorderedAccessView(1, va_a); + for (UINT index = 1; index <= 2; ++index) { + const UINT inputs[] = {index, 0xfffffffcu}; + list->SetComputeRoot32BitConstants(0, 2, inputs, 0); + list->Dispatch(1, 1, 1); + const auto copy = transition(out_a.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, ©); + list->CopyBufferRegion(readback.p, (index - 1) * bytes, out_a.p, 0, bytes); + const auto resume = transition(out_a.p, D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list->ResourceBarrier(1, &resume); + } + EXPECT(SUCCEEDED(list->Close())); + ID3D12CommandList* submitted[] = {list.p}; + queue->ExecuteCommandLists(1, submitted); + Ref done; + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&done.p)))); + EXPECT(SUCCEEDED(queue->Signal(done.p, 1)) && SUCCEEDED(done->SetEventOnCompletion(1, nullptr))); + void* results{}; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &results))); + const auto* values = static_cast(results); + for (UINT i = 0; i < elements; ++i) { + EXPECT(values[i] == 0); + EXPECT(values[elements + i] == (enabled ? table_values[i % 4] : 0)); + } + readback->Unmap(0, nullptr); + std::puts(enabled ? "directly indexed compute heap: 64 buffer reads and 64 null controls matched" + : "directly indexed compute heap disabled: 128 zero controls matched"); + EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr))); + } + // Misuse is reported by Close: a dispatch without a pipeline, a root view set on a constants parameter. list->Dispatch(1, 1, 1); EXPECT(list->Close() == E_INVALIDARG); diff --git a/runtime/test/glsl/cs_user_data.comp b/runtime/test/glsl/cs_user_data.comp index b285c0f3f9..110d611b76 100644 --- a/runtime/test/glsl/cs_user_data.comp +++ b/runtime/test/glsl/cs_user_data.comp @@ -39,6 +39,21 @@ void main() { const uint i = gl_GlobalInvocationID.x; Words table = at(uvec2(pc.s[8], 0u)); Words result = at(uvec2(pc.s[6], pc.s[7])); + if (pc.s[5] == 0xFFFFFFFCu) { + // Direct resource indexing. The explicit table is unrelated; the heap follows it at s9. + uint value = 0u; + if (pc.s[9] != 0u) { + Words view = at(uvec2(pc.s[9] + 32u * pc.s[4], 0u)); + uint byteOffset = (i % 4u) * 4u; + if (view.w[2] >= byteOffset + 4u) { + // V# buffer addresses are signed 48-bit offsets from heap_base. + uint high = uint(int(view.w[1] << 16u) >> 16); + value = at(uvec2(view.w[0], high)).w[byteOffset / 4u]; + } + } + result.w[i] = value; + return; + } if (pc.s[5] == 0u) { // CBV V# mode: table holds a 16-byte GFX10 raw buffer descriptor written by CreateConstantBufferView. const uint num_records = table.w[2]; diff --git a/tests/test_compute_heap_layout_census.py b/tests/test_compute_heap_layout_census.py new file mode 100644 index 0000000000..86507174ea --- /dev/null +++ b/tests/test_compute_heap_layout_census.py @@ -0,0 +1,64 @@ +"""Compute heap layout census on synthetic shader containers, listings and dispatch logs.""" +from pathlib import Path +import struct +import sys +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from test_heap_index_census import Work, SFI0_RES, SFI0_SMP +from test_rootsig_census import container, rts0 +import compute_heap_layout_census as c + + +class ComputeHeapLayout(unittest.TestCase): + def test_compare_programs(self): + work = Work() + self.addCleanup(work.close) + root = Path(work.root) + both = c.RESOURCE | c.SAMPLER + + def program(name, res, smp, constants=3, flags=both, used=SFI0_RES | SFI0_SMP, embedded=True): + lines = [(f"s_mov_b32 s20, s{res}", 4), ("s_mov_b32 s21, 0", 4), + ("s_load_dwordx8 s[32:39], s[20:21], s4", 8), + (f"s_mov_b32 s20, s{smp}", 4), ("s_load_dwordx4 s[40:43], s[20:21], s4", 8), + ("image_sample v[0:3], v[4:5], s[32:39], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D", 8), + ("s_endpgm", 4)] + work.add(name, "cs", used, lines, rsrc2=12 << 1) + if embedded: + payload = rts0(params=[("constants", 0, constants)], flags=flags) + (root / (name + ".dxbc")).write_bytes(container([(b"SFI0", struct.pack("/disasm + [--dispatch-log LOG ... --group GROUP] [--per-program] + +Read the carve index, each compute container's SFI0 and embedded RTS0, and the listing and +launch metadata for comparable programs. An optional integration dispatch log pairs compute-layout +parameter records with compute-input program names by PSO within that log. Use one carve group +per invocation. Entries in different carves need not be unique programs. +""" +import argparse +from collections import Counter, defaultdict +import json +import re +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import heap_index_census as heap +import shader_meta +import rootsig_census as roots + +RESOURCE, SAMPLER = 0x400, 0x800 # D3D12 root-signature flags +PARAM = re.compile(r" \(s(\d+) type=(\d+) const=(\d+) slots=\d+\)") + + +def captured_layouts(logs, group): + by_name = defaultdict(set) + for path in logs: + # Never join handles across processes, or a reused handle with ambiguous ownership. + names, layouts = defaultdict(set), defaultdict(set) + with path.open(encoding="utf-8", errors="replace") as stream: + for line in stream: + if "[rt] compute-layout:" in line: + match = re.search(r"compute-layout: pso=(\w+) flags=([\da-fA-F]+) .*?shader-heap=\S+(.*)$", line) + if not match: + continue + handle, flags, tail = match.groups() + end, tables = 4, [] + valid = not PARAM.sub("", tail).strip() + for slot, kind, count in PARAM.findall(tail): + width = {"0": int(count), "1": 2, "2": 1}.get(kind, 0) + valid &= int(slot) == end and width > 0 + if kind == "2": + tables.append(end) + end += width + layouts[handle].add((int(flags, 16), end, tuple(tables)) if valid else None) + elif "compute-input: execute=" in line and " pso=" in line: + m = re.search(r" name=(\S+) pso=(\w+)", line) + if m: + names[m[2]].add(m[1]) + for handle, programs in names.items(): + for program in programs: + prefix, _, name = program.rpartition("/") + if prefix == group: + by_name[name].update(layouts[handle] if len(programs) == 1 else {None}) + return by_name + + +def embedded_layout(payload): + sig, error = roots.parse_rts0(payload) + if error: + return None + end, tables = 4, [] + for p in sig["params"]: + if p["type"] == "table": + tables.append(end) + end += 1 + else: + end += p["count"] if p["type"] == "constants" else 2 + return sig["flags"], end, tuple(tables) + + +def compare(kind, layout, loads): + flags, end, tables = layout + if not flags & kind: + return "incompatible flags" + expected = end + (kind == SAMPLER and bool(flags & RESOURCE)) + if expected >= 32: + return "no room" + roles = {"V#", "T#"} if kind == RESOURCE else {"S#"} + # Declared tables can use dynamic offsets too. Never use the predicted heap slot + # to choose among multiple remaining candidates. + candidates = set() + for load in loads: + if not roles.intersection(load["roles"]) or load["offset"][0] != "dynamic": + continue + base = re.fullmatch(r"user s(\d+)", load["base"]) + if not base or load["ptr"] != "ptr32": + return "inconclusive" + reg = int(base[1]) + if reg not in tables: + candidates.add(reg) + if len(candidates) != 1: + return "inconclusive" + return "match" if expected in candidates else "mismatch" + + +def program_loads(disasm, name): + user = heap.cs_user_count(disasm, name) + launch = disasm.parent / "fspx" / (name + ".json") + if user is None and launch.exists(): + user = json.loads(launch.read_bytes()).get("user_sgprs") + listing = disasm / (name + ".s") + if user is not None and listing.is_file(): + ir = heap.shader_ir.parse_file(str(listing)) + if ir["insns"] and not ir["invalid"]: + try: + return heap.analyse(ir["insns"], "cs", user) + except heap.Skip: + pass + return [] + + +def census(disasm, captured, per_program=False): + result = Counter() + for name, stage in heap.stage_index(disasm).items(): + if stage != "cs": + continue + result["compute"] += 1 + chunks = roots.parts((disasm.parent / (name + ".dxbc")).read_bytes()) + sfi = chunks.get(b"SFI0", b"") + if len(sfi) < 8: + result["missing SFI0"] += 1 + continue + bits = struct.unpack_from(" Date: Tue, 24 Nov 2026 21:38:59 +0100 Subject: [PATCH 2/3] RT-DIRECT-HEAP-GRAPHICS: graphics draws supply the directly indexed heaps after their root arguments With CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED / SAMPLER_HEAP_DIRECTLY_INDEXED a console program reads the resource heap's address in the dword after its root arguments and the sampler heap's in the next, from s8 in VS/PS/GS and s16 in mesh shaders (DadaCap, issue #14 comment 7143020922), as #1064 does for compute. DrawInstanced, DrawIndexedInstanced and DispatchMesh now record them at RootArgumentLayout::graphics_arguments_end; a mesh shader reads the same push dwords through the #974 window. Nothing is written for a signature with parameters in the argument block or under LEONIDA_GRAPHICS_ROOT_LAYOUT=pc (no slot is measured there); LEONIDA_GRAPHICS_DIRECT_HEAPS=0 restores the previous arguments. d3d12_mesh_test checks a vertex and a mesh draw, a rebind, a signature ending at s30 and a spilled one. --- docs/d3d12_vulkan.md | 15 +++++- runtime/shims/d3d12_com.cpp | 42 ++++++++++++++--- runtime/shims/d3d12_com.h | 4 ++ runtime/shims/d3d12_vulkan_device.cpp | 1 + runtime/test/d3d12_mesh_test.cpp | 67 ++++++++++++++++++++++++++- 5 files changed, 118 insertions(+), 11 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index ef66c6f48d..e0cf023435 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1625,8 +1625,19 @@ The game can use D3D12 descriptors in three ways, and the layer must handle all Each direct or indirect compute dispatch records the 32-bit arena offsets at those positions. An unbound heap contributes zero. Rebinding affects subsequent commands. A heap that cannot fit in the inline user data is - reported once. `LEONIDA_COMPUTE_DIRECT_HEAPS=0` restores the previous arguments. Spilled signatures and graphics - stages remain open on question 3. + reported once. `LEONIDA_COMPUTE_DIRECT_HEAPS=0` restores the previous arguments. Spilled signatures remain open + on question 3. + + **Graphics stages (RT-DIRECT-HEAP-GRAPHICS).** The same two dwords follow the graphics root arguments: from s8 in + VS/PS/GS and s16 in mesh shaders, every directly indexed program of the retail library reads the resource heap's + address in the dword after its root arguments and the sampler heap's in the next one (issue #14, comment + 7143020922, measured on the retail title with DadaCap's `boot-prototype`). Each `DrawInstanced`, + `DrawIndexedInstanced` and `DispatchMesh` records them right after the inline graphics arguments + (`RootArgumentLayout::graphics_arguments_end`); a mesh shader reads the same push dwords through its window + (section 3.5). An unbound heap contributes zero, a heap past s31 is reported once, and a signature with + parameters in the argument block, or under `LEONIDA_GRAPHICS_ROOT_LAYOUT=pc`, gets nothing written (no slot is + measured there). `LEONIDA_GRAPHICS_DIRECT_HEAPS=0` restores the previous arguments. `d3d12_mesh_test` checks a + vertex and a mesh draw, a rebind, a signature ending at s30 and a spilled one. 3. **Game-built descriptor memory.** The game writes raw T#/S# bytes into a heap itself, without calling `CreateShaderResourceView`. The shaders then read those bytes exactly as in case 1. diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 26d02f3259..e3f758fae0 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -492,7 +492,7 @@ class GraphicsCommandList final return check(false); } if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; // as record_draw: nothing is rasterized - leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, {}, 0, viewport_, + leonida::Draw draw{graphics_pipeline_, graphics_user_data(), draw_views(), depth_, {}, 0, viewport_, scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, false, x, y, z, 0, 0}; draw.mesh = true; check(list_.draw(std::move(draw))); @@ -1362,15 +1362,11 @@ class GraphicsCommandList final if (!cbv_srv_uav_heap_) note_once(compute ? "dispatch uses direct resource indexing with no CBV/SRV/UAV heap bound" : "draw uses direct resource indexing with no CBV/SRV/UAV heap bound"); - else if (!compute) - note_once("draw uses direct resource indexing; graphics heap-base SGPR is not supplied"); } if (layout->flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) { if (!sampler_heap_) note_once(compute ? "dispatch uses direct sampler indexing with no sampler heap bound" : "draw uses direct sampler indexing with no sampler heap bound"); - else if (!compute) - note_once("draw uses direct sampler indexing; graphics heap-base SGPR is not supplied"); } } @@ -1432,6 +1428,39 @@ class GraphicsCommandList final return data; } + // The graphics side of the same layout (RT-DIRECT-HEAP-GRAPHICS): with CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED the dword + // after the graphics root arguments holds the resource heap's 32-bit address, and with + // SAMPLER_HEAP_DIRECTLY_INDEXED the next one the sampler heap's; every directly indexed program of the retail + // library reads them there, from s4 in compute, s8 in VS/PS/GS and s16 in mesh shaders (issue #14, comment + // 7143020922). A mesh shader reads the same dwords through its window (+8). Not written when the signature has no + // measured slot for them (graphics_arguments_end) or under LEONIDA_GRAPHICS_DIRECT_HEAPS=0. + std::array graphics_user_data() const { + note_direct_heap_indexing(graphics_.layout, false); + auto data = graphics_.data; + static const bool enabled = [] { + char value[2]{}; + return GetEnvironmentVariableA("LEONIDA_GRAPHICS_DIRECT_HEAPS", value, 2) != 1 || value[0] != '0'; + }(); + const auto flags = graphics_.layout->flags; + const bool direct = flags & (D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | + D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED); + if (!enabled || !direct) return data; + auto slot = graphics_.layout->graphics_arguments_end; + if (slot == rt::rootsig::kNoSgpr) { + note_once("draw uses direct heap indexing; its root signature has no measured slot for the heap addresses"); + return data; + } + if (flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) { + if (slot < data.size()) data[slot++] = static_cast(cbv_srv_uav_base_); + else note_once("graphics root arguments leave no inline SGPR for the resource heap"); + } + if (flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) { + if (slot < data.size()) data[slot] = static_cast(sampler_base_); + else note_once("graphics root arguments leave no inline SGPR for the sampler heap"); + } + return data; + } + void record_dispatch(UINT x, UINT y, UINT z) { if (!compute_pipeline_ || !compute_.layout) return check(false); check(list_.dispatch({compute_pipeline_, compute_user_data(), x, y, z})); @@ -1453,11 +1482,10 @@ class GraphicsCommandList final // A draw needs a graphics pipeline, a graphics root signature and a topology. void record_draw(bool indexed, UINT count, UINT instances, UINT first, INT base_vertex, UINT first_instance) { if (!graphics_pipeline_ || !graphics_.layout || !topology_) return check(false); - note_direct_heap_indexing(graphics_.layout, false); // No viewport (never set, or unbound with RSSetViewports(0)) or an empty one: D3D12 rasterizes nothing, // and Vulkan forbids a 0x0 viewport, so the draw is not recorded. if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; - leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, index_, topology_, viewport_, + leonida::Draw draw{graphics_pipeline_, graphics_user_data(), draw_views(), depth_, index_, topology_, viewport_, scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances, first, base_vertex, first_instance}; check(list_.draw(std::move(draw))); diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 4c834485ad..f79b143185 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -405,6 +405,10 @@ struct RootArgumentLayout { bool mesh_ok = true; // the graphics layout also fits a mesh shader's 16-dword window bool compute_ok = true; std::uint32_t compute_arguments_end = rt::rootsig::kNoSgpr; + // One past the last graphics root dword (the push dword where a VS/PS/GS reads s, a mesh shader s), + // where the directly indexed heaps' addresses follow (RT-DIRECT-HEAP-GRAPHICS). kNoSgpr when the graphics layout is + // not the console's, or when a parameter went to the argument block: no slot is measured for the heaps then. + std::uint32_t graphics_arguments_end = rt::rootsig::kNoSgpr; }; // For the command list: the argument layout of a root signature from a Vulkan device, and the id it records for a diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index ac91f788b7..05909c8beb 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -6092,6 +6092,7 @@ class Device final layout.mesh_ok = graphics_console && mesh.ok; layout.compute_ok = compute.ok; if (compute.ok) layout.compute_arguments_end = compute.end_sgpr; + if (graphics_console && graphics.first_spilled == SIZE_MAX) layout.graphics_arguments_end = graphics.end_sgpr; for (std::size_t i = 0; i < parsed.sig.params.size(); ++i) { std::uint32_t first = rt::rootsig::kNoSgpr; if (graphics_console) { diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp index ccde1658b1..f39f5ef658 100644 --- a/runtime/test/d3d12_mesh_test.cpp +++ b/runtime/test/d3d12_mesh_test.cpp @@ -175,13 +175,14 @@ int main() { }; // Twenty constants: s8..s27 for a pixel shader, but past a mesh shader's 16-dword window (s16..s31). Thirty: // past the graphics window (24 from s8) and the compute one (28 from s4) too, as a retail start-up signature is. - const auto wide_root_signature = [&](ID3D12Device* device, Ref& root, UINT values = 20) { + const auto wide_root_signature = [&](ID3D12Device* device, Ref& root, UINT values = 20, + D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE) { D3D12_ROOT_PARAMETER param{}; param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; param.Constants = {0, 0, values}; D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; - root_desc.Desc_1_0 = {1, ¶m, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + root_desc.Desc_1_0 = {1, ¶m, 0, nullptr, flags}; const auto blob = serialize_root_signature(root_desc); return !blob.empty() && SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root.p))); @@ -473,6 +474,68 @@ int main() { list->RSSetViewports(1, &viewport); list6->DispatchMesh(1, 1, 1); EXPECT(SUCCEEDED(list->Close())); + + // RT-DIRECT-HEAP-GRAPHICS: with the directly-indexed flags, the dword after the graphics root arguments + // holds the resource heap's 32-bit address and the next one the sampler heap's, for vertex and mesh draws + // alike (a mesh shader reads them through its window). 4 constants take s8..s11, so the heaps are at 12 + // and 13; 23 constants leave room for the resource heap only (s31); a signature with spilled parameters + // (30 constants) has no measured slot, so nothing is written past what the title set. + const auto direct = static_cast( + D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | + D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED); + Ref direct4, direct23, direct30; + EXPECT(wide_root_signature(device.p, direct4, 4, direct)); + EXPECT(wide_root_signature(device.p, direct23, 23, direct)); + EXPECT(wide_root_signature(device.p, direct30, 30, direct)); + D3D12_DESCRIPTOR_HEAP_DESC resources_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + auto samplers_desc = resources_desc; + samplers_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER; + Ref resources, samplers; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&resources_desc, IID_PPV_ARGS(&resources.p)))); + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&samplers_desc, IID_PPV_ARGS(&samplers.p)))); + const std::uint64_t res_va = reinterpret_cast(slot(resources.p, 10))(resources.p); + const std::uint64_t smp_va = reinterpret_cast(slot(samplers.p, 10))(samplers.p); + EXPECT(res_va && res_va < (1ull << 32) && smp_va && smp_va < (1ull << 32)); + const std::array four{1, 2, 3, 4}; + ID3D12DescriptorHeap* both[] = {resources.p, samplers.p}; + EXPECT(SUCCEEDED(list->Reset(allocator.p, vs_pso.p))); + list->SetDescriptorHeaps(2, both); + list->SetGraphicsRootSignature(direct4.p); + list->SetGraphicsRoot32BitConstants(0, 4, four.data(), 0); + list->RSSetViewports(1, &viewport); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->DrawInstanced(3, 1, 0, 0); + list->SetPipelineState(mesh_pso.p); + list6->DispatchMesh(1, 1, 1); + list->SetPipelineState(vs_pso.p); + list->SetDescriptorHeaps(1, &resources.p); // rebinding only the resource heap unbinds the sampler heap + list->DrawInstanced(3, 1, 0, 0); + list->SetDescriptorHeaps(2, both); + list->SetGraphicsRootSignature(direct23.p); + list->SetGraphicsRoot32BitConstant(0, 77, 22); + list->DrawInstanced(3, 1, 0, 0); + list->SetGraphicsRootSignature(direct30.p); + list->DrawInstanced(3, 1, 0, 0); + EXPECT(SUCCEEDED(list->Close())); + std::vector commands; + EXPECT(rt::d3d12::recorded_commands(list.p, commands)); + std::vector draws; + for (const auto& command : commands) + if (const auto* recorded = std::get_if(&command)) draws.push_back(recorded); + EXPECT(draws.size() == 5); + char setting[2]{}; + const bool enabled = GetEnvironmentVariableA("LEONIDA_GRAPHICS_DIRECT_HEAPS", setting, 2) != 1 || + setting[0] != '0'; + const auto res = enabled ? std::uint32_t(res_va) : 0u, smp = enabled ? std::uint32_t(smp_va) : 0u; + const auto& vertex = draws[0]->user_data; + EXPECT(vertex[8] == 1 && vertex[11] == 4 && vertex[12] == res && vertex[13] == smp); + EXPECT(draws[1]->mesh && draws[1]->user_data == vertex); // the mesh draw: the same dwords + EXPECT(draws[2]->user_data[12] == res && draws[2]->user_data[13] == 0); + EXPECT(draws[3]->user_data[30] == 77 && draws[3]->user_data[31] == res); + for (std::uint32_t k = 0; k < 32; ++k) EXPECT(draws[4]->user_data[k] == 0); + std::printf("direct heaps on graphics draws: resource heap at s%u, sampler heap at s%u%s\n", 12u, 13u, + enabled ? "" : " (LEONIDA_GRAPHICS_DIRECT_HEAPS=0: not written)"); } EXPECT(SUCCEEDED(queue->Signal(fence.p, 2)) && SUCCEEDED(fence->SetEventOnCompletion(2, nullptr))); From c8f7515e2e6fb2a2a61eb1e986ee8c6fd4431399 Mon Sep 17 00:00:00 2001 From: Moriz82 <72836413+Moriz82@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:01:43 -0600 Subject: [PATCH 3/3] d3d12: supply directly indexed heaps to compute dispatches (RT-DIRECT-HEAP-COMPUTE) Compute shaders using direct resource indexing received a zero heap pointer. Snapshot each bound heap offset after the explicit inline root arguments on direct and indirect dispatches, so each command retains the bindings it had when recorded. When the explicit arguments leave no SGPR, keep them and report the missing heap slot once. The placement is a hypothesis with partial evidence. Of 2,959 direct-indexing compute entries, seven could be paired with recorded layouts. All seven resource reads agree with the predicted slot. The other 2,952 have no paired layout, and no paired sampler read establishes the relative heap order. tools/compute_heap_layout_census.py reproduces the count, with synthetic tests for agreement, disagreement and missing evidence. Built gta6rt and d3d12_compute_test with clang-cl. The Proton Vulkan fixture passed 64 buffer reads and 64 null controls on an RTX 4070. With the rollback switch, all 128 controls read zero. Both runs check the recorded arguments for bundle inheritance, indirect heap rebinding and the last inline SGPR. The synthetic SPIR-V fixture passed validation. AI-assisted (Codex and Claude Code agents). Co-authored-by: Plaaasma <47513553+Plaaasma@users.noreply.github.com> Co-Authored-By: Claude Fable 5.2 --- docs/d3d12_vulkan.md | 18 ++- runtime/shims/d3d12_com.cpp | 48 +++++-- runtime/shims/d3d12_com.h | 1 + runtime/shims/d3d12_vulkan_device.cpp | 1 + runtime/test/d3d12_compute_test.cpp | 121 ++++++++++++++++ runtime/test/glsl/cs_user_data.comp | 15 ++ tests/test_compute_heap_layout_census.py | 64 +++++++++ tools/compute_heap_layout_census.py | 168 +++++++++++++++++++++++ 8 files changed, 422 insertions(+), 14 deletions(-) create mode 100644 tests/test_compute_heap_layout_census.py create mode 100644 tools/compute_heap_layout_census.py diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 90828d409c..d2ae9d500f 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1611,8 +1611,22 @@ The game can use D3D12 descriptors in three ways, and the layer must handle all translator input. No stride is read at run time: static offsets of T# loads are multiples of 32 and of S# loads multiples of 16, so the stride is compiled into the code. In the runtime shim, `CreateRootSignature` records the `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` and `SAMPLER_HEAP_DIRECTLY_INDEXED` root-signature flags and `SetDescriptorHeaps` - tracks the bound shader-visible heap GPU bases (`d3d12_set_descriptor_heaps`), while placing those bases into - per-stage user SGPRs remains open on question 3. + tracks the bound shader-visible heap GPU bases (`d3d12_set_descriptor_heaps`). + + **Inline compute layout (integration #984).** Run + `python -I tools/compute_heap_layout_census.py /disasm` on each compute carve. Of 5,450 indexed compute + entries, 2,959 advertise direct indexing and none of those embeds its root signature. Adding + `--group fspx_compute --dispatch-log ` joined seven resource-indexing entries to independently + recorded layouts. In all seven, a dynamically indexed resource descriptor used the first SGPR after the explicit + arguments. There were zero mismatches and zero cases without room **among those seven**. For the remaining + 2,952 entries the layout is unknown. These are entries across carves, which can contain the same program. + No sampler-indexing entry had a matched layout. Putting the resource heap first when both flags are set, then the + sampler in the next dword, remains a hypothesis. D3D-329's adjacent SGPR examples alone do not establish it. + + Each direct or indirect compute dispatch records the 32-bit arena offsets at those positions. An unbound heap + contributes zero. Rebinding affects subsequent commands. A heap that cannot fit in the inline user data is + reported once. `LEONIDA_COMPUTE_DIRECT_HEAPS=0` restores the previous arguments. Spilled signatures and graphics + stages remain open on question 3. 3. **Game-built descriptor memory.** The game writes raw T#/S# bytes into a heap itself, without calling `CreateShaderResourceView`. The shaders then read those bytes exactly as in case 1. diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 42c8e5cea7..9da7240efa 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -883,7 +883,7 @@ class GraphicsCommandList final if (kind == leonida::IndirectKind::dispatch && max_command_count) { // the pipeline and root arguments a Dispatch would record if (!compute_pipeline_ || !compute_.layout) return check(false); cmd.pipeline = compute_pipeline_; - cmd.user_data = compute_.data; + cmd.user_data = compute_user_data(); } check(list_.execute_indirect(cmd)); } @@ -1370,19 +1370,20 @@ class GraphicsCommandList final if ((cbv && cbv != cbv_srv_uav_heap_) || (smp && smp != sampler_heap_)) check(false); } - void note_direct_heap_indexing(const RootArgumentLayout* layout) const { - if (!layout) return; + void note_direct_heap_indexing(const RootArgumentLayout* layout, bool compute) const { if (layout->flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) { if (!cbv_srv_uav_heap_) - note_once("draw/dispatch uses CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED with no CBV/SRV/UAV heap bound"); - else - note_once("CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED heap base tracked on list (SGPR slot open, section 3.4)"); + note_once(compute ? "dispatch uses direct resource indexing with no CBV/SRV/UAV heap bound" + : "draw uses direct resource indexing with no CBV/SRV/UAV heap bound"); + else if (!compute) + note_once("draw uses direct resource indexing; graphics heap-base SGPR is not supplied"); } if (layout->flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) { if (!sampler_heap_) - note_once("draw/dispatch uses SAMPLER_HEAP_DIRECTLY_INDEXED with no sampler heap bound"); - else - note_once("SAMPLER_HEAP_DIRECTLY_INDEXED heap base tracked on list (SGPR slot open, section 3.4)"); + note_once(compute ? "dispatch uses direct sampler indexing with no sampler heap bound" + : "draw uses direct sampler indexing with no sampler heap bound"); + else if (!compute) + note_once("draw uses direct sampler indexing; graphics heap-base SGPR is not supplied"); } } @@ -1426,10 +1427,33 @@ class GraphicsCommandList final : leonida::IndexBufferView{}; } + // Section 3.4 documents the observed resource-heap slot. Appending flagged heaps in this + // order is a working hypothesis for signatures without a matched program and layout. + // Snapshot them for each command so rebinding a heap cannot change a recorded dispatch. + std::array compute_user_data() const { + note_direct_heap_indexing(compute_.layout, true); + auto data = compute_.data; + static const bool enabled = [] { + char value[2]{}; + return GetEnvironmentVariableA("LEONIDA_COMPUTE_DIRECT_HEAPS", value, 2) != 1 || value[0] != '0'; + }(); + if (!enabled) return data; + const auto flags = compute_.layout->flags; + auto slot = compute_.layout->compute_arguments_end; + if (flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) { + if (slot < data.size()) data[slot++] = static_cast(cbv_srv_uav_base_); + else note_once("compute root arguments leave no inline SGPR for the resource heap"); + } + if (flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) { + if (slot < data.size()) data[slot] = static_cast(sampler_base_); + else note_once("compute root arguments leave no inline SGPR for the sampler heap"); + } + return data; + } + void record_dispatch(UINT x, UINT y, UINT z) { if (!compute_pipeline_ || !compute_.layout) return check(false); - note_direct_heap_indexing(compute_.layout); - check(list_.dispatch({compute_pipeline_, compute_.data, x, y, z})); + check(list_.dispatch({compute_pipeline_, compute_user_data(), x, y, z})); } // The views block a draw records. Rebuilt only when the render targets or the bound vertex buffers change. @@ -1468,7 +1492,7 @@ class GraphicsCommandList final // A draw needs a graphics pipeline, a graphics root signature and a topology. void record_draw(bool indexed, UINT count, UINT instances, UINT first, INT base_vertex, UINT first_instance) { if (!graphics_pipeline_ || !graphics_.layout || !topology_) return check(false); - note_direct_heap_indexing(graphics_.layout); + note_direct_heap_indexing(graphics_.layout, false); // No viewport (never set, or unbound with RSSetViewports(0)) or every bound viewport empty: D3D12 rasterizes // nothing, and Vulkan forbids a 0x0 viewport, so the draw is not recorded. if (!any_nonempty_viewport()) return; diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 07233494bf..c989df064a 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -398,6 +398,7 @@ struct RootArgumentLayout { std::uint32_t flags = 0; // D3D12_ROOT_SIGNATURE_FLAGS from the serialized blob bool graphics_ok = true; bool compute_ok = true; + std::uint32_t compute_arguments_end = rt::rootsig::kNoSgpr; }; // For the command list: the argument layout of a root signature from a Vulkan device, and the id it records for a diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index f8a5f656dc..3e007bd71d 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -6086,6 +6086,7 @@ class Device final layout.flags = parsed.sig.flags; layout.graphics_ok = packed.ok; layout.compute_ok = compute.ok; + if (compute.ok) layout.compute_arguments_end = compute.end_sgpr; for (std::size_t i = 0; i < parsed.sig.params.size(); ++i) { std::uint32_t first = UINT32_MAX; for (std::uint32_t d = 0; packed.ok && d < packed.dword_count; ++d) diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp index 5ba3ded525..1f5d534819 100644 --- a/runtime/test/d3d12_compute_test.cpp +++ b/runtime/test/d3d12_compute_test.cpp @@ -559,6 +559,127 @@ int main() { IID_PPV_ARGS(&list.p)))); EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + // Direct and indirect compute commands snapshot the bound shader heaps after s4..s8. + // Rebinding just the resource heap clears the sampler for the later command. + { + auto direct_desc = root_desc; + direct_desc.Desc_1_0.Flags = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | + D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED; + const auto direct_blob = serialize(direct_desc); + Ref direct_root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, direct_blob.data(), direct_blob.size(), IID_PPV_ARGS(&direct_root.p)))); + auto pipeline_desc = pso_desc; + pipeline_desc.pRootSignature = direct_root.p; + Ref direct_pso; + EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pipeline_desc, IID_PPV_ARGS(&direct_pso.p)))); + Ref sampler; + auto sampler_desc = heap_desc; + sampler_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&sampler_desc, IID_PPV_ARGS(&sampler.p)))); + const auto smp = reinterpret_cast(slot(sampler.p, 10))(sampler.p); + const D3D12_INDIRECT_ARGUMENT_DESC arg{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH}; + const D3D12_COMMAND_SIGNATURE_DESC signature_desc{12, 1, &arg, 0}; + Ref signature; + EXPECT(SUCCEEDED(device->CreateCommandSignature(&signature_desc, nullptr, IID_PPV_ARGS(&signature.p)))); + list->SetPipelineState(direct_pso.p); + list->SetComputeRootSignature(direct_root.p); + ID3D12DescriptorHeap* both[] = {sampler.p, heap.p}; + list->SetDescriptorHeaps(2, both); + list->SetComputeRootDescriptorTable(2, {gpu + 32}); + list->Dispatch(1, 1, 1); + Ref bundle_allocator; + Ref bundle; + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_BUNDLE, IID_PPV_ARGS(&bundle_allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_BUNDLE, bundle_allocator.p, nullptr, + IID_PPV_ARGS(&bundle.p)))); + bundle->Dispatch(1, 1, 1); + EXPECT(SUCCEEDED(bundle->Close())); + list->ExecuteBundle(bundle.p); + list->SetDescriptorHeaps(1, &heap.p); + list->ExecuteIndirect(signature.p, 1, out_a.p, 0, nullptr, 0); + list->SetDescriptorHeaps(1, &sampler.p); + list->ExecuteIndirect(signature.p, 1, out_a.p, 0, nullptr, 0); + // 27 constants starting at s4 leave room for one heap. At 28, s31 is explicit too. + for (UINT count : {27u, 28u}) { + auto constants_param = params[0]; + constants_param.Constants.Num32BitValues = count; + auto full_desc = direct_desc; + full_desc.Desc_1_0.NumParameters = 1; + full_desc.Desc_1_0.pParameters = &constants_param; + const auto blob = serialize(full_desc); + Ref full; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&full.p)))); + pipeline_desc.pRootSignature = full.p; + Ref full_pso; + EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pipeline_desc, IID_PPV_ARGS(&full_pso.p)))); + list->SetPipelineState(full_pso.p); + list->SetComputeRootSignature(full.p); + list->SetComputeRoot32BitConstant(0, 123, count - 1); + list->SetDescriptorHeaps(2, both); + list->Dispatch(1, 1, 1); + } + EXPECT(SUCCEEDED(list->Close())); + std::vector commands; + EXPECT(rt::d3d12::recorded_commands(list.p, commands) && commands.size() == 6); + const auto& before = std::get(commands[0]).user_data; + const auto& after = std::get(commands[2]).user_data; + char setting[2]{}; + const bool enabled = GetEnvironmentVariableA("LEONIDA_COMPUTE_DIRECT_HEAPS", setting, 2) != 1 || + setting[0] != '0'; + EXPECT(before[8] == gpu + 32 && before[9] == (enabled ? gpu : 0) && before[10] == (enabled ? smp : 0)); + EXPECT(after[8] == gpu + 32 && after[9] == (enabled ? gpu : 0) && after[10] == 0); + EXPECT(std::get(commands[1]).user_data == before); + const auto& sampler_only = std::get(commands[3]).user_data; + EXPECT(sampler_only[9] == 0 && sampler_only[10] == (enabled ? smp : 0)); + const auto& one_slot = std::get(commands[4]).user_data; + EXPECT(one_slot[30] == 123 && one_slot[31] == (enabled ? gpu : 0)); + EXPECT(std::get(commands[5]).user_data[31] == 123); + EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); + // The shader follows the V# at the heap index in s4. Slot 1 and the unrelated explicit table are null. + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Buffer.NumElements = 4; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(nullptr, &srv, {cpu + 32}); + device->CreateShaderResourceView(constants.p, &srv, {cpu + 2 * 32}); + list->SetComputeRootSignature(direct_root.p); + list->SetPipelineState(direct_pso.p); + list->SetDescriptorHeaps(2, both); + list->SetComputeRootDescriptorTable(2, {gpu + 32}); + list->SetComputeRootUnorderedAccessView(1, va_a); + for (UINT index = 1; index <= 2; ++index) { + const UINT inputs[] = {index, 0xfffffffcu}; + list->SetComputeRoot32BitConstants(0, 2, inputs, 0); + list->Dispatch(1, 1, 1); + const auto copy = transition(out_a.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, ©); + list->CopyBufferRegion(readback.p, (index - 1) * bytes, out_a.p, 0, bytes); + const auto resume = transition(out_a.p, D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list->ResourceBarrier(1, &resume); + } + EXPECT(SUCCEEDED(list->Close())); + ID3D12CommandList* submitted[] = {list.p}; + queue->ExecuteCommandLists(1, submitted); + Ref done; + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&done.p)))); + EXPECT(SUCCEEDED(queue->Signal(done.p, 1)) && SUCCEEDED(done->SetEventOnCompletion(1, nullptr))); + void* results{}; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &results))); + const auto* values = static_cast(results); + for (UINT i = 0; i < elements; ++i) { + EXPECT(values[i] == 0); + EXPECT(values[elements + i] == (enabled ? table_values[i % 4] : 0)); + } + readback->Unmap(0, nullptr); + std::puts(enabled ? "directly indexed compute heap: 64 buffer reads and 64 null controls matched" + : "directly indexed compute heap disabled: 128 zero controls matched"); + EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr))); + } + // Misuse is reported by Close: a dispatch without a pipeline, a root view set on a constants parameter. list->Dispatch(1, 1, 1); EXPECT(list->Close() == E_INVALIDARG); diff --git a/runtime/test/glsl/cs_user_data.comp b/runtime/test/glsl/cs_user_data.comp index b285c0f3f9..110d611b76 100644 --- a/runtime/test/glsl/cs_user_data.comp +++ b/runtime/test/glsl/cs_user_data.comp @@ -39,6 +39,21 @@ void main() { const uint i = gl_GlobalInvocationID.x; Words table = at(uvec2(pc.s[8], 0u)); Words result = at(uvec2(pc.s[6], pc.s[7])); + if (pc.s[5] == 0xFFFFFFFCu) { + // Direct resource indexing. The explicit table is unrelated; the heap follows it at s9. + uint value = 0u; + if (pc.s[9] != 0u) { + Words view = at(uvec2(pc.s[9] + 32u * pc.s[4], 0u)); + uint byteOffset = (i % 4u) * 4u; + if (view.w[2] >= byteOffset + 4u) { + // V# buffer addresses are signed 48-bit offsets from heap_base. + uint high = uint(int(view.w[1] << 16u) >> 16); + value = at(uvec2(view.w[0], high)).w[byteOffset / 4u]; + } + } + result.w[i] = value; + return; + } if (pc.s[5] == 0u) { // CBV V# mode: table holds a 16-byte GFX10 raw buffer descriptor written by CreateConstantBufferView. const uint num_records = table.w[2]; diff --git a/tests/test_compute_heap_layout_census.py b/tests/test_compute_heap_layout_census.py new file mode 100644 index 0000000000..86507174ea --- /dev/null +++ b/tests/test_compute_heap_layout_census.py @@ -0,0 +1,64 @@ +"""Compute heap layout census on synthetic shader containers, listings and dispatch logs.""" +from pathlib import Path +import struct +import sys +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from test_heap_index_census import Work, SFI0_RES, SFI0_SMP +from test_rootsig_census import container, rts0 +import compute_heap_layout_census as c + + +class ComputeHeapLayout(unittest.TestCase): + def test_compare_programs(self): + work = Work() + self.addCleanup(work.close) + root = Path(work.root) + both = c.RESOURCE | c.SAMPLER + + def program(name, res, smp, constants=3, flags=both, used=SFI0_RES | SFI0_SMP, embedded=True): + lines = [(f"s_mov_b32 s20, s{res}", 4), ("s_mov_b32 s21, 0", 4), + ("s_load_dwordx8 s[32:39], s[20:21], s4", 8), + (f"s_mov_b32 s20, s{smp}", 4), ("s_load_dwordx4 s[40:43], s[20:21], s4", 8), + ("image_sample v[0:3], v[4:5], s[32:39], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D", 8), + ("s_endpgm", 4)] + work.add(name, "cs", used, lines, rsrc2=12 << 1) + if embedded: + payload = rts0(params=[("constants", 0, constants)], flags=flags) + (root / (name + ".dxbc")).write_bytes(container([(b"SFI0", struct.pack("/disasm + [--dispatch-log LOG ... --group GROUP] [--per-program] + +Read the carve index, each compute container's SFI0 and embedded RTS0, and the listing and +launch metadata for comparable programs. An optional integration dispatch log pairs compute-layout +parameter records with compute-input program names by PSO within that log. Use one carve group +per invocation. Entries in different carves need not be unique programs. +""" +import argparse +from collections import Counter, defaultdict +import json +import re +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import heap_index_census as heap +import shader_meta +import rootsig_census as roots + +RESOURCE, SAMPLER = 0x400, 0x800 # D3D12 root-signature flags +PARAM = re.compile(r" \(s(\d+) type=(\d+) const=(\d+) slots=\d+\)") + + +def captured_layouts(logs, group): + by_name = defaultdict(set) + for path in logs: + # Never join handles across processes, or a reused handle with ambiguous ownership. + names, layouts = defaultdict(set), defaultdict(set) + with path.open(encoding="utf-8", errors="replace") as stream: + for line in stream: + if "[rt] compute-layout:" in line: + match = re.search(r"compute-layout: pso=(\w+) flags=([\da-fA-F]+) .*?shader-heap=\S+(.*)$", line) + if not match: + continue + handle, flags, tail = match.groups() + end, tables = 4, [] + valid = not PARAM.sub("", tail).strip() + for slot, kind, count in PARAM.findall(tail): + width = {"0": int(count), "1": 2, "2": 1}.get(kind, 0) + valid &= int(slot) == end and width > 0 + if kind == "2": + tables.append(end) + end += width + layouts[handle].add((int(flags, 16), end, tuple(tables)) if valid else None) + elif "compute-input: execute=" in line and " pso=" in line: + m = re.search(r" name=(\S+) pso=(\w+)", line) + if m: + names[m[2]].add(m[1]) + for handle, programs in names.items(): + for program in programs: + prefix, _, name = program.rpartition("/") + if prefix == group: + by_name[name].update(layouts[handle] if len(programs) == 1 else {None}) + return by_name + + +def embedded_layout(payload): + sig, error = roots.parse_rts0(payload) + if error: + return None + end, tables = 4, [] + for p in sig["params"]: + if p["type"] == "table": + tables.append(end) + end += 1 + else: + end += p["count"] if p["type"] == "constants" else 2 + return sig["flags"], end, tuple(tables) + + +def compare(kind, layout, loads): + flags, end, tables = layout + if not flags & kind: + return "incompatible flags" + expected = end + (kind == SAMPLER and bool(flags & RESOURCE)) + if expected >= 32: + return "no room" + roles = {"V#", "T#"} if kind == RESOURCE else {"S#"} + # Declared tables can use dynamic offsets too. Never use the predicted heap slot + # to choose among multiple remaining candidates. + candidates = set() + for load in loads: + if not roles.intersection(load["roles"]) or load["offset"][0] != "dynamic": + continue + base = re.fullmatch(r"user s(\d+)", load["base"]) + if not base or load["ptr"] != "ptr32": + return "inconclusive" + reg = int(base[1]) + if reg not in tables: + candidates.add(reg) + if len(candidates) != 1: + return "inconclusive" + return "match" if expected in candidates else "mismatch" + + +def program_loads(disasm, name): + user = heap.cs_user_count(disasm, name) + launch = disasm.parent / "fspx" / (name + ".json") + if user is None and launch.exists(): + user = json.loads(launch.read_bytes()).get("user_sgprs") + listing = disasm / (name + ".s") + if user is not None and listing.is_file(): + ir = heap.shader_ir.parse_file(str(listing)) + if ir["insns"] and not ir["invalid"]: + try: + return heap.analyse(ir["insns"], "cs", user) + except heap.Skip: + pass + return [] + + +def census(disasm, captured, per_program=False): + result = Counter() + for name, stage in heap.stage_index(disasm).items(): + if stage != "cs": + continue + result["compute"] += 1 + chunks = roots.parts((disasm.parent / (name + ".dxbc")).read_bytes()) + sfi = chunks.get(b"SFI0", b"") + if len(sfi) < 8: + result["missing SFI0"] += 1 + continue + bits = struct.unpack_from("