From f3c53d2e5a1bd0d8494ed0e9fe54612f7b6531eb Mon Sep 17 00:00:00 2001 From: c1 Date: Thu, 26 Nov 2026 20:25:10 +0100 Subject: [PATCH 1/6] test: a native DXIL module reads a GPU-selected descriptor heap slot (ResourceDescriptorHeap probe) Adds DxilModule::heap_handle (dx.op.createHandleFromHeap, opcode 218, annotated with the view class) and a probe that compiles the same selection shader as DXC HLSL and as the native module, creates the pipeline with the heap-indexed root flag, and dispatches it twice with different selector words: each readback must be the data of the selected slot and the UAV guard word must stay intact. The adapter needs shader model 6.6 and resource binding tier 3, else the test skips. --- CMakeLists.txt | 12 + src/dxil_module.h | 19 ++ tests/native_heap_handle_probe.cpp | 278 ++++++++++++++++++++++++ tests/native_heap_handle_probe_check.py | 46 ++++ 4 files changed, 355 insertions(+) create mode 100644 tests/native_heap_handle_probe.cpp create mode 100644 tests/native_heap_handle_probe_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index de8c359067..15de552013 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1930,6 +1930,18 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ "${CMAKE_SOURCE_DIR}/tests/native_direct_container_check.py" --graphics-sampler-pso "${DXC_BIN_DIR}" "$") set_tests_properties(native_graphics_comparison_pso_warp PROPERTIES SKIP_RETURN_CODE 77) + # Cycle 1 of the global SRV work: ResourceDescriptorHeap[index] from a native DXIL module against a DXC reference. + add_executable(native_heap_handle_probe tests/native_heap_handle_probe.cpp) + target_include_directories(native_heap_handle_probe PRIVATE src) + target_compile_features(native_heap_handle_probe PRIVATE cxx_std_17) + target_link_libraries(native_heap_handle_probe PRIVATE x2w_shader_compiler dxgi d3d12) + set_property(TARGET native_heap_handle_probe PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_heap_handle_probe_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_heap_handle_probe_check.py" "$" + "${DXC_BIN_DIR}" ${adapter}) + set_tests_properties(native_heap_handle_probe_${adapter} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + endforeach() add_test(NAME native_recording_pages_warp COMMAND native_recording_check) add_test(NAME native_dispatch_states_warp COMMAND native_recording_check --subresources) set_tests_properties(native_dispatch_states_warp PROPERTIES SKIP_RETURN_CODE 77) diff --git a/src/dxil_module.h b/src/dxil_module.h index 34361d7247..605641f9c2 100644 --- a/src/dxil_module.h +++ b/src/dxil_module.h @@ -24,6 +24,7 @@ class DxilModule { }; std::ostringstream body, setup, globals; bool uses_wave = false; + bool heap_used = false; unsigned features = 0; struct Signature { Text name; @@ -141,6 +142,18 @@ class DxilModule { << " })\n"; return h; } + // A handle taken from the descriptor heap at a run-time index (SM 6.6 ResourceDescriptorHeap[index]), annotated with + // the view class the shader reads: `kind` is the DXIL resource kind (11 raw buffer, 2 Texture2D) and `props` the + // second ResourceProperties word. No resource record is declared: the binding is the whole heap. + Text heap_handle(const Text &index, unsigned kind, unsigned props, bool uav = false) { + heap_used = true; + const Text h = "%heap" + std::to_string(sequence++); + body << " " << h << "b = call %dx.types.Handle @dx.op.createHandleFromHeap(i32 218, i32 " << index + << ", i1 false, i1 true)\n" + << " " << h << " = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle " << h + << "b, %dx.types.ResourceProperties { i32 " << (kind + (uav ? 4096 : 0)) << ", i32 " << props << " })\n"; + return h; + } Text finish_compute(unsigned x, unsigned y, unsigned z, const Text &stage = "cs") { std::ostringstream out; out << "target datalayout = " @@ -256,6 +269,12 @@ class DxilModule { out << globals.str() << "define void @main() {\nentry:\n" << setup.str() << body.str() << "}\n"; for (auto &[name, decl] : declarations) out << decl << "\n"; + if (heap_used) { + out << "declare %dx.types.Handle @dx.op.createHandleFromHeap(i32,i32,i1,i1) nounwind readnone\n"; + if (resources.empty()) + out << "declare %dx.types.Handle " + "@dx.op.annotateHandle(i32,%dx.types.Handle,%dx.types.ResourceProperties) nounwind readnone\n"; + } if (!resources.empty()) out << "declare %dx.types.Handle @dx.op.createHandleFromBinding(i32,%dx.types.ResBind,i32,i1) nounwind " "readnone\n" diff --git a/tests/native_heap_handle_probe.cpp b/tests/native_heap_handle_probe.cpp new file mode 100644 index 0000000000..2d77e55ed5 --- /dev/null +++ b/tests/native_heap_handle_probe.cpp @@ -0,0 +1,278 @@ +// Cycle 1 of the global SRV work: can a native compute module read through ResourceDescriptorHeap[index]? +// +// Two shaders select a heap slot from a GPU word and copy that slot's raw buffer to a UAV: one is HLSL compiled by DXC +// (the reference), the other is the textual DXIL module the native compiler builds (dx.op.createHandleFromHeap, opcode +// 218). Both run on the same pipeline shape (root flag CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) with two different selector +// words: the readbacks must be the distinct data of slot A and slot B, and a UAV guard word past the copied range must +// stay intact. Usage: native_heap_handle_probe ADAPTER SDK_DIRECTORY WORK_DIRECTORY SHADER_FLAGS +// ADAPTER is warp or hardware. Exit 77 when the adapter lacks shader model 6.6 or resource binding tier 3. +#include "dxil_module.h" +#include "shader_dxil_compiler.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +namespace { +constexpr UINT words = 64; +constexpr UINT guard_word = 0xC0FFEE11u; +constexpr UINT sentinel = 0xCAFEF00Du; + +UINT slot_word(UINT slot, UINT i) { return (slot == 0 ? 0x1000u : 0x9000u) + i * (slot == 0 ? 7u : 13u); } + +ComPtr make_buffer(ID3D12Device *device, UINT64 bytes, D3D12_HEAP_TYPE type, D3D12_RESOURCE_STATES state, + D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + D3D12_HEAP_PROPERTIES heap{type}; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = flags; + ComPtr resource; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(&resource)))) + return {}; + return resource; +} + +struct Gpu { + ComPtr device; + ComPtr queue; + ComPtr allocator; + ComPtr list; + ComPtr fence; + UINT64 value = 0; + bool open(ID3D12Device *d) { + device = d; + D3D12_COMMAND_QUEUE_DESC q{D3D12_COMMAND_LIST_TYPE_DIRECT}; + return SUCCEEDED(d->CreateCommandQueue(&q, IID_PPV_ARGS(&queue))) && + SUCCEEDED(d->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) && + SUCCEEDED(d->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(&list))) && + SUCCEEDED(list->Close()) && SUCCEEDED(d->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))); + } + template bool run(Record &&record) { + if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.Get(), nullptr))) return false; + record(list.Get()); + if (FAILED(list->Close())) return false; + ID3D12CommandList *lists[]{list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.Get(), ++value))) return false; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + fence->SetEventOnCompletion(value, event); + WaitForSingleObject(event, 30000); + CloseHandle(event); + return fence->GetCompletedValue() >= value; + } +}; + +void transition(ID3D12GraphicsCommandList *list, ID3D12Resource *r, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) { + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {r, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, from, to}; + list->ResourceBarrier(1, &b); +} + +// The dxil module of the native compiler: output[tid] = ResourceDescriptorHeap[selection[0]][tid]. +std::string native_module(unsigned shader_flags) { + x2w::DxilModule m; + m.features = shader_flags | 16; + const auto selection = m.handle({0, 0, 11, 0, 0, 0}); + const auto output = m.handle({1, 0, 11, 0, 0, 0}); + const auto thread = m.invoke("i32", "threadId.i32", 93, {{"i32", "0"}}, "nounwind readnone"); + const auto address = m.binary("shl", thread, "2"); + const auto word = m.invoke("%dx.types.ResRet.i32", "rawBufferLoad.i32", 139, + {{"%dx.types.Handle", selection}, {"i32", "0"}, {"i32", "undef"}, {"i8", "1"}, {"i32", "4"}}, + "nounwind readonly"); + const auto slot = m.value("extractvalue %dx.types.ResRet.i32 " + word + ", 0"); + const auto data = m.heap_handle(slot, 11, 0); + const auto loaded = m.invoke("%dx.types.ResRet.i32", "rawBufferLoad.i32", 139, + {{"%dx.types.Handle", data}, {"i32", address}, {"i32", "undef"}, {"i8", "1"}, {"i32", "4"}}, + "nounwind readonly"); + const auto value = m.value("extractvalue %dx.types.ResRet.i32 " + loaded + ", 0"); + m.invoke("void", "rawBufferStore.i32", 140, + {{"%dx.types.Handle", output}, {"i32", address}, {"i32", "undef"}, {"i32", value}, {"i32", "undef"}, + {"i32", "undef"}, {"i32", "undef"}, {"i8", "1"}, {"i32", "4"}}, + "nounwind"); + return m.finish_compute(words, 1, 1); +} + +const char *reference_hlsl = + "ByteAddressBuffer selection : register(t0);\n" + "RWByteAddressBuffer output : register(u0);\n" + "[numthreads(64, 1, 1)] void main(uint3 id : SV_DispatchThreadID) {\n" + " ByteAddressBuffer data = ResourceDescriptorHeap[selection.Load(0)];\n" + " output.Store(id.x * 4, data.Load(id.x * 4));\n" + "}\n"; +} // namespace + +int wmain(int argc, wchar_t **argv) { + if (argc != 5) { + std::fputs("usage: native_heap_handle_probe ADAPTER SDK WORK SHADER_FLAGS\n", stderr); + return 2; + } + const std::wstring adapter = argv[1]; + const unsigned shader_flags = static_cast(std::stoull(argv[4])); + const std::filesystem::path work = argv[3]; + std::filesystem::create_directories(work); + + ComPtr factory; + ComPtr chosen; + ComPtr device; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 77; + if (adapter == L"warp") { + if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&chosen)))) return 77; + } else { + for (UINT i = 0; i < 8; ++i) { + ComPtr candidate; + if (factory->EnumAdapters1(i, &candidate) == DXGI_ERROR_NOT_FOUND) break; + DXGI_ADAPTER_DESC1 desc{}; + candidate->GetDesc1(&desc); + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) { chosen = candidate; break; } + } + if (!chosen) { std::puts("no hardware adapter"); return 77; } + } + if (FAILED(D3D12CreateDevice(chosen.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) { std::puts("no device"); return 77; } + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_6}; + D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; + if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &model, sizeof model)) || + model.HighestShaderModel < D3D_SHADER_MODEL_6_6 || + FAILED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof options)) || + options.ResourceBindingTier < D3D12_RESOURCE_BINDING_TIER_3) { + std::printf("adapter lacks shader model 6.6 or resource binding tier 3 (tier %d)\n", int(options.ResourceBindingTier)); + return 77; + } + try { + x2w::ShaderDxilCompiler compiler(argv[2]); + const auto module = native_module(shader_flags); + std::ofstream(work / "native_module.ll") << module; + x2w::CompiledShader reference, native; + reference = compiler.compile(reference_hlsl, L"cs_6_6", work); + try { + native = compiler.compile(module, L"cs_6_6", work, x2w::ShaderSourceFormat::dxil_ir); + } catch (const std::exception &error) { + std::printf("FAIL: the native module was refused by the compiler or validator: %s\n", error.what()); + return 3; + } + + // Root signature: root SRV t0 (selector), root UAV u0 (output), and the heap indexed directly. + D3D12_ROOT_PARAMETER1 parameters[2]{}; + parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC versioned{}; + versioned.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + versioned.Desc_1_1.NumParameters = 2; + versioned.Desc_1_1.pParameters = parameters; + versioned.Desc_1_1.Flags = static_cast(0x400); // CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED + ComPtr blob, error; + ComPtr root; + if (FAILED(D3D12SerializeVersionedRootSignature(&versioned, &blob, &error)) || + FAILED(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root)))) { + std::puts("FAIL: root signature with the heap-indexed flag"); + return 4; + } + ComPtr states[2]; + const x2w::CompiledShader *shaders[2]{&reference, &native}; + for (int k = 0; k < 2; ++k) { + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = root.Get(); + pso.CS = {shaders[k]->dxil.data(), shaders[k]->dxil.size()}; + if (FAILED(device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&states[k])))) { + std::printf("FAIL: pipeline state of the %s shader\n", k ? "native" : "reference"); + return 5; + } + } + + // Heap slots 0 and 1: two raw buffers with different data. Slot 2: a buffer of another size, never selected. + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 3, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr heap; + if (FAILED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)))) return 6; + const UINT step = device->GetDescriptorHandleIncrementSize(heap_desc.Type); + ComPtr data[2], decoy; + void *mapped = nullptr; + for (UINT s = 0; s < 2; ++s) { + data[s] = make_buffer(device.Get(), words * 4, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + if (!data[s] || FAILED(data[s]->Map(0, nullptr, &mapped))) return 6; + for (UINT i = 0; i < words; ++i) static_cast(mapped)[i] = slot_word(s, i); + data[s]->Unmap(0, nullptr); + } + decoy = make_buffer(device.Get(), words * 4, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Buffer.NumElements = words; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + auto cpu = heap->GetCPUDescriptorHandleForHeapStart(); + for (ID3D12Resource *r : {data[0].Get(), data[1].Get(), decoy.Get()}) { + device->CreateShaderResourceView(r, &srv, cpu); + cpu.ptr += step; + } + + auto selection = make_buffer(device.Get(), 256, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + auto output = make_buffer(device.Get(), (words + 1) * 4, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + auto seed = make_buffer(device.Get(), (words + 1) * 4, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + auto readback = make_buffer(device.Get(), (words + 1) * 4, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + if (!selection || !output || !seed || !readback) return 6; + Gpu gpu; + if (!gpu.open(device.Get())) return 6; + int failures = 0; + for (int k = 0; k < 2; ++k) { + const char *name = k ? "native" : "reference"; + std::vector seen[2]; + for (UINT selected = 0; selected < 2; ++selected) { + seed->Map(0, nullptr, &mapped); + for (UINT i = 0; i < words; ++i) static_cast(mapped)[i] = sentinel; + static_cast(mapped)[words] = guard_word; + seed->Unmap(0, nullptr); + selection->Map(0, nullptr, &mapped); + static_cast(mapped)[0] = selected; + selection->Unmap(0, nullptr); + const bool ok = gpu.run([&](ID3D12GraphicsCommandList *list) { + transition(list, output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyResource(output.Get(), seed.Get()); + transition(list, output.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + ID3D12DescriptorHeap *heaps[]{heap.Get()}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootSignature(root.Get()); + list->SetPipelineState(states[k].Get()); + list->SetComputeRootShaderResourceView(0, selection->GetGPUVirtualAddress()); + list->SetComputeRootUnorderedAccessView(1, output->GetGPUVirtualAddress()); + list->Dispatch(1, 1, 1); + transition(list, output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyResource(readback.Get(), output.Get()); + transition(list, output.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + }); + if (!ok || FAILED(device->GetDeviceRemovedReason())) { + std::printf("FAIL: %s dispatch selecting slot %u did not complete\n", name, selected); + return 7; + } + readback->Map(0, nullptr, &mapped); + seen[selected].assign(static_cast(mapped), static_cast(mapped) + words + 1); + readback->Unmap(0, nullptr); + bool match = true; + for (UINT i = 0; i < words; ++i) match &= seen[selected][i] == slot_word(selected, i); + const bool guard = seen[selected][words] == guard_word; + std::printf("%s selector %u: data %s, guard %s\n", name, selected, match ? "matches the CPU reference" : "DIFFERS", + guard ? "intact" : "OVERWRITTEN"); + failures += !match || !guard; + } + if (seen[0] == seen[1]) { + std::printf("FAIL: %s read the same data for both selectors\n", name); + ++failures; + } + } + std::puts(failures ? "native_heap_handle_probe: FAIL" : "native_heap_handle_probe: PASS"); + return failures ? 1 : 0; + } catch (const std::exception &error) { + std::printf("FAIL: %s\n", error.what()); + return 8; + } +} diff --git a/tests/native_heap_handle_probe_check.py b/tests/native_heap_handle_probe_check.py new file mode 100644 index 0000000000..323bdfa3a4 --- /dev/null +++ b/tests/native_heap_handle_probe_check.py @@ -0,0 +1,46 @@ +"""Cycle 1 of the global SRV work: compile a reference ResourceDescriptorHeap shader with DXC, show how DXC spells the heap handle and +its shader flags, then run the native heap-handle probe with those flags (exit 77 from the probe is a skip).""" +import re +import subprocess +import sys +import tempfile +from pathlib import Path + + +REFERENCE = """ByteAddressBuffer selection : register(t0); +RWByteAddressBuffer output : register(u0); +[numthreads(64, 1, 1)] void main(uint3 id : SV_DispatchThreadID) { + ByteAddressBuffer data = ResourceDescriptorHeap[selection.Load(0)]; + output.Store(id.x * 4, data.Load(id.x * 4)); +} +""" + + +def main(probe, sdk, adapter): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + source = work / "reference.hlsl" + source.write_text(REFERENCE) + listing = work / "reference.ll" + subprocess.run([str(Path(sdk) / "dxc.exe"), "-T", "cs_6_6", "-E", "main", "-Fc", str(listing), str(source)], check=True, + capture_output=True) + text = listing.read_text() + flags = re.search(r"!\{i32 0, i64 (\d+)", text) + if not flags: + raise AssertionError("the reference listing has no shader flags tag") + for line in text.splitlines(): + if "createHandleFromHeap" in line or "annotateHandle(i32 216" in line and "ResourceProperties { i32 11" in line: + print("reference:", line.strip()) + print("reference shader flags:", flags.group(1)) + result = subprocess.run([probe, adapter, sdk, str(work / "probe"), flags.group(1)], capture_output=True, text=True) + print(result.stdout, end="") + print(result.stderr, end="") + if result.returncode == 77: + return 77 + assert result.returncode == 0, f"probe exit {result.returncode}" + assert "native_heap_handle_probe: PASS" in result.stdout + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:4])) From ab365cc1c65ff8fe6661ab9ab3565f203483f06a Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:09:32 +0100 Subject: [PATCH 2/6] feat: the direct compute lowering reads a GPU-selected descriptor heap slot as a raw buffer SRV A buffer load through a descriptor loaded from the whole resource heap at a GPU-computed index used to be refused (whole-heap buffer access needs a matching descriptor at the GPU-selected index). The direct DXIL lowering now emits ResourceDescriptorHeap[slot] (createHandleFromHeap, annotated as a raw buffer) and records a heap_buffer_srv binding with no table register; the pipeline then creates its root signature with the heap-indexed flag and sets the heap on the list. Adds the view-type classification header (native_global_srv.h) that the dispatch guard will use; no guard yet. --- src/direct_compute_cache.cpp | 2 +- src/gfx1013_compute_native.h | 5 +- src/gfx1013_direct_compute.inl | 28 +++++ src/native_compute_pipeline.cpp | 10 +- src/native_compute_pipeline.h | 2 + src/startup_stubs/native_global_srv.h | 142 ++++++++++++++++++++++++++ 6 files changed, 185 insertions(+), 4 deletions(-) create mode 100644 src/startup_stubs/native_global_srv.h diff --git a/src/direct_compute_cache.cpp b/src/direct_compute_cache.cpp index c8aded0444..9141aa7f86 100644 --- a/src/direct_compute_cache.cpp +++ b/src/direct_compute_cache.cpp @@ -122,7 +122,7 @@ NativeComputeShader decode(std::string_view bytes) { unsigned n = in.count(1000000); shader.bindings.reserve(n); for (unsigned j = 0; j < n; ++j) { - auto kind = static_cast(in.count(static_cast(ComputeViewKind::byte_window_srv))); + auto kind = static_cast(in.count(static_cast(ComputeViewKind::heap_buffer_srv))); ComputeViewBinding b{kind, in.word(), in.word(), in.word(), in.word(), in.word(), in.word(), in.count(7)}; b.scalar_table = static_cast(in.count(unsigned(ComputeViewBinding::ScalarTable::srv))); if (!b.array_count || b.array_position >= b.array_count || diff --git a/src/gfx1013_compute_native.h b/src/gfx1013_compute_native.h index 2022bbf3ce..e9817c4a96 100644 --- a/src/gfx1013_compute_native.h +++ b/src/gfx1013_compute_native.h @@ -34,9 +34,12 @@ enum class ComputeViewKind { cube_comparison_srv, indexed_atomic_uav, d16_sample_srv, - byte_window_srv + byte_window_srv, + heap_buffer_srv // A raw buffer read through ResourceDescriptorHeap[slot]; the slot is a GPU value. }; inline constexpr unsigned compute_resource_heap = ~0u; +// A binding of the whole descriptor heap: it has no table register and no root parameter. +inline bool compute_heap_binding(ComputeViewKind kind) { return kind == ComputeViewKind::heap_buffer_srv; } inline bool compute_buffer_uav(ComputeViewKind kind) { return kind == ComputeViewKind::raw_buffer_uav || kind == ComputeViewKind::typed_buffer_uav || kind == ComputeViewKind::half_buffer_uav || kind == ComputeViewKind::indexed_atomic_uav; diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index fe027be66a..4cc0818c45 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -247,10 +247,38 @@ struct DirectCompute { } } } + // A raw buffer SRV chosen by a GPU value in the whole descriptor heap: ResourceDescriptorHeap[slot]. The view class the + // shader reads is the one this handle is annotated with (raw buffer); a slot holding another class is refused by the + // dispatch before the shader runs. The binding names the heap (no table register); the pipeline indexes it directly. + string heap_resource(const Inst &i, const State &s, unsigned base, ComputeViewKind kind, unsigned bytes) { + const auto &symbol = s.at(base); + if (kind != ComputeViewKind::raw_vector_srv && kind != ComputeViewKind::buffer_srv) + refuse(i.pc, "a GPU-selected heap slot is read as a raw buffer SRV only"); + if (symbol.offset % 32 || s[base].type != Symbol::Type::indexed_descriptor) + refuse(i.pc, "unaligned heap descriptor"); + for (unsigned j = 1; j < 4; ++j) { + Symbol expected = symbol; + expected.offset += 4 * j; + if (!(s.at(base + j) == expected)) + refuse(i.pc, "non-contiguous resource descriptor"); + } + auto &bindings = analysis.result.bindings; + auto it = std::find_if(bindings.begin(), bindings.end(), [](const auto &b) { + return b.kind == ComputeViewKind::heap_buffer_srv; + }); + if (it == bindings.end()) + bindings.push_back({ComputeViewKind::heap_buffer_srv, compute_resource_heap, 0, 0, bytes}); + else + it->required_bytes = (std::max)(it->required_bytes, bytes); + ir.features |= 16; + return ir.heap_handle(ir.binary("add", read(base), to_string(symbol.offset / 32)), 11, 0); + } string resource(const Inst &i, const State &s, unsigned base, ComputeViewKind kind, unsigned bytes, unsigned *bound_register = nullptr) { const auto &symbol = s.at(base); const bool indexed = symbol.type == Symbol::Type::indexed_descriptor; + if (indexed && symbol.value == compute_resource_heap) + return heap_resource(i, s, base, kind, bytes); const unsigned count = indexed ? 1 + symbol.index_mask / 32 : 1; analysis.binding(i, s, base, 4, kind, bytes); auto it = std::find_if(analysis.result.bindings.begin(), analysis.result.bindings.end(), [&](const auto &b) { diff --git a/src/native_compute_pipeline.cpp b/src/native_compute_pipeline.cpp index 5e50896fff..a7fa824eaf 100644 --- a/src/native_compute_pipeline.cpp +++ b/src/native_compute_pipeline.cpp @@ -32,6 +32,10 @@ NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, Shade UINT counts[2]{}; for (const auto &binding : pipeline.bindings) { + if (compute_heap_binding(binding.kind)) { + pipeline.heap_indexed = true; // ResourceDescriptorHeap reads: no table register + continue; + } auto &count = counts[is_uav(binding)]; if (binding.shader_register != count++) throw std::runtime_error("noncontiguous compute register range"); @@ -82,7 +86,9 @@ NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, Shade param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; param.Constants = {b.shader_register + 1, 0, 2}; } - D3D12_ROOT_SIGNATURE_DESC desc{param_count, params.data(), static_cast(samplers.size()), samplers.data()}; + D3D12_ROOT_SIGNATURE_DESC desc{param_count, params.data(), static_cast(samplers.size()), samplers.data(), + pipeline.heap_indexed ? static_cast(0x400) // CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED + : D3D12_ROOT_SIGNATURE_FLAG_NONE}; Microsoft::WRL::ComPtr blob; if (FAILED(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr)) || FAILED(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), @@ -104,7 +110,7 @@ void NativeComputePipeline::bind(ID3D12GraphicsCommandList *list, ID3D12Descript throw std::runtime_error("compute root constants missing"); if (atomic.size() != atomic_views) throw std::runtime_error("indexed atomic view metadata missing"); - if (srv_count || uav_count) + if (srv_count || uav_count || heap_indexed) list->SetDescriptorHeaps(1, &heap); list->SetComputeRootSignature(root.Get()); list->SetPipelineState(state.Get()); diff --git a/src/native_compute_pipeline.h b/src/native_compute_pipeline.h index f3ebfe86fc..2494665e27 100644 --- a/src/native_compute_pipeline.h +++ b/src/native_compute_pipeline.h @@ -18,6 +18,8 @@ struct NativeComputePipeline { unsigned constant_words = 0, atomic_views = 0; unsigned instructions = 0; bool cache_hit = false, frontend_cache_hit = false; + bool heap_indexed = false; // reads ResourceDescriptorHeap: the root signature indexes the heap directly, which must be set + // on the list (bind() does it) and holds the selectable slots from index 0 double frontend_ms = 0; double backend_ms = 0; double pipeline_ms = 0; diff --git a/src/startup_stubs/native_global_srv.h b/src/startup_stubs/native_global_srv.h new file mode 100644 index 0000000000..fa258a802b --- /dev/null +++ b/src/startup_stubs/native_global_srv.h @@ -0,0 +1,142 @@ +#pragma once + +#include "native_buffer_stride.h" +#include +#include +#include +#include +#include + +// The view type of a global (descriptor heap) SRV slot that a dispatch can select from GPU data. +// +// A shader that picks its slot at run time can only be recorded and replayed if the type of every slot it may pick is +// known: the capture keeps {slot, type, stride} for each slot of the heap, and the dispatch is refused, before any +// shader runs, when the selected slot holds another type than the one the shader reads. No heap-indexed data read is +// translated here; this header only classifies, serializes and checks. +namespace x2w_startup { +enum class GlobalSrvType : unsigned { none, raw_buffer, structured_buffer, typed_buffer, texture }; + +inline const char *global_srv_type_name(GlobalSrvType type) { + switch (type) { + case GlobalSrvType::raw_buffer: return "raw_buffer"; + case GlobalSrvType::structured_buffer: return "structured_buffer"; + case GlobalSrvType::typed_buffer: return "typed_buffer"; + case GlobalSrvType::texture: return "texture"; + default: return "none"; + } +} + +inline GlobalSrvType global_srv_type_from_name(const std::string &name) { + for (auto type : {GlobalSrvType::raw_buffer, GlobalSrvType::structured_buffer, GlobalSrvType::typed_buffer, + GlobalSrvType::texture}) + if (name == global_srv_type_name(type)) return type; + return GlobalSrvType::none; +} + +struct GlobalSrvView { + unsigned slot = 0; + GlobalSrvType type = GlobalSrvType::none; + unsigned stride = 0; // Bytes per element for a buffer view (the value native_view_stride gives), 0 for a texture. +}; + +// Classifies the description a title passed for an SRV (slot 18 of the device interface). False: not a view this +// path can name (an unknown dimension, or a buffer view without a usable stride). +inline bool classify_global_srv_view(unsigned heap_slot, const void *bytes, std::size_t size, GlobalSrvView &view) { + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + if (!bytes || size < sizeof(desc)) return false; + std::memcpy(&desc, bytes, sizeof(desc)); + view = {}; + view.slot = heap_slot; + if (desc.ViewDimension == D3D12_SRV_DIMENSION_UNKNOWN) return false; + if (desc.ViewDimension != D3D12_SRV_DIMENSION_BUFFER) { + view.type = GlobalSrvType::texture; + return true; + } + if (!native_view_stride(18, bytes, size, view.stride)) return false; + view.type = desc.Buffer.StructureByteStride ? GlobalSrvType::structured_buffer + : (desc.Buffer.Flags & D3D12_BUFFER_SRV_FLAG_RAW) ? GlobalSrvType::raw_buffer + : GlobalSrvType::typed_buffer; + return true; +} + +// One request's view metadata, the text that travels with a captured request (req_.views). +struct GlobalSrvRequest { + unsigned selected = 0; + GlobalSrvType needed = GlobalSrvType::none; + std::vector views; + bool has_selected = false; +}; + +inline std::string encode_global_srv_request(const GlobalSrvRequest &request) { + std::ostringstream out; + out << "x2w-global-srv-views 1\nselect " << request.selected << "\nneed " << global_srv_type_name(request.needed) << '\n'; + for (const auto &view : request.views) + out << "slot " << view.slot << ' ' << global_srv_type_name(view.type) << ' ' << view.stride << '\n'; + return out.str(); +} + +// False with a diagnostic in `error` for a text that cannot reconstruct the binding. +inline bool decode_global_srv_request(const std::string &text, GlobalSrvRequest &request, std::string &error) { + request = {}; + std::istringstream in(text); + std::string line; + if (!std::getline(in, line) || line != "x2w-global-srv-views 1") { + error = "global SRV view metadata has no 'x2w-global-srv-views 1' header"; + return false; + } + bool has_need = false; + while (std::getline(in, line)) { + std::istringstream fields(line); + std::string key; + fields >> key; + if (key.empty()) continue; + if (key == "select") { + if (!(fields >> request.selected)) { error = "global SRV view metadata: unreadable select line"; return false; } + request.has_selected = true; + } else if (key == "need") { + std::string name; + fields >> name; + request.needed = global_srv_type_from_name(name); + if (request.needed == GlobalSrvType::none) { + error = "global SRV view metadata: unknown needed view type '" + name + "'"; + return false; + } + has_need = true; + } else if (key == "slot") { + GlobalSrvView view; + std::string name; + if (!(fields >> view.slot >> name >> view.stride)) { + error = "global SRV view metadata: unreadable slot line"; + return false; + } + view.type = global_srv_type_from_name(name); + if (view.type == GlobalSrvType::none) { + error = "global SRV slot " + std::to_string(view.slot) + " has unknown view type '" + name + "'"; + return false; + } + request.views.push_back(view); + } else { + error = "global SRV view metadata: unknown line '" + key + "'"; + return false; + } + } + if (!request.has_selected || !has_need) { + error = std::string("global SRV view metadata lacks the ") + (request.has_selected ? "needed view type" : "selected slot"); + return false; + } + return true; +} + +// Empty when the selected slot holds the type the shader reads. Otherwise the refusal text: it names the slot and the +// view types, and is produced before the shader runs. Used by the native recording and by the replay alike. +inline std::string refuse_global_srv_selection(const std::vector &views, unsigned selected, + GlobalSrvType needed) { + for (const auto &view : views) { + if (view.slot != selected) continue; + if (view.type == needed) return {}; + return "global SRV slot " + std::to_string(selected) + " has view type " + global_srv_type_name(view.type) + + ", the shader needs " + global_srv_type_name(needed); + } + return "global SRV slot " + std::to_string(selected) + " has no captured view type"; +} +} // namespace x2w_startup From 7e49e638fdbd1c1a7c59a58b8d95d0db5f1afb03 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:18:23 +0100 Subject: [PATCH 3/6] fix: the probe module ends with ret void --- tests/native_heap_handle_probe.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/native_heap_handle_probe.cpp b/tests/native_heap_handle_probe.cpp index 2d77e55ed5..faa4b2d291 100644 --- a/tests/native_heap_handle_probe.cpp +++ b/tests/native_heap_handle_probe.cpp @@ -100,6 +100,7 @@ std::string native_module(unsigned shader_flags) { {{"%dx.types.Handle", output}, {"i32", address}, {"i32", "undef"}, {"i32", value}, {"i32", "undef"}, {"i32", "undef"}, {"i32", "undef"}, {"i8", "1"}, {"i32", "4"}}, "nounwind"); + m.body << " ret void\n"; return m.finish_compute(words, 1, 1); } From 432db950e4782119b144a4f3f743a99c5563e1a2 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:30:12 +0100 Subject: [PATCH 4/6] test: the probe writes both shader containers and the check prints how they differ --- tests/native_heap_handle_probe.cpp | 6 ++++++ tests/native_heap_handle_probe_check.py | 12 ++++++++++++ 2 files changed, 18 insertions(+) diff --git a/tests/native_heap_handle_probe.cpp b/tests/native_heap_handle_probe.cpp index faa4b2d291..3f358505a0 100644 --- a/tests/native_heap_handle_probe.cpp +++ b/tests/native_heap_handle_probe.cpp @@ -162,6 +162,12 @@ int wmain(int argc, wchar_t **argv) { return 3; } + // Both containers go to the work directory so the check script can print how they differ. + for (const auto &[name, shader] : {std::pair{"reference.dxil", &reference}, + std::pair{"native.dxil", &native}}) + std::ofstream(work / name, std::ios::binary) + .write(reinterpret_cast(shader->dxil.data()), static_cast(shader->dxil.size())); + // Root signature: root SRV t0 (selector), root UAV u0 (output), and the heap indexed directly. D3D12_ROOT_PARAMETER1 parameters[2]{}; parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; diff --git a/tests/native_heap_handle_probe_check.py b/tests/native_heap_handle_probe_check.py index 323bdfa3a4..eb9fa22c1a 100644 --- a/tests/native_heap_handle_probe_check.py +++ b/tests/native_heap_handle_probe_check.py @@ -35,6 +35,18 @@ def main(probe, sdk, adapter): result = subprocess.run([probe, adapter, sdk, str(work / "probe"), flags.group(1)], capture_output=True, text=True) print(result.stdout, end="") print(result.stderr, end="") + if result.returncode not in (0, 77): + # Show how the two containers differ (module, shader flags, pipeline state validation data). + import difflib + listings = {} + for name in ("reference", "native"): + container = work / "probe" / f"{name}.dxil" + if container.exists(): + listings[name] = subprocess.run([str(Path(sdk) / "dxc.exe"), "-dumpbin", str(container)], + capture_output=True, text=True).stdout.splitlines() + if len(listings) == 2: + diff = list(difflib.unified_diff(listings["reference"], listings["native"], "reference", "native", lineterm="", n=1)) + print("\n".join(diff[:160])) if result.returncode == 77: return 77 assert result.returncode == 0, f"probe exit {result.returncode}" From 85bb79e6a7c914c81b154bdd3aadfcd4c1b01c24 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Thu, 26 Nov 2026 22:39:09 +0100 Subject: [PATCH 5/6] test: skip the heap-handle probe on adapters without 32-lane waves The native module declares WaveSize=32 (the guest wave). WARP offers only 4-lane waves, so CreateComputePipelineState refuses the native shader and native_heap_handle_probe_warp failed with "pipeline state of the native shader". Return 77 when the adapter cannot run 32-lane waves, as native_store_replay and native_recording_check already do. AI-assisted. Co-Authored-By: Claude Opus 5.5 --- tests/native_heap_handle_probe.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/native_heap_handle_probe.cpp b/tests/native_heap_handle_probe.cpp index 3f358505a0..6fb745d5db 100644 --- a/tests/native_heap_handle_probe.cpp +++ b/tests/native_heap_handle_probe.cpp @@ -149,6 +149,13 @@ int wmain(int argc, wchar_t **argv) { std::printf("adapter lacks shader model 6.6 or resource binding tier 3 (tier %d)\n", int(options.ResourceBindingTier)); return 77; } + // The native module declares WaveSize=32 (the guest wave), so an adapter without 32-lane waves cannot create it. + D3D12_FEATURE_DATA_D3D12_OPTIONS1 waves{}; + if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, &waves, sizeof waves)) || !waves.WaveOps || + waves.WaveLaneCountMin > 32 || waves.WaveLaneCountMax < 32) { + std::printf("adapter has no 32-lane waves (%u..%u)\n", waves.WaveLaneCountMin, waves.WaveLaneCountMax); + return 77; + } try { x2w::ShaderDxilCompiler compiler(argv[2]); const auto module = native_module(shader_flags); From faa7ccf4cc1c595c324fdca155c088bc520ed45a Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Fri, 27 Nov 2026 01:46:16 +0100 Subject: [PATCH 6/6] native: capture and replay view types for GPU-selected global SRV slots The direct compute translation takes a view contract for a GPU-selected descriptor heap slot (HeapViewContract none / raw_buffer / other). A heap descriptor load is translated only with raw_buffer; without a contract the existing refusal stays. Constant heap indices, immediate offsets, scalar buffer loads from the heap base and stride reads of a selected slot are refused. Heap-reading modules set shader flag 0x40000000, which the validator requires. compile_dxil gfx1013-container-cs reads an optional req_.views (native_global_srv.h, format version 2 with buffer sizes), refuses a selection whose slot holds another view type before publishing a .cso, and reports the captured selection. native_global_srv_heap_replay records a dispatch that selects its slot from GPU data (selector read back before recording, guard before Dispatch, NativeRecording + NativeDispatchStates) and replays the compile_dxil output on a heap rebuilt from the captured view types, with negative controls on both paths. Fixes #2908. AI-assisted. Co-Authored-By: Claude Opus 5.5 --- .../native-global-srv-heap-replay.md | 100 ++++ src/direct_compute_cache.cpp | 9 +- src/direct_compute_cache.h | 3 +- src/gfx1013_compute_native.cpp | 10 +- src/gfx1013_compute_native.h | 7 +- src/gfx1013_direct_compute.inl | 50 +- src/native_compute_pipeline.cpp | 7 +- src/native_compute_pipeline.h | 3 +- src/startup_stubs/native_global_srv.h | 16 +- .../cmake/native_global_srv_heap_replay.cmake | 15 + tests/native_global_srv_heap_replay.cpp | 451 ++++++++++++++++++ tests/native_global_srv_heap_replay_check.py | 259 ++++++++++ tools/startup/compile_dxil.cpp | 47 +- 13 files changed, 940 insertions(+), 37 deletions(-) create mode 100644 docs/experiments/native-global-srv-heap-replay.md create mode 100644 tests/cmake/native_global_srv_heap_replay.cmake create mode 100644 tests/native_global_srv_heap_replay.cpp create mode 100644 tests/native_global_srv_heap_replay_check.py diff --git a/docs/experiments/native-global-srv-heap-replay.md b/docs/experiments/native-global-srv-heap-replay.md new file mode 100644 index 0000000000..04e7a3baca --- /dev/null +++ b/docs/experiments/native-global-srv-heap-replay.md @@ -0,0 +1,100 @@ +# GPU-selected global SRV heap slots: capture and replay of view types + +Issue #2908, branch `cpp-migration`. Builds on the heap read in the direct C++ DXIL path from #2912 +(`ResourceDescriptorHeap[slot]` for a raw buffer read, `src/gfx1013_direct_compute.inl` `heap_resource`). + +## What changed + +- The direct compute translation takes a view contract for a GPU-selected heap slot (`x2w::HeapViewContract`: + `none`, `raw_buffer`, `other`). An SMEM descriptor load from the resource heap is refused unless the contract is + `raw_buffer`; without a contract the existing text stays: "direct resource-heap load requires the selected GPU slot and + its view type". A scalar buffer load from the heap base, a heap descriptor load with an immediate offset or a constant + index (both could address another slot than the captured selection), and a stride read of a GPU-selected slot in the + direct path are refused with their own texts. The contract is part of the frontend cache key when it is not `none`. +- Modules that read `ResourceDescriptorHeap` now also set shader flag `0x40000000`, as DXC does for the HLSL reference. + Without it the validator refuses the module ("Flags must match usage. Validation failed."), measured by removing the + flag and running the hardware test. +- `src/startup_stubs/native_global_srv.h` writes and reads version 2 of the view metadata, which adds the buffer size: + + ``` + x2w-global-srv-views 2 + select + need + slot + ``` + +- `compile_dxil ... gfx1013-container-cs` reads an optional `req_.views` next to the `.cdx` (single file and + `--requests`). It decodes the file, refuses a selection whose slot holds another view type than `need`, refuses a `need` + other than `raw_buffer`, translates with the `raw_buffer` contract and prints `global_srv select= need=`. Every + refusal happens before the `.cso` is published. Without the file a heap-reading shader is refused as before. The + `.views` file is not part of the `.cdx`/`.root` content key: it describes one captured dispatch. + +## Meaning of "native recording" and "runtime path" here + +The issue's reproduction names `native_recording_check` and `native_dispatch_states_warp`, which test +`x2w_startup::NativeRecording` (descriptor-table pages) and `x2w_startup::NativeDispatchStates` (dispatch barriers). On +`cpp-migration` only tests use these classes; the D3D12 stand-in does not call the native compiler. The fixture's `record` +mode records the dispatch with both classes and applies the view guard before `Dispatch`; that is the native recording +path checked here, and its unchanged UAV sentinels are the "runtime path" sentinels of the issue. The startup runtime +itself is not covered. + +The slot is selected by GPU data. The `record` mode reads the selector back from its GPU buffer before recording the +dispatch (one copy to a readback buffer and one fence per recorded dispatch) and uses that value as the captured +selection, so the guard checks the slot the GPU input actually selects, before the shader runs. + +## Fixture + +`tests/native_global_srv_heap_replay.cpp` with `tests/native_global_srv_heap_replay_check.py`. A source-built compute +container (two root inputs: a descriptor table in s[0:1], the descriptor heap in s[2:3]; instruction words assembled with +LLVM 15 `clang -cc1as -triple amdgcn-amd-amdhsa -target-cpu gfx1013 -show-encoding`) loads the selector from t0, loads +the descriptor of `ResourceDescriptorHeap[selector]`, reads 64 words through it and stores them to u0. Heap slots: 0 and +1 raw buffers with different data, 2 a Texture2D, 3 a typed buffer. u0 holds 72 words; the last 8 and, on a refused +selection, all 72 must keep the sentinel `0x69696969`. + +The check runs, in order: + +1. `compile_dxil --requests` on the request without `.views`: refused with the heap text, no `.cso`. +2. `record` for selections 0 and 1: fenced output equals the selected slot's data, sentinels intact, `.views` captured. + Selections 2 and 3: "global SRV slot 2 has view type texture, the shader needs raw_buffer" (and `typed_buffer` for 3) + before the dispatch, nothing dispatched, sentinels intact. +3. Discrimination control: `record --no-guard` on slot 0 expecting a refusal sees the changed sentinels (exit 3). A + texture slot is not dispatched without the guard: reading a texture descriptor as a raw buffer is undefined in D3D12. +4. `compile_dxil --requests` on each captured selection: 0 and 1 compile, 2 and 3 are refused with the slot/type text + and publish no `.cso`. +5. `replay` of the compiled `.cso` for 0 and 1 matches the CPU reference; the `.views` of 2 and 3 are refused before the + dispatch with sentinels intact. +6. Mutation control: replaying selection 0 against the slot 1 reference reports a mismatch. +7. Negative controls on both `compile_dxil` and `replay`: slot 0 rewritten to `texture`, no `need` line, no `select` + line, no line for the selected slot, `select 7`, and (replay) a missing `.views` file. Each gives an explicit + diagnostic, no `.cso`, and intact sentinels. +8. Shader shapes refused by `compile_dxil` even with valid metadata: a constant heap index, a heap descriptor load with + an immediate offset, and a stride read of the selected slot. + +## Result + +``` +cmake --preset dev +cmake --build --preset dev +ctest --preset dev --no-tests=error -R "^native_global_srv_heap_replay(_warp|_hardware)?$" -V +``` + +- `native_global_srv_heap_replay_hardware`: passed, 70 assertions (NVIDIA GeForce RTX 3080, driver 32.0.16.2124, + Windows 11 build 26200, MSVC toolset 14.51.36231, Windows SDK 10.0.26100 DXC, D3D12 debug layer not enabled). +- `native_global_srv_heap_replay_warp`: skipped (77), "adapter has no 32-lane waves (4..4)". The native module declares + `WaveSize=32`; WARP offers 4-lane waves only. The skip is not evidence for the fixture. +- `ctest --preset dev --no-tests=error -R ^native_ -j 1`: same result as before the change apart from the two new tests + (one known failure, `native_wave_request_hardware`, #2915, addressed by #2928). +- Revert control: with the heap refusal restored for every contract, `record` for selection 0 exits 4 with "direct + resource-heap load requires the selected GPU slot and its view type". + +## Limits + +- Only raw buffer heap reads are translated; other view classes are refused with a named diagnostic. +- The selected slot's index is per-lane VGPR data in general; reads stay inside the raw buffer view, which returns 0 + out of bounds. No static index bound is checked. +- Replay regenerates the slot contents deterministically from the slot index; `.views` captures type, stride and size, + not contents. +- In the direct DXIL path a stride read of a GPU-selected heap slot is refused. The HLSL path's `heap_stride_srv` + (`src/gfx1013_compute_native.cpp`, used by `tests/native_compute_grid.cpp`) is unchanged. +- The captured `select` must be the slot index the dispatch addresses; producing it from a title capture is outside this + fixture. diff --git a/src/direct_compute_cache.cpp b/src/direct_compute_cache.cpp index 9141aa7f86..729e72a3e2 100644 --- a/src/direct_compute_cache.cpp +++ b/src/direct_compute_cache.cpp @@ -295,12 +295,17 @@ size_t index_graphics_interfaces(const fs::path &source, const fs::path &cache) return count; } NativeComputeShader prepare_direct_compute(const std::filesystem::path &input, unsigned entry, bool container, - const std::filesystem::path &cache, bool &cache_hit) { + const std::filesystem::path &cache, bool &cache_hit, + HeapViewContract heap_view) { + if (!container && heap_view != HeapViewContract::none) + throw std::runtime_error("a heap view contract needs a container request"); ComputeRequest request{}; ComputeContainer packed; Bytes identity = X2W_NATIVE_SHADER_REVISION; identity += container ? "/container/cs_6_6" : "/slot67/cs_6_6"; word(identity, container ? 0 : entry); + if (heap_view != HeapViewContract::none) + identity += heap_view == HeapViewContract::raw_buffer ? "/heap-view/raw_buffer" : "/heap-view/other"; if (container) { packed = read_compute_container(input); identity += shader_digest(packed.bytes) + shader_digest(packed.root); @@ -322,7 +327,7 @@ NativeComputeShader prepare_direct_compute(const std::filesystem::path &input, u } } if (!cache_hit) { - program = container ? translate_compute_container(std::move(packed)) : translate_compute(request, entry, true); + program = container ? translate_compute_container(std::move(packed), heap_view) : translate_compute(request, entry, true); publish(path, key, encode(program)); } return program; diff --git a/src/direct_compute_cache.h b/src/direct_compute_cache.h index 334e628c01..d74c9e7e00 100644 --- a/src/direct_compute_cache.h +++ b/src/direct_compute_cache.h @@ -8,7 +8,8 @@ size_t index_graphics_interfaces(const std::filesystem::path &source, const std: // Signature component (f32/u32/i32) for supported typed IA and RTV formats. unsigned dxil_io_component(unsigned dxgi_format); NativeComputeShader prepare_direct_compute(const std::filesystem::path &input, unsigned entry, bool container, - const std::filesystem::path &cache, bool &cache_hit); + const std::filesystem::path &cache, bool &cache_hit, + HeapViewContract heap_view = HeapViewContract::none); DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view b, const std::filesystem::path &cache, bool &cache_hit, std::string_view root = {}, std::string_view input_layout = {}, diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index 419f5928b7..1908d31fb0 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -1351,7 +1351,8 @@ void lower_blocks(Emit &e) { #include "gfx1013_direct_compute.inl" #include "gfx1013_direct_graphics.inl" } // namespace -static NativeComputeShader translate_program(const ComputeRequest &request, unsigned entry, bool direct_dxil, const GuestShaderStage *stage) { +static NativeComputeShader translate_program(const ComputeRequest &request, unsigned entry, bool direct_dxil, const GuestShaderStage *stage, + HeapViewContract heap_view) { if (entry == 36 && ((word(request.code, 0) >> 16) != 0xd580 || (word(request.code, 12) >> 16) != 0xd580 || (word(request.code, 24) >> 16) != 0xd580 || (word(request.code, 36) >> 16) != 0xbfa0)) refuse(entry, "unrecognized compute header"); @@ -1464,6 +1465,7 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi if (direct_dxil) { DirectCompute compiler{emit}; compiler.wave64 = wave64; + compiler.heap_view = heap_view; if (wave64 && threads % 64) refuse(entry, "wave64 exchange requires complete guest waves"); if (wave64 && threads > 64) { const auto &code = program.code; @@ -1635,10 +1637,10 @@ void x2w::apply_scalar_table_layout(ComputeViewBinding &binding, const D3D12_ROO } x2w::NativeComputeShader x2w::translate_compute(const ComputeRequest &request, unsigned entry, bool direct_dxil) { - return translate_program(request, entry, direct_dxil, nullptr); + return translate_program(request, entry, direct_dxil, nullptr, HeapViewContract::none); } -x2w::NativeComputeShader x2w::translate_compute_container(ComputeContainer container) { +x2w::NativeComputeShader x2w::translate_compute_container(ComputeContainer container, HeapViewContract heap_view) { auto stages = read_guest_shader_container(container.bytes); GuestShaderStage *compute = nullptr; for (auto &stage : stages) { @@ -1650,7 +1652,7 @@ x2w::NativeComputeShader x2w::translate_compute_container(ComputeContainer conta ComputeRequest request{}; request.code = std::move(compute->code); request.root = std::move(container.root); - return translate_program(request, 0, true, compute); + return translate_program(request, 0, true, compute, heap_view); } x2w::NativeComputeShader x2w::translate_graphics_container(const std::string &bytes,bool pixel) { diff --git a/src/gfx1013_compute_native.h b/src/gfx1013_compute_native.h index e9817c4a96..760f76511c 100644 --- a/src/gfx1013_compute_native.h +++ b/src/gfx1013_compute_native.h @@ -108,9 +108,14 @@ struct NativeComputeShader { bool vertex_fetch = false; std::array pixel_writes{}; }; +// The view class a GPU-selected descriptor heap slot is read as. none: the slot and its view type are not known, so a +// heap read is refused. raw_buffer: the capture says the selected slot is a raw buffer SRV. other: the capture names a +// view type that is not translated (refused when the shader reads the heap). +enum class HeapViewContract : unsigned { none, raw_buffer, other }; NativeComputeShader translate_compute(const ComputeRequest &request, unsigned entry_byte_offset, bool direct_dxil = false); -NativeComputeShader translate_compute_container(ComputeContainer container); +NativeComputeShader translate_compute_container(ComputeContainer container, + HeapViewContract heap_view = HeapViewContract::none); struct NativeVertexElement { std::string semantic; unsigned index, format, slot, offset, classification, step_rate; diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 58d48529cd..faaeadde2c 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -8,6 +8,8 @@ struct DirectCompute { unsigned exchange_words = 0; bool uses_exchange = false; bool wave64 = false; + // The view class a GPU-selected heap slot is read as; see HeapViewContract. + HeapViewContract heap_view = HeapViewContract::none; std::vector scc_live; unsigned label_number = 0; bool pixel_stage = false; @@ -247,11 +249,19 @@ struct DirectCompute { } } } + // Refuses a GPU-selected heap read that the contract does not cover. raw_buffer is the only class that is translated. + void refuse_heap_contract(unsigned pc) const { + if (heap_view == HeapViewContract::none) + refuse(pc, "direct resource-heap load requires the selected GPU slot and its view type"); + if (heap_view == HeapViewContract::other) + refuse(pc, "GPU-selected heap slot view type is not raw_buffer; only raw buffer heap reads are translated"); + } // A raw buffer SRV chosen by a GPU value in the whole descriptor heap: ResourceDescriptorHeap[slot]. The view class the // shader reads is the one this handle is annotated with (raw buffer); a slot holding another class is refused by the // dispatch before the shader runs. The binding names the heap (no table register); the pipeline indexes it directly. string heap_resource(const Inst &i, const State &s, unsigned base, ComputeViewKind kind, unsigned bytes) { const auto &symbol = s.at(base); + refuse_heap_contract(i.pc); if (kind != ComputeViewKind::raw_vector_srv && kind != ComputeViewKind::buffer_srv) refuse(i.pc, "a GPU-selected heap slot is read as a raw buffer SRV only"); if (symbol.offset % 32 || s[base].type != Symbol::Type::indexed_descriptor) @@ -270,7 +280,9 @@ struct DirectCompute { bindings.push_back({ComputeViewKind::heap_buffer_srv, compute_resource_heap, 0, 0, bytes}); else it->required_bytes = (std::max)(it->required_bytes, bytes); - ir.features |= 16; + // 16: raw buffers. 0x40000000: the module reads ResourceDescriptorHeap (DXC sets both for the HLSL reference, + // see tests/native_heap_handle_probe_check.py); the validator refuses a module whose flags do not match. + ir.features |= 16 | 0x40000000; return ir.heap_handle(ir.binary("add", read(base), to_string(symbol.offset / 32)), 11, 0); } string resource(const Inst &i, const State &s, unsigned base, ComputeViewKind kind, unsigned bytes, @@ -388,9 +400,21 @@ struct DirectCompute { unsigned so = i.b >> 25; const auto &low = s.at(i.src[0]); const bool root = low.type == Symbol::Type::root_address; + if (!root && low.type == Symbol::Type::table && low.value == compute_resource_heap) { + // Reads from the whole descriptor heap: only the indexed descriptor load of a captured raw buffer slot. + if (i.op >= 8) + refuse(i.pc, "scalar buffer load from the descriptor heap is not translated"); + refuse_heap_contract(i.pc); + if (so == 125) + refuse(i.pc, "heap descriptor load needs a GPU-selected index (SGPR offset)"); + // The captured selection names the slot the GPU data selects; a constant index or an immediate offset + // would address another slot than the one the guard checked. + if (s.at(so).type == Symbol::Type::constant) + refuse(i.pc, "heap descriptor index is a constant; the captured selection must come from GPU data"); + if (i.b & 0xfffff) + refuse(i.pc, "heap descriptor load with an immediate offset addresses another slot than the captured selection"); + } if (i.op < 8 && !root) { - if (low.type == Symbol::Type::table && low.value == compute_resource_heap) - refuse(i.pc, "direct resource-heap load requires the selected GPU slot and its view type"); if (s.at(i.src[0]).type != Symbol::Type::table || s.at(i.src[0] + 1).type != Symbol::Type::constant || s.at(i.src[0] + 1).value != 0) refuse(i.pc, "direct descriptor address outside bound table"); @@ -1428,22 +1452,10 @@ struct DirectCompute { const auto field = source(i, i.src[1], state); if (descriptor.type == Symbol::Type::indexed_descriptor && descriptor.value == compute_resource_heap && descriptor.offset % 32 == 4 && field.type == Symbol::Type::constant && field.value == 0xe0010) { - auto &bindings = analysis.result.bindings; - auto it = std::find_if(bindings.begin(), bindings.end(), [](const auto &binding) { - return binding.kind == ComputeViewKind::heap_stride_srv; - }); - if (it == bindings.end()) { - bindings.push_back({ComputeViewKind::heap_stride_srv, compute_resource_heap, 0, analysis.srv++, 4}); - it = std::prev(bindings.end()); - } - ir.features |= 16; - auto handle = ir.handle({0, it->shader_register, 11, 0, 0, 0}); - auto slot = ir.binary("add", read(i.src[0]), to_string(descriptor.offset / 32)); - auto bytes = load_buffer(handle, ir.binary("shl", slot, "2"), true, 1); - auto stride = ir.binary("and", ir.value("extractvalue %dx.types.ResRet.i32 " + bytes + ", 0"), "16383"); - write(i.dst, stride); - write(128, ir.value("zext i1 " + cmp("ne", stride, "0") + " to i32")); - return; + // Reachable only through a heap descriptor load, which needs the raw_buffer contract. A raw buffer view + // has no stride to read, so the stride of a GPU-selected slot stays untranslated in the direct path. + refuse_heap_contract(i.pc); + refuse(i.pc, "a GPU-selected heap slot stride read is not translated with a view contract"); } } auto a = val(0); diff --git a/src/native_compute_pipeline.cpp b/src/native_compute_pipeline.cpp index a7fa824eaf..4ca6ff9477 100644 --- a/src/native_compute_pipeline.cpp +++ b/src/native_compute_pipeline.cpp @@ -16,11 +16,14 @@ bool is_uav(const ComputeViewBinding &binding) { return compute_uav(binding.kind NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, ShaderDxilCompiler &compiler, const std::filesystem::path &marker, unsigned entry, - const std::filesystem::path &cache, bool direct_dxil) { + const std::filesystem::path &cache, bool direct_dxil, + HeapViewContract heap_view) { + if (!direct_dxil && heap_view != HeapViewContract::none) + throw std::runtime_error("a heap view contract needs the direct DXIL path"); NativeComputePipeline pipeline; auto start = Clock::now(); auto program = direct_dxil - ? prepare_direct_compute(marker,entry,marker.extension()==L".cdx",cache,pipeline.frontend_cache_hit) + ? prepare_direct_compute(marker,entry,marker.extension()==L".cdx",cache,pipeline.frontend_cache_hit,heap_view) : translate_compute(read_compute_request(marker), entry, direct_dxil); pipeline.instructions = program.instruction_count; pipeline.bindings = std::move(program.bindings); diff --git a/src/native_compute_pipeline.h b/src/native_compute_pipeline.h index 2494665e27..9951cc67dc 100644 --- a/src/native_compute_pipeline.h +++ b/src/native_compute_pipeline.h @@ -31,6 +31,7 @@ struct NativeComputePipeline { NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, ShaderDxilCompiler &compiler, const std::filesystem::path &marker, unsigned entry, - const std::filesystem::path &cache, bool direct_dxil = false); + const std::filesystem::path &cache, bool direct_dxil = false, + HeapViewContract heap_view = HeapViewContract::none); } // namespace x2w diff --git a/src/startup_stubs/native_global_srv.h b/src/startup_stubs/native_global_srv.h index fa258a802b..0ea0f62d9a 100644 --- a/src/startup_stubs/native_global_srv.h +++ b/src/startup_stubs/native_global_srv.h @@ -3,6 +3,8 @@ #include "native_buffer_stride.h" #include #include +#include +#include #include #include #include @@ -13,6 +15,9 @@ // known: the capture keeps {slot, type, stride} for each slot of the heap, and the dispatch is refused, before any // shader runs, when the selected slot holds another type than the one the shader reads. No heap-indexed data read is // translated here; this header only classifies, serializes and checks. +// +// A .views file describes the one dispatch it was captured from. It is not part of the .cdx/.root content key of the +// request it sits next to. namespace x2w_startup { enum class GlobalSrvType : unsigned { none, raw_buffer, structured_buffer, typed_buffer, texture }; @@ -37,6 +42,7 @@ struct GlobalSrvView { unsigned slot = 0; GlobalSrvType type = GlobalSrvType::none; unsigned stride = 0; // Bytes per element for a buffer view (the value native_view_stride gives), 0 for a texture. + std::uint64_t bytes = 0; // Size of the buffer in bytes, 0 for a texture. Set by the caller from the resource description. }; // Classifies the description a title passed for an SRV (slot 18 of the device interface). False: not a view this @@ -69,9 +75,9 @@ struct GlobalSrvRequest { inline std::string encode_global_srv_request(const GlobalSrvRequest &request) { std::ostringstream out; - out << "x2w-global-srv-views 1\nselect " << request.selected << "\nneed " << global_srv_type_name(request.needed) << '\n'; + out << "x2w-global-srv-views 2\nselect " << request.selected << "\nneed " << global_srv_type_name(request.needed) << '\n'; for (const auto &view : request.views) - out << "slot " << view.slot << ' ' << global_srv_type_name(view.type) << ' ' << view.stride << '\n'; + out << "slot " << view.slot << ' ' << global_srv_type_name(view.type) << ' ' << view.stride << ' ' << view.bytes << '\n'; return out.str(); } @@ -80,8 +86,8 @@ inline bool decode_global_srv_request(const std::string &text, GlobalSrvRequest request = {}; std::istringstream in(text); std::string line; - if (!std::getline(in, line) || line != "x2w-global-srv-views 1") { - error = "global SRV view metadata has no 'x2w-global-srv-views 1' header"; + if (!std::getline(in, line) || line != "x2w-global-srv-views 2") { + error = "global SRV view metadata has no 'x2w-global-srv-views 2' header"; return false; } bool has_need = false; @@ -105,7 +111,7 @@ inline bool decode_global_srv_request(const std::string &text, GlobalSrvRequest } else if (key == "slot") { GlobalSrvView view; std::string name; - if (!(fields >> view.slot >> name >> view.stride)) { + if (!(fields >> view.slot >> name >> view.stride >> view.bytes)) { error = "global SRV view metadata: unreadable slot line"; return false; } diff --git a/tests/cmake/native_global_srv_heap_replay.cmake b/tests/cmake/native_global_srv_heap_replay.cmake new file mode 100644 index 0000000000..b966866a65 --- /dev/null +++ b/tests/cmake/native_global_srv_heap_replay.cmake @@ -0,0 +1,15 @@ +# GPU-selected global SRV heap slot: record and offline request replay with captured view types (issue #2908). +# The fixture runs the native recording path (NativeRecording and NativeDispatchStates) and the compile_dxil request +# replay on the same accepted and refused selections. _warp skips (77): WARP has no 32-lane waves. +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll" AND EXISTS "${INTAKE_PYTHON}") + add_executable(native_global_srv_heap_replay tests/native_global_srv_heap_replay.cpp tests/desktop_gpu.cpp) + target_include_directories(native_global_srv_heap_replay PRIVATE src tests) + target_link_libraries(native_global_srv_heap_replay PRIVATE x2w_shader_compiler d3d12 dxgi d3dcompiler) + set_property(TARGET native_global_srv_heap_replay PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_global_srv_heap_replay_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_global_srv_heap_replay_check.py" + "$" "$" "${DXC_BIN_DIR}" ${adapter}) + set_tests_properties(native_global_srv_heap_replay_${adapter} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + endforeach() +endif() diff --git a/tests/native_global_srv_heap_replay.cpp b/tests/native_global_srv_heap_replay.cpp new file mode 100644 index 0000000000..c0d823b1aa --- /dev/null +++ b/tests/native_global_srv_heap_replay.cpp @@ -0,0 +1,451 @@ +// Native compute fixture whose shader picks a global (descriptor heap) SRV slot from a GPU input. +// +// root OUT.root writes the root signature the request container carries. +// record SDK CACHE REQ.cdx ADAPTER SELECTOR EXPECT [--no-guard] +// Native recording path: reads the GPU selector back before the dispatch, captures {select, view types} +// into REQ.views, refuses a slot of another view type before the shader runs, otherwise records the +// dispatch with x2w_startup::NativeRecording and NativeDispatchStates and compares the fenced output. +// replay SDK CACHE REQ.cdx COMPILED.cso VIEWS ADAPTER EXPECT REFERENCE_SLOT +// Offline request replay: decodes VIEWS, refuses before the dispatch or runs the compiled.cso shader on a +// heap rebuilt from the captured slot types and compares with the reference slot data. +// EXPECT is "ok" or "refused". Exit 0: outcome as expected. 1: output mismatch for an expected-ok case. 3: the +// outcome differs from the expectation. 4: setup error. 77: capability skip. +#include "desktop_gpu.h" +#include "native_compute_pipeline.h" +#include "startup_stubs/native_dispatch_states.h" +#include "startup_stubs/native_global_srv.h" +#include "startup_stubs/native_recording.h" +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; +using x2w_startup::GlobalSrvType; +using x2w_startup::GlobalSrvView; +namespace fs = std::filesystem; + +namespace { +constexpr unsigned slot_count = 4, slot_words = 64, selector_page_slot = 4, output_page_slot = 5; +constexpr unsigned output_words = 72; +constexpr std::uint32_t sentinel = 0x69696969u; + +// Backing data of a raw buffer slot, deterministic from the slot index. +std::uint32_t slot_word(unsigned slot, unsigned index) { return 0xA0000000u + slot * 0x10000000u + index; } + +struct Rig { + ComPtr device; + ComPtr queue; + ComPtr allocator; + ComPtr list; + ComPtr fence; + HANDLE event = nullptr; + UINT64 fence_value = 0; + x2w_startup::NativeRecording recording; + x2w_startup::NativeDescriptorTable page; + ComPtr selector, output; + std::vector> slots{slot_count}; // keeps the backing resources of the heap alive + std::vector> upload_keep; + + ~Rig() { + if (event) CloseHandle(event); + } + + // Returns 77 when the adapter cannot run the fixture; 0 when the rig is ready. + int open(const std::wstring &adapter) { + ComPtr factory; + ComPtr chosen; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 77; + if (adapter == L"warp") { + if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&chosen)))) return 77; + } else { + for (UINT i = 0; i < 8; ++i) { + ComPtr candidate; + if (factory->EnumAdapters1(i, &candidate) == DXGI_ERROR_NOT_FOUND) break; + DXGI_ADAPTER_DESC1 desc{}; + candidate->GetDesc1(&desc); + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) { + chosen = candidate; + std::printf("adapter=%ls\n", desc.Description); + break; + } + } + if (!chosen) { std::puts("no hardware adapter"); return 77; } + } + if (FAILED(D3D12CreateDevice(chosen.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) { + std::puts("no device"); + return 77; + } + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_6}; + D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; + if (FAILED(check_feature(device.Get(), D3D12_FEATURE_SHADER_MODEL, &model, sizeof model)) || + model.HighestShaderModel < D3D_SHADER_MODEL_6_6 || + FAILED(check_feature(device.Get(), D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof options)) || + options.ResourceBindingTier < D3D12_RESOURCE_BINDING_TIER_3) { + std::printf("adapter lacks shader model 6.6 or resource binding tier 3 (tier %d)\n", + int(options.ResourceBindingTier)); + return 77; + } + // The native module declares WaveSize=32 (the guest wave), so an adapter without 32-lane waves cannot run it. + D3D12_FEATURE_DATA_D3D12_OPTIONS1 waves{}; + if (FAILED(check_feature(device.Get(), D3D12_FEATURE_D3D12_OPTIONS1, &waves, sizeof waves)) || !waves.WaveOps || + waves.WaveLaneCountMin > 32 || waves.WaveLaneCountMax < 32) { + std::printf("adapter has no 32-lane waves (%u..%u)\n", waves.WaveLaneCountMin, waves.WaveLaneCountMax); + return 77; + } + D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + check(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)), "queue"); + check(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), "allocator"); + check(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(&list)), + "list"); + check(list->Close(), "close"); + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "fence"); + event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!event) throw std::runtime_error("event"); + // The descriptor page of one native recording: slots 0..3 are selectable, 4 is t0, 5 is u0. + page = recording.allocate(device.Get(), 6); + return 0; + } + + D3D12_CPU_DESCRIPTOR_HANDLE cpu(unsigned index) const { + auto handle = page.cpu; + handle.ptr += SIZE_T(index) * page.increment; + return handle; + } + D3D12_GPU_DESCRIPTOR_HANDLE first_gpu() const { + auto handle = page.gpu; + handle.ptr += UINT64(selector_page_slot) * page.increment; + return handle; + } + + void wait() { + check(queue->Signal(fence.Get(), ++fence_value), "signal"); + check(fence->SetEventOnCompletion(fence_value, event), "fence event"); + if (WaitForSingleObject(event, 30000) != WAIT_OBJECT_0) throw std::runtime_error("fence wait timed out"); + } + // Records `body` on the one list and waits for its fence. + template void run(Body body) { + check(allocator->Reset(), "allocator reset"); + check(list->Reset(allocator.Get(), nullptr), "list reset"); + body(list.Get()); + check(list->Close(), "list close"); + ID3D12CommandList *lists[]{list.Get()}; + queue->ExecuteCommandLists(1, lists); + wait(); + } + // A command list with no commands: what a refused request submits instead of the dispatch. + void run_empty() { + run([](ID3D12GraphicsCommandList *) {}); + } + void fill(ID3D12Resource *destination, const std::vector &words) { + const UINT64 bytes = words.size() * 4; + auto upload = make_buffer(device.Get(), bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + void *mapped = nullptr; + D3D12_RANGE none{}; + check(upload->Map(0, &none, &mapped), "upload map"); + std::memcpy(mapped, words.data(), bytes); + upload->Unmap(0, nullptr); + run([&](ID3D12GraphicsCommandList *l) { l->CopyBufferRegion(destination, 0, upload.Get(), 0, bytes); }); + } + std::vector read(ID3D12Resource *source, unsigned words) { + auto readback = make_buffer(device.Get(), UINT64(words) * 4, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + run([&](ID3D12GraphicsCommandList *l) { l->CopyBufferRegion(readback.Get(), 0, source, 0, UINT64(words) * 4); }); + std::vector out(words); + void *mapped = nullptr; + D3D12_RANGE range{0, UINT64(words) * 4}; + check(readback->Map(0, &range, &mapped), "readback map"); + std::memcpy(out.data(), mapped, out.size() * 4); + D3D12_RANGE written{}; + readback->Unmap(0, &written); + return out; + } + + // t0 (the selector, a raw buffer) and u0 (72 words of output) in their page slots. + void create_io() { + selector = make_buffer(device.Get(), 4, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON); + output = make_buffer(device.Get(), output_words * 4, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Buffer.NumElements = 1; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(selector.Get(), &srv, cpu(selector_page_slot)); + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{}; + uav.Format = DXGI_FORMAT_R32_TYPELESS; + uav.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + uav.Buffer.NumElements = output_words; + uav.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device->CreateUnorderedAccessView(output.Get(), nullptr, &uav, cpu(output_page_slot)); + } + void fill_sentinel() { fill(output.Get(), std::vector(output_words, sentinel)); } + bool sentinels_intact() { + for (auto word : read(output.Get(), output_words)) + if (word != sentinel) return false; + return true; + } + + // Creates the backing resource and the SRV of one selectable slot. Returns the captured view: the class is + // classified from the exact description passed to CreateShaderResourceView, the size from the resource. + GlobalSrvView add_slot(unsigned slot, GlobalSrvType type, std::uint64_t bytes) { + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (type == GlobalSrvType::texture) { + D3D12_RESOURCE_DESC texture{}; + texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + texture.Width = texture.Height = 8; + texture.DepthOrArraySize = texture.MipLevels = 1; + texture.Format = DXGI_FORMAT_R32_UINT; + texture.SampleDesc.Count = 1; + slots[slot] = resource(device.Get(), texture, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON); + desc.Format = DXGI_FORMAT_R32_UINT; + desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + desc.Texture2D.MipLevels = 1; + } else if (type == GlobalSrvType::raw_buffer || type == GlobalSrvType::typed_buffer) { + if (!bytes || bytes % 4 || bytes > (1u << 20)) + throw std::runtime_error("slot " + std::to_string(slot) + " has an unusable buffer size"); + slots[slot] = make_buffer(device.Get(), bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON); + std::vector data(bytes / 4); + for (unsigned i = 0; i < data.size(); ++i) data[i] = slot_word(slot, i); + fill(slots[slot].Get(), data); + desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + desc.Buffer.NumElements = static_cast(bytes / 4); + if (type == GlobalSrvType::raw_buffer) { + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + } else { + desc.Format = DXGI_FORMAT_R32_UINT; + } + } else { + throw std::runtime_error(std::string("view type ") + x2w_startup::global_srv_type_name(type) + + " cannot be rebuilt by this fixture"); + } + device->CreateShaderResourceView(slots[slot].Get(), &desc, cpu(slot)); + GlobalSrvView view; + if (!x2w_startup::classify_global_srv_view(slot, &desc, sizeof desc, view)) + throw std::runtime_error("slot view could not be classified"); + if (view.type != type) throw std::runtime_error("slot view classified as another type"); + view.bytes = type == GlobalSrvType::texture ? 0 : slots[slot]->GetDesc().Width; + return view; + } + + unsigned read_selector(unsigned value) { + fill(selector.Get(), {value}); + return read(selector.Get(), 1)[0]; + } + + // Barriers from the views of the dispatch (NativeDispatchStates), the dispatch, the barriers back, the fence. + // `state` is the pipeline-state object to run (null: the one bind() set). + void dispatch(const x2w::NativeComputePipeline &pipeline, ID3D12PipelineState *state, ID3D12Resource *selected) { + struct View { + ComPtr resource; + bool write = false; + x2w_startup::NativeTextureWindow texture{}; + struct { bool upload = false; } buffer; + }; + std::vector views; + views.push_back({selector, false, {}, {}}); + views.push_back({output, true, {}, {}}); + views.push_back({selected, false, {}, {}}); + x2w_startup::NativeDispatchStates states(views); + std::vector before, after; + states.whole_states([&](ID3D12Resource *resource, D3D12_RESOURCE_STATES target) { + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON, target}; + before.push_back(b); + std::swap(b.Transition.StateBefore, b.Transition.StateAfter); + after.push_back(b); + }); + run([&](ID3D12GraphicsCommandList *l) { + l->ResourceBarrier(UINT(before.size()), before.data()); + pipeline.bind(l, page.heap, first_gpu(), page.increment); + if (state) l->SetPipelineState(state); + l->Dispatch(1, 1, 1); + l->ResourceBarrier(UINT(after.size()), after.data()); + }); + } +}; + +std::vector reference_output(unsigned slot) { + std::vector words(output_words, sentinel); + for (unsigned i = 0; i < slot_words; ++i) words[i] = slot_word(slot, i); + return words; +} + +// 0: the 72 words equal the reference; 1 prints the first mismatch. +int compare_output(Rig &rig, unsigned reference_slot) { + const auto expected = reference_output(reference_slot); + const auto actual = rig.read(rig.output.Get(), output_words); + for (unsigned i = 0; i < output_words; ++i) + if (actual[i] != expected[i]) { + std::printf("mismatch word %u: got 0x%08x expected 0x%08x (reference slot %u)\n", i, actual[i], expected[i], + reference_slot); + return 1; + } + std::printf("output matches slot %u data (%u words) and the %u sentinel words are intact\n", reference_slot, + slot_words, output_words - slot_words); + return 0; +} + +// The refused path of both modes: no dispatch is recorded, and the output must be untouched. +int refused_path(Rig &rig, bool expect_ok) { + rig.run_empty(); + const bool intact = rig.sentinels_intact(); + std::printf("no dispatch submitted; u0 sentinels %s\n", intact ? "intact" : "CHANGED"); + return (!expect_ok && intact) ? 0 : 3; +} + +int write_root(const fs::path &destination) { + D3D12_DESCRIPTOR_RANGE ranges[2]{}; + ranges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + ranges[0].NumDescriptors = 1; + ranges[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; + ranges[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV; + ranges[1].NumDescriptors = 1; + ranges[1].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; + D3D12_ROOT_PARAMETER parameter{}; + parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameter.DescriptorTable = {2, ranges}; + D3D12_ROOT_SIGNATURE_DESC desc{1, ¶meter, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr blob, error; + if (FAILED(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, &error))) + throw std::runtime_error("root signature serialization failed"); + std::ofstream file(destination, std::ios::binary); + file.write(static_cast(blob->GetBufferPointer()), static_cast(blob->GetBufferSize())); + file.close(); + if (!file) throw std::runtime_error("could not write the root signature"); + return 0; +} + +// The pipeline must read t0 and u0 through the tables and the selected slot through the heap. +void check_pipeline_shape(const x2w::NativeComputePipeline &pipeline) { + if (!pipeline.heap_indexed || pipeline.srv_count != 1 || pipeline.uav_count != 1 || pipeline.constant_words) + throw std::runtime_error("native pipeline has an unexpected binding layout"); +} + +int record(int argc, wchar_t **argv) { + if (argc != 8 && argc != 9) return 2; + const std::wstring expect = argv[7]; + const bool guard = !(argc == 9 && std::wstring_view(argv[8]) == L"--no-guard"); + if ((argc == 9 && guard) || (expect != L"ok" && expect != L"refused")) return 2; + const unsigned selector = static_cast(std::stoul(argv[6])); + const fs::path cdx = argv[4]; + Rig rig; + if (int skip = rig.open(argv[5])) return skip; + try { + x2w::ShaderDxilCompiler compiler(argv[2]); + auto pipeline = x2w::create_native_compute_pipeline(rig.device.Get(), compiler, cdx, 0, argv[3], true, + x2w::HeapViewContract::raw_buffer); + check_pipeline_shape(pipeline); + rig.create_io(); + x2w_startup::GlobalSrvRequest request; + request.needed = GlobalSrvType::raw_buffer; + request.views.push_back(rig.add_slot(0, GlobalSrvType::raw_buffer, slot_words * 4)); + request.views.push_back(rig.add_slot(1, GlobalSrvType::raw_buffer, slot_words * 4)); + request.views.push_back(rig.add_slot(2, GlobalSrvType::texture, 0)); + request.views.push_back(rig.add_slot(3, GlobalSrvType::typed_buffer, slot_words * 4)); + rig.fill_sentinel(); + // The selector is GPU data: it is read back (one CPU/GPU sync) before the dispatch is recorded. + request.selected = rig.read_selector(selector); + request.has_selected = true; + auto views_path = cdx; + views_path.replace_extension(L".views"); + std::ofstream(views_path, std::ios::binary) << x2w_startup::encode_global_srv_request(request); + std::printf("captured select=%u need=raw_buffer views=%s\n", request.selected, views_path.string().c_str()); + const auto diagnostic = x2w_startup::refuse_global_srv_selection(request.views, request.selected, request.needed); + if (!diagnostic.empty() && guard) { + std::printf("refused select=%u: %s\n", request.selected, diagnostic.c_str()); + return refused_path(rig, expect == L"ok"); + } + if (request.selected >= slot_count || request.views[request.selected].type != GlobalSrvType::raw_buffer) + throw std::runtime_error("--no-guard only dispatches a raw buffer slot"); + rig.dispatch(pipeline, nullptr, rig.slots[request.selected].Get()); + if (expect == L"refused") { + // Discrimination control: without the guard the shader ran, so the output must have changed. + const bool intact = rig.sentinels_intact(); + std::printf("dispatch ran (%s); %s\n", guard ? "no refusal" : "guard disabled", + intact ? "sentinels intact" : "sentinels changed"); + return 3; + } + return compare_output(rig, request.selected); + } catch (const std::exception &error) { + std::printf("setup error: %s\n", error.what()); + return 4; + } +} + +int replay(int argc, wchar_t **argv) { + if (argc != 10) return 2; + const std::wstring expect = argv[8]; + if (expect != L"ok" && expect != L"refused") return 2; + const fs::path cdx = argv[4], cso = argv[5], views_path = argv[6]; + const unsigned reference_slot = static_cast(std::stoul(argv[9])); + Rig rig; + if (int skip = rig.open(argv[7])) return skip; + try { + rig.create_io(); + rig.fill_sentinel(); + std::string text, error; + x2w_startup::GlobalSrvRequest request; + std::ifstream file(views_path, std::ios::binary); + if (!file) { + error = "global SRV view metadata file missing: " + views_path.string(); + } else { + text.assign(std::istreambuf_iterator(file), {}); + x2w_startup::decode_global_srv_request(text, request, error); + } + if (error.empty()) + error = x2w_startup::refuse_global_srv_selection(request.views, request.selected, request.needed); + if (error.empty() && request.needed != GlobalSrvType::raw_buffer) + error = std::string("GPU-selected heap slot view type ") + x2w_startup::global_srv_type_name(request.needed) + + " is not raw_buffer; only raw buffer heap reads are translated"; + if (!error.empty()) { + std::printf("refused: %s\n", error.c_str()); + return refused_path(rig, expect == L"ok"); + } + x2w::ShaderDxilCompiler compiler(argv[2]); + auto pipeline = x2w::create_native_compute_pipeline(rig.device.Get(), compiler, cdx, 0, argv[3], true, + x2w::HeapViewContract::raw_buffer); + check_pipeline_shape(pipeline); + std::ifstream shader(cso, std::ios::binary); + if (!shader) throw std::runtime_error("missing compiled shader " + cso.string()); + const std::string dxil((std::istreambuf_iterator(shader)), {}); + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = pipeline.root.Get(); + pso.CS = {dxil.data(), dxil.size()}; + ComPtr compiled; + check(rig.device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&compiled)), "compiled shader pipeline"); + for (const auto &view : request.views) { + if (view.slot >= slot_count) throw std::runtime_error("captured slot outside the fixture heap page"); + rig.add_slot(view.slot, view.type, view.bytes); + } + rig.read_selector(request.selected); + rig.dispatch(pipeline, compiled.Get(), rig.slots[request.selected].Get()); + const int result = compare_output(rig, reference_slot); + if (expect == L"refused") return 3; // ran when a refusal was expected + return result; + } catch (const std::exception &error) { + std::printf("setup error: %s\n", error.what()); + return 4; + } +} +} // namespace + +int wmain(int argc, wchar_t **argv) { + try { + if (argc >= 2 && std::wstring_view(argv[1]) == L"root" && argc == 3) return write_root(argv[2]); + if (argc >= 2 && std::wstring_view(argv[1]) == L"record") return record(argc, argv); + if (argc >= 2 && std::wstring_view(argv[1]) == L"replay") return replay(argc, argv); + } catch (const std::exception &error) { + std::printf("setup error: %s\n", error.what()); + return 4; + } + std::fputs("usage: native_global_srv_heap_replay root OUT.root | record SDK CACHE REQ.cdx ADAPTER SELECTOR ok|refused " + "[--no-guard] | replay SDK CACHE REQ.cdx COMPILED.cso VIEWS ADAPTER ok|refused REFERENCE_SLOT\n", stderr); + return 2; +} diff --git a/tests/native_global_srv_heap_replay_check.py b/tests/native_global_srv_heap_replay_check.py new file mode 100644 index 0000000000..22776f8098 --- /dev/null +++ b/tests/native_global_srv_heap_replay_check.py @@ -0,0 +1,259 @@ +"""GPU-selected global SRV heap slot: native recording and offline request replay (issue #2908). + +usage: native_global_srv_heap_replay_check.py FIXTURE COMPILE_DXIL SDK ADAPTER + +A source-built compute container picks a descriptor heap slot from a GPU buffer (t0), reads 64 words through +ResourceDescriptorHeap[slot] and stores them to u0. Slots 0 and 1 are raw buffers with different data, slot 2 is a +texture, slot 3 a typed buffer. The fixture's `record` mode captures the GPU selector and the slot view types into a +req_.views file and refuses the incompatible slots before the dispatch; `compile_dxil` and the fixture's `replay` +mode consume the same file offline. Exit 77 when the fixture reports a capability skip. +""" +import pathlib +import shutil +import struct +import subprocess +import sys +import tempfile +import zlib + +fixture, compile_dxil, sdk, adapter = sys.argv[1:5] +RAW = "global SRV slot {n} has view type {t}, the shader needs raw_buffer" +HEAP_REFUSAL = "direct resource-heap load requires the selected GPU slot and its view type" + + +def words(*values): + return struct.pack(f"<{len(values)}I", *values) + + +def pack(body, extra=()): + raw = b"FSSM" + struct.pack(" exit {result.returncode}") + if result.returncode == 77 and str(command[0]) == fixture: + print("fixture capability skip (77)") + sys.exit(77) + return result.returncode, out, err + + +def require(condition, message): + if not condition: + print("FAIL: " + message) + sys.exit(1) + print("ok: " + message) + + +with tempfile.TemporaryDirectory(prefix="x2w_global_srv_") as scratch: + base = pathlib.Path(scratch) + cache = base / "cache" + cache.mkdir() + + # Fixture root signature, container, key (B6). + root_path = base / "fixture.root" + code, out, err = run([fixture, "root", root_path]) + require(code == 0 and root_path.stat().st_size > 0, "fixture wrote the root signature") + root = root_path.read_bytes() + cdx = compute_two_inputs(PROGRAM) + stem = "req_%016x" % key_of(root, cdx) + + def request_dir(name): + directory = base / name + directory.mkdir() + (directory / (stem + ".cdx")).write_bytes(cdx) + (directory / (stem + ".root")).write_bytes(root) + return directory + + def compile_directory(directory): + out_dir = base / (directory.name + "_out") + result = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + return result, out_dir / (stem + ".cso") + + selections = [request_dir(f"sel{n}") for n in range(4)] + nometa = request_dir("nometa") + + # 1. Missing metadata, offline: a heap shader without .views is refused before any output exists. + (code, out, err), cso = compile_directory(nometa) + require(code == 1 and HEAP_REFUSAL in err, "compile_dxil without .views refuses the heap read with the slot/type text") + require(not cso.exists(), "no .cso is published for the request without .views") + + # 2. Native recording path: accepted and refused selections. + for n in (0, 1): + views = selections[n] / (stem + ".views") + code, out, err = run([fixture, "record", sdk, cache, selections[n] / (stem + ".cdx"), adapter, n, "ok"]) + require(code == 0, f"record select {n}: fenced output equals the slot {n} data and u0 sentinels are intact") + require("output matches slot %d data" % n in out, f"record select {n} compared 64 words with the CPU reference") + text = views.read_text() + require(text.startswith("x2w-global-srv-views 2\nselect %d\nneed raw_buffer\n" % n), + f"record select {n} captured the GPU selector and the view type") + for line in ("slot 0 raw_buffer 1 256", "slot 1 raw_buffer 1 256", "slot 2 texture 0 0", "slot 3 typed_buffer 4 256"): + require(line + "\n" in text, f"captured view line '{line}'") + for n, type_name in ((2, "texture"), (3, "typed_buffer")): + code, out, err = run([fixture, "record", sdk, cache, selections[n] / (stem + ".cdx"), adapter, n, "refused"]) + require(code == 0, f"record select {n}: refused with unchanged u0 sentinels") + require(RAW.format(n=n, t=type_name) in out, f"record select {n}: slot/type diagnostic before the dispatch") + require("no dispatch submitted" in out and "sentinels intact" in out, f"record select {n}: nothing was dispatched") + + # 3. Discrimination control: without the guard a valid slot runs and changes u0, which the check must see. + code, out, err = run([fixture, "record", sdk, cache, selections[0] / (stem + ".cdx"), adapter, 0, "refused", "--no-guard"]) + require(code == 3 and "sentinels changed" in out, "record --no-guard expecting a refusal sees the changed sentinels (exit 3)") + + # 4. Offline replay compilation of the captured requests. + outputs = {} + for n in range(4): + (code, out, err), cso = compile_directory(selections[n]) + outputs[n] = cso + if n < 2: + require(code == 0 and "requests=1 compiled=1 refused=0" in out, f"compile_dxil select {n}: compiled") + require("global_srv select=%d need=raw_buffer" % n in out, f"compile_dxil select {n}: reports the captured selection") + require(cso.exists(), f"compile_dxil select {n}: published a .cso") + else: + type_name = "texture" if n == 2 else "typed_buffer" + require(code == 1 and "refused=1" in out, f"compile_dxil select {n}: refused") + require(RAW.format(n=n, t=type_name) in err, f"compile_dxil select {n}: slot/type diagnostic") + require(not cso.exists(), f"compile_dxil select {n}: no .cso") + + # 5. Fixture replay of the compiled shader and of the refusals. + def replay(directory, cso, views, expect, reference): + return run([fixture, "replay", sdk, cache, directory / (stem + ".cdx"), cso, views, adapter, expect, reference]) + + for n in (0, 1): + code, out, err = replay(selections[n], outputs[n], selections[n] / (stem + ".views"), "ok", n) + require(code == 0 and "output matches slot %d data" % n in out, f"replay select {n}: compiled shader output equals slot {n} data") + for n, type_name in ((2, "texture"), (3, "typed_buffer")): + code, out, err = replay(selections[0], outputs[0], selections[n] / (stem + ".views"), "refused", 0) + require(code == 0 and RAW.format(n=n, t=type_name) in out and "sentinels intact" in out, + f"replay select {n}: refused with the slot/type diagnostic, u0 sentinels intact") + + # 6. Mutation control: the slot 1 data is not the slot 0 reference. + code, out, err = replay(selections[0], outputs[0], selections[0] / (stem + ".views"), "ok", 1) + require(code == 1 and "mismatch word 0" in out, "replay select 0 compared with slot 1 data reports a mismatch (exit 1)") + + # 7. Negative controls on both paths: metadata that cannot reconstruct the binding. + good = (selections[0] / (stem + ".views")).read_text() + lines = good.splitlines() + + def variant(name, text, expected): + directory = request_dir("neg_" + name) + views = directory / (stem + ".views") + views.write_text(text, newline="\n") + (code, out, err), cso = compile_directory(directory) + require(code == 1 and expected in err, f"compile_dxil '{name}': refused with '{expected}'") + require(not cso.exists(), f"compile_dxil '{name}': no .cso") + code, out, err = replay(selections[0], outputs[0], views, "refused", 0) + require(code == 0 and expected in out and "sentinels intact" in out, + f"replay '{name}': refused with the same diagnostic, u0 sentinels intact") + + def without(prefix): + kept = [line for line in lines if not line.startswith(prefix)] + require(len(kept) == len(lines) - 1, f"control input drops exactly one '{prefix}' line") + return "\n".join(kept) + "\n" + + variant("mismatched_type", good.replace("slot 0 raw_buffer 1 256", "slot 0 texture 0 0"), RAW.format(n=0, t="texture")) + require("slot 0 texture 0 0" in (base / "neg_mismatched_type" / (stem + ".views")).read_text(), "mismatch input rewrote slot 0") + variant("no_need", without("need "), "global SRV view metadata lacks the needed view type") + variant("no_select", without("select "), "global SRV view metadata lacks the selected slot") + variant("no_slot_line", without("slot 0 "), "global SRV slot 0 has no captured view type") + variant("select_7", good.replace("select 0", "select 7"), "global SRV slot 7 has no captured view type") + + # 8. Shader shapes whose heap read could address another slot than the captured selection, or read the slot's + # stride: refused by compile_dxil even with valid metadata, no .cso. + words_list = list(struct.unpack(f"<{len(PROGRAM) // 4}I", PROGRAM)) + lshl = words_list.index(0x8f118510) + heap_load = words_list.index(0xf4080501) + shapes = { + # s_mov_b32 s17, 64 instead of the GPU-derived s_lshl_b32 s17, s16, 5 + "constant_index": (words_list[:lshl] + [0xbe9103c0] + words_list[lshl + 1:], + "heap descriptor index is a constant; the captured selection must come from GPU data"), + # s_load_dwordx4 s[20:23], s[2:3], s17 offset:0x20 + "immediate_offset": (words_list[:heap_load] + [0xf4080501, 0x22000020] + words_list[heap_load + 2:], + "heap descriptor load with an immediate offset addresses another slot than the captured selection"), + # s_bfe_u32 s24, s21, 0xe0010 after the heap descriptor load (stride field of the selected slot) + "stride_read": (words_list[:heap_load + 3] + [0x9398ff15, 0x000e0010] + words_list[heap_load + 3:], + "a GPU-selected heap slot stride read is not translated with a view contract"), + } + for name, (program, expected) in shapes.items(): + directory = base / ("shape_" + name) + directory.mkdir() + shape_cdx = compute_two_inputs(words(*program)) + shape_stem = "req_%016x" % key_of(root, shape_cdx) + (directory / (shape_stem + ".cdx")).write_bytes(shape_cdx) + (directory / (shape_stem + ".root")).write_bytes(root) + (directory / (shape_stem + ".views")).write_text(good, newline="\n") + out_dir = base / (directory.name + "_out") + code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + require(code == 1 and expected in err, f"compile_dxil shape '{name}': refused with '{expected}'") + require(not (out_dir / (shape_stem + ".cso")).exists(), f"compile_dxil shape '{name}': no .cso") + + missing = base / "missing" / (stem + ".views") + code, out, err = replay(selections[0], outputs[0], missing, "refused", 0) + require(code == 0 and "global SRV view metadata file missing: " + str(missing) in out and "sentinels intact" in out, + "replay with a missing .views path refuses with the file diagnostic, u0 sentinels intact") + +print("native_global_srv_heap_replay: all checks passed") diff --git a/tools/startup/compile_dxil.cpp b/tools/startup/compile_dxil.cpp index 7f401b7002..1a2089f0db 100644 --- a/tools/startup/compile_dxil.cpp +++ b/tools/startup/compile_dxil.cpp @@ -5,6 +5,7 @@ #include "gfx1013_vertex_id.h" #include "gfx1013_compute_clear.h" #include "gfx1013_compute_native.h" +#include "startup_stubs/native_global_srv.h" #include #include #include @@ -48,6 +49,36 @@ static void compile_source(x2w::ShaderDxilCompiler& compiler,const std::string& } } +// The view metadata captured with a compute request (req_.views), read before the program is translated. Absent: +// the request has no captured selection and a GPU-selected heap read is refused. Present: every refusal below happens +// before any output is published. +struct CapturedViews { + x2w::HeapViewContract contract = x2w::HeapViewContract::none; + x2w_startup::GlobalSrvRequest request; + bool present = false; +}; + +static CapturedViews read_captured_views(const fs::path& request_path) { + CapturedViews views; + const auto path = fs::path(request_path).replace_extension(L".views"); + std::ifstream file(path, std::ios::binary); + if (!file) return views; + std::string text((std::istreambuf_iterator(file)), {}); + if (file.bad()) throw std::runtime_error("global SRV view metadata read failed"); + std::string error; + if (!x2w_startup::decode_global_srv_request(text, views.request, error)) throw std::runtime_error(error); + views.present = true; + const auto& request = views.request; + auto refusal = x2w_startup::refuse_global_srv_selection(request.views, request.selected, request.needed); + if (!refusal.empty()) throw std::runtime_error(refusal); + if (request.needed != x2w_startup::GlobalSrvType::raw_buffer) + throw std::runtime_error(std::string("GPU-selected heap slot view type ") + + x2w_startup::global_srv_type_name(request.needed) + + " is not raw_buffer; only raw buffer heap reads are translated"); + views.contract = x2w::HeapViewContract::raw_buffer; + return views; +} + static void compile_one(x2w::ShaderDxilCompiler& compiler, std::wstring profile, const fs::path& input_path, const fs::path& destination, const fs::path& cache, std::ostream& report,const x2w::NativeComputeShader *linked=nullptr) { Clock::time_point start; @@ -64,7 +95,9 @@ static void compile_one(x2w::ShaderDxilCompiler& compiler, std::wstring profile, start=Clock::now(); const auto entry=static_cast(std::stoul(offset)); bool frontend_hit=false; - auto program=direct?x2w::prepare_direct_compute(input_path,entry,container,cache,frontend_hit) + CapturedViews views; + if(container)views=read_captured_views(input_path); + auto program=direct?x2w::prepare_direct_compute(input_path,entry,container,cache,frontend_hit,views.contract) :x2w::translate_compute(x2w::read_compute_request(input_path),entry,false); report<<"frontend=native_cpp instructions="<.c67.\n" "Direct DXIL profiles: gfx1013-direct-cs@BYTE_OFFSET, gfx1013-container-cs, gfx1013-container-vs, gfx1013-container-ps.\n" + "gfx1013-container-cs reads an optional req_.views next to the .cdx (GPU-selected heap slot view types).\n" "gfx1013-container-pair accepts two containers and emits VS then PS using the runtime register allocation.\n" "For capture directories use PROFILE --requests DIRECTORY OUTPUT_DIRECTORY. " "gfx1013-container-rect also emits the rectangle geometry stage.\n" @@ -230,7 +273,7 @@ int wmain(int argc, wchar_t** argv) { std::set occupied(inputs.begin(),inputs.end()); if(compute_request) { for(const auto& input : inputs) { - for(auto suffix : {L".root",L".data",L".sa",L".sb",L".desc"}) + for(auto suffix : {L".root",L".data",L".sa",L".sb",L".desc",L".views"}) occupied.insert(fs::weakly_canonical(fs::path(input).replace_extension(suffix))); } }