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/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/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/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 diff --git a/tests/native_heap_handle_probe.cpp b/tests/native_heap_handle_probe.cpp new file mode 100644 index 0000000000..3f358505a0 --- /dev/null +++ b/tests/native_heap_handle_probe.cpp @@ -0,0 +1,285 @@ +// 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"); + m.body << " ret void\n"; + 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; + } + + // 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; + 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..eb9fa22c1a --- /dev/null +++ b/tests/native_heap_handle_probe_check.py @@ -0,0 +1,58 @@ +"""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 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}" + assert "native_heap_handle_probe: PASS" in result.stdout + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:4]))