diff --git a/docs/experiments/native-sampler-heap.md b/docs/experiments/native-sampler-heap.md index 420bb043c0..12963b2a60 100644 --- a/docs/experiments/native-sampler-heap.md +++ b/docs/experiments/native-sampler-heap.md @@ -4,7 +4,8 @@ Issue #3076, part of #2935 (related #1143). The native compute translator now ac the sampler heap with `s_load_dwordx4` / `s_load_dwordx8` at a constant 16-byte aligned offset and uses with `image_sample_l` or `image_sample_lz`. It lowers the sampler to `SamplerDescriptorHeap[index]` in the DXIL module. This is stage 1: the translator, the binding record, the cache, the root signature and `bind()`. Binding a real, mirrored sampler heap -at dispatch time in the runtime is stage 2 and is not part of this change. +at dispatch time in the runtime is stage 2: the published-manifest route is stage 2a (section "Stage 2a" below); the in-process +route is not done. ## Why @@ -44,9 +45,9 @@ requests stop first at such a load (117 `dwordx4`, 13 `dwordx8`). The change rem does for `SamplerDescriptorHeap[i]` (DXC reference: flags `0x80000010` with raw buffers). - Binding record: `ComputeViewKind::heap_sampler`, one per program, `{heap_sampler, compute_sampler_heap, byte_offset 0, register 0, required_bytes 16 * (highest index + 1)}`. The frontend cache accepts the kind with exactly that root value; an - older decoder rejects it and recomputes. `format_compute_runtime_manifest` returns no manifest for it (root parameter above - 15), so `compile_dxil --requests` publishes `.cs.cso` without `.txt`; the in-process dispatch route refuses the - kind. `compile_dxil` reports `sampler_heap span=`. + older decoder rejects it and recomputes. Stage 1 published no manifest for it (root parameter above 15); stage 2a (below) + publishes `smpidx `. The in-process dispatch route (`translate_compute_natively`) still refuses the kind. + `compile_dxil` reports `sampler_heap span=`. - `create_native_compute_pipeline`: `sampler_heap_indexed` adds root flag `0x800` (`SAMPLER_HEAP_DIRECTLY_INDEXED`) and does not set `heap_indexed` or `0x400`. `NativeComputePipeline::bind` has a last parameter `ID3D12DescriptorHeap *sampler_heap`: with `sampler_heap_indexed` a null heap throws ("a sampler heap is needed"); with views too, the heaps are set as views first, then @@ -61,8 +62,58 @@ requests stop first at such a load (117 `dwordx4`, 13 `dwordx8`). The change rem The runtime must fill the sampler heap bound for a natively translated compute dispatch so that entry `n` is title byte offset `16 * n` (index parity), with `dynamic_sampler()` decoding (`src/startup_stubs/translated_sampler_bindings.h`: MIN_LOD and MAX_LOD applied, which is why only the explicit-LOD forms are translated), and entry 2047 (`translated_sampler_fallback`) holding the -fallback sampler. The translator refuses index 2047, so the fallback is never read. None of this is implemented here; the fixture -builds its heap with `dynamic_sampler()` and the index parity itself. +fallback sampler. The translator refuses index 2047, so the fallback is never read. The stage 1 fixture builds its heap with +`dynamic_sampler()` and the index parity itself; stage 2a below does it in the runtime. + +## Stage 2a: the title's sampler heap for a published manifest (#3076) + +Scope: the published-manifest route only (`compile_dxil --requests` writes `.txt`, `load_compute_translation` reads it, the +stand-in's `Dispatch` path binds). The in-process route `translate_compute_natively` keeps refusing the heap sampler (stage 2b, +after #3154), and `dynamic_sampler`, `create_sampler_snapshot_heap` and `decode_statics` are untouched (#3199). + +- Manifest writer (`format_compute_runtime_manifest`, `src/direct_compute_cache.cpp`): the one `heap_sampler` binding leaves the + SRV/UAV bookkeeping (it has shader register 0 and no table) and is written as `smpidx `, `bytes` being the binding's span, + after the `smp`/`smpl` lines and before `native `. It is published only for exactly one binding with root + `compute_sampler_heap`, register 0, array count 1 and a span of 16 to `16 * 2047` bytes in whole entries (2047 is the fallback + entry that the translator never reads). Any other shape keeps the one reason that every sampler heap had before, `sampler heap`, + and publishes nothing (so `triage_run.py`'s fixed reasons and `native_compute_manifest_reasons` are unchanged). Static samplers + and `smpidx` may coexist. +- Manifest reader (`load_compute_translation`): `smpidx ` is accepted once; zero, a span that is not a multiple of 16, a span + above `16 * 2047` or a second line is refused as "a sampler heap span that is not 16-byte entries below the fallback" (a line with + trailing text is "a sampler that is not a plain static one", as before). The graphics-style `smpheap` table is still refused + ("a sampler from the sampler heap"). +- Root signature (`create_translated_root`, new trailing parameter `extra_flags`): a translation with `smpidx` creates its root with + `D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED` (serialized as version 1.0, which takes the flag on the RTX 3080); + graphics callers are unchanged. A root that fails to serialize is refused with "root signature creation failed". A root that + serializes with the flag and is then refused by `CreateRootSignature` is refused with "the device does not take a directly + indexed sampler heap" only when the adapter reports shader model below 6.6 or resource binding tier below 3 (an inference + from the reported capabilities, not proof of the driver's reason), and with "root signature creation failed" otherwise; + a pipeline failure keeps "pipeline creation failed" with the adapter capability added. +- Dispatch (`record_translated_dispatch`), after the views are resolved and before a descriptor is taken: refused with + "no sampler heap is set on the list" when the list has no title sampler heap (neither the title-memory address nor the wrapper); + the heap is the draw path's snapshot of the title heap (`prepare_draw_sampler_heap`, keeping the list's existing fallback + setting so draws and dispatches on one list do not rebuild it), refused with "the sampler heap could not be created" when it cannot be + made, with "the sampler heap has no readable entries" when the snapshot is empty (a wrapper without a readable shadow heap), + and with "the sampler heap is smaller than the program reads" when the snapshot holds fewer entries than the span. The + sampler heap is then set with the view heap before the root signature, and again when another snapshot heap replaces it. A + program without `smpidx` leaves whatever sampler heap is bound, as before. Every refusal counts as a bind refusal. +- Limits kept from the draw path: an unreadable entry or an unresolvable `X2WV` token becomes the border sampler (counted in the + `x2w-draw sampler heap:` log line), and entries are decoded by `dynamic_sampler()`. + +Tests: `native_compute_manifest_sampler_heap` (CPU: exact text, the heap binding first, between and last next to a stride source, +static samplers, and the one-reason refusals), `native_sampler_heap_hardware` (the published manifests of SAMPLE, TWO and MIXED are +exact; they were absent before), and `startup_compute_dispatch_sampler_heap_{warp,hardware}` +(`tests/startup_compute_sampler_heap_check.py`, consumer mode `sampler-heap`; `SKIP_RETURN_CODE 77`). The GPU test publishes +the SAMPLE program with `compile_dxil --requests`, runs six reader refusals (they come before the pipeline is created, so WARP +runs them too, then exits 77: no 32-lane waves), runs the dispatch on a 128-entry title heap (entry 67 wrap/point, decoys elsewhere) +and compares all 32 lanes with a CPU model, puts each of four decoys in slot 67 (the output must change and equal the decoy's +model where it is a point sampler), and checks the controls: view heap only ("no sampler heap is set on the list"), 67 entries +("the sampler heap is smaller than the program reads"), exactly 68 entries (runs), a manifest span of 1104 on 68 entries (refused), +and the manifest without `smpidx` ("pipeline creation failed": the root then lacks the flag). + +Not done: the in-process route; title heaps on the wrapper-only path (no title memory; `prepare_draw_sampler_heap` serves both, +only the title-memory path is exercised by the GPU test); `ExecuteIndirect` dispatches (the code path is shared, no test); +containers; GPU-selected sampler indices. ## Fixture @@ -120,7 +171,8 @@ skips: the four WARP tests that already skipped and the new one). ## Limits -- Stage 1 only: no runtime binding of a mirrored sampler heap for natively translated compute dispatch. +- Stage 1 binds no sampler heap at dispatch time; stage 2a binds the title's heap for the published-manifest route only (the + in-process route is not done). - GPU-selected sampler indices (SGPR offset), comparison, gather and gradient sampling through the heap, and containers are refused. - The fixture samples with point filters and compares exact texels; decoys are checked to change the result (and to run: diff --git a/src/direct_compute_cache.cpp b/src/direct_compute_cache.cpp index ab7ff78833..c7f03fa8be 100644 --- a/src/direct_compute_cache.cpp +++ b/src/direct_compute_cache.cpp @@ -941,6 +941,22 @@ std::optional format_compute_runtime_manifest(const NativeComputeSh return refuse("more than 32 user data words"); auto sorted = program.bindings; + // The directly indexed sampler heap (#3076) is no SRV or UAV register and has no table: its one binding leaves the + // view bookkeeping below and becomes the line `smpidx `, the span the program reads (16 bytes per title entry, + // whole entries below the fallback entry 2047 that the translator never reads). A binding the runtime cannot bind + // keeps the reason this function always gave for the sampler heap. + unsigned sampler_heap_bytes = 0; + for (auto at = sorted.begin(); at != sorted.end();) { + if (at->kind != ComputeViewKind::heap_sampler) { + ++at; + continue; + } + if (sampler_heap_bytes || at->root_parameter != compute_sampler_heap || at->shader_register != 0 || + at->array_count != 1 || !at->required_bytes || at->required_bytes % 16 || at->required_bytes > 16 * 2047) + return refuse("sampler heap"); + sampler_heap_bytes = at->required_bytes; + at = sorted.erase(at); + } std::sort(sorted.begin(), sorted.end(), [](const auto &a, const auto &b) { const bool ua = compute_uav(a.kind), ub = compute_uav(b.kind); if (ua != ub) @@ -1069,8 +1085,10 @@ std::optional format_compute_runtime_manifest(const NativeComputeSh return refuse("stride words from a view that is not one raw vector SRV"); out << "udsrc " << ud_index++ << " stride " << srv << '\n'; } - out << srv_lines.str() << uav_lines.str() << sampler_lines.str() - << "native " << native_compute_output_revision << '\n'; + out << srv_lines.str() << uav_lines.str() << sampler_lines.str(); + if (sampler_heap_bytes) + out << "smpidx " << sampler_heap_bytes << '\n'; + out << "native " << native_compute_output_revision << '\n'; return out.str(); } diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 3a5bea91e5..930a3a6009 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -58,6 +58,7 @@ struct ComputeTranslation { x2w_startup::ManifestRetry manifest_retry; // absent and stale manifests can become ready later std::vector uds, srvs, uavs; UINT heap_srvs = 0; + UINT sampler_heap_bytes = 0; // `smpidx`: the program reads the title's sampler heap (directly indexed) up to this byte x2w_startup::TranslatedSamplers samplers; // static ones only x2w_startup::ComPtr root; x2w_startup::ComPtr pipeline; @@ -251,6 +252,16 @@ bool adapter_reports_shader_model_below_6_6() model.HighestShaderModel < D3D_SHADER_MODEL_6_6; } +// The directly indexed sampler heap needs shader model 6.6 and resource binding tier 3 (tests/native_sampler_heap.cpp). +// A query that fails does not count as lacking: the capability text is only given on a reported shortfall. +bool adapter_lacks_directly_indexed_sampler_heap() +{ + D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; + return adapter_reports_shader_model_below_6_6() || + (SUCCEEDED(device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options))) && + options.ResourceBindingTier < D3D12_RESOURCE_BINDING_TIER_3); +} + // The root signature and pipeline of a translation whose entry values and views are filled in. Returns why it is // unavailable, or null when it is ready. const char* create_compute_pipeline(ComputeTranslation& tr, const void* code, std::size_t bytes) @@ -260,15 +271,20 @@ const char* create_compute_pipeline(ComputeTranslation& tr, const void* code, st std::vector atomic_registers; for (UINT i = 0; i < tr.uavs.size(); ++i) if (tr.uavs[i].atomic) atomic_registers.push_back(i); + bool serialized = false; if (FAILED(x2w_startup::create_translated_root(device_of(the_device), static_cast(tr.uds.empty() ? 1 : tr.uds.size()), static_cast(tr.srvs.size()), tr.samplers, &tr.root, static_cast(tr.uavs.size()), false, tr.heap_srvs, - static_cast(atomic_registers.size()), atomic_registers.data()))) - return "root signature creation failed"; + static_cast(atomic_registers.size()), atomic_registers.data(), + tr.sampler_heap_bytes ? D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED : D3D12_ROOT_SIGNATURE_FLAG_NONE, + &serialized))) + return x2w_startup::compute_root_refusal(tr.sampler_heap_bytes != 0, serialized, + tr.sampler_heap_bytes != 0 && serialized && + adapter_lacks_directly_indexed_sampler_heap()); D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; desc.pRootSignature = tr.root.Get(); desc.CS = {code, bytes}; if (FAILED(device_of(the_device)->CreateComputePipelineState(&desc, IID_PPV_ARGS(&tr.pipeline)))) - return "pipeline creation failed"; + return "pipeline creation failed"; // exact text: the caller adds the adapter capability to it tr.state = 1; return nullptr; } @@ -425,6 +441,14 @@ const char* load_compute_translation(ComputeTranslation& tr) return "a resource heap range outside the supported layout"; tr.heap_srvs = x; } + // The directly indexed sampler heap (#3076): the span in bytes the program reads, whole 16-byte title entries + // below the fallback entry (2047) that the translator never reads. Accepted once. + else if (std::sscanf(line.c_str(), "smpidx %u%n", &x, &used) == 1 && whole()) { + if (tr.sampler_heap_bytes || !x || x % x2w_startup::title_sampler_stride || + x > x2w_startup::title_sampler_stride * x2w_startup::translated_sampler_fallback) + return "a sampler heap span that is not 16-byte entries below the fallback"; + tr.sampler_heap_bytes = x; + } // A static sampler, decoded as the draw path does: plain (smp), with the descriptor's LOD clamp (smpl) or a // comparison one (smpc). Not modelled here: the run-time sampler heap table (smpheap). else if (line.rfind("smpheap", 0) == 0) return "a sampler from the sampler heap"; @@ -1286,6 +1310,21 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& reason = "an input texture could not be uploaded"; std::memset(words, 0, sizeof(words)); } + // A program that reads the directly indexed sampler heap (#3076) runs with the sampler heap the title set on the + // list, entry n at title byte 16 * n. Each refusal here comes before the view descriptors are taken. The heap is the + // draw path's snapshot (an unreadable entry or an unresolvable token is its border sampler, counted in the + // "x2w-draw sampler heap" line); entry 2047 is never read by the program, so a snapshot with or without the reserved + // fallback serves, and the list's existing one is kept to avoid rebuilding the heap between draws and dispatches. + if (!reason && tr->sampler_heap_bytes) { + if (!pass.title_samplers.address && !pass.sampler_heap_wrapper) + reason = "no sampler heap is set on the list"; + else if (!prepare_draw_sampler_heap(self, pass, list, pass.sampler_snapshot ? pass.sampler_snapshot->reserved_fallback : true)) + reason = "the sampler heap could not be created"; + else if (!pass.sampler_snapshot->count) // a wrapper without a readable shadow heap gives no entries + reason = "the sampler heap has no readable entries"; + else if (u64{pass.sampler_snapshot->count} * x2w_startup::title_sampler_stride < tr->sampler_heap_bytes) + reason = "the sampler heap is smaller than the program reads"; + } if (reason) { if (!tr->first_refusal) { tr->first_refusal = reason; @@ -1340,10 +1379,13 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; device_of(the_device)->CreateUnorderedAccessView(view.resource, nullptr, &desc, dest); } - if (!pass.heap_set) { - x2w_startup::bind_translated_heaps(list, draw_heap, nullptr); + // A directly indexed root needs its sampler heap set before the root signature; another program keeps whatever + // sampler heap is bound. + ID3D12DescriptorHeap* const samplers = tr->sampler_heap_bytes ? pass.sampler_heap.Get() : nullptr; + if (!pass.heap_set || (samplers && pass.bound_sampler_heap != samplers)) { + x2w_startup::bind_translated_heaps(list, draw_heap, samplers); pass.heap_set = true; - pass.bound_sampler_heap = nullptr; + pass.bound_sampler_heap = samplers; } list->SetPipelineState(tr->pipeline.Get()); list->SetComputeRootSignature(tr->root.Get()); diff --git a/src/startup_stubs/translated_sampler_bindings.h b/src/startup_stubs/translated_sampler_bindings.h index 255765fbb3..66df064f68 100644 --- a/src/startup_stubs/translated_sampler_bindings.h +++ b/src/startup_stubs/translated_sampler_bindings.h @@ -121,11 +121,16 @@ inline UINT sampler_root_parameter(UINT views) { return views ? 2u : 1u; } // `atomic` names the UAV registers (one per indexed atomic UAV, in UAV order) that each get a 32-bit-constants // parameter after the view table: the translated program reads the view's {stride, count} from b(register + 1), // as NativeComputePipeline binds it. The sampler-heap table, when present, follows those parameters. +// extra_flags are root signature flags added to the root's own (a compute program that reads the directly indexed sampler +// heap takes SAMPLER_HEAP_DIRECTLY_INDEXED). inline HRESULT create_translated_root(ID3D12Device* device, UINT constants, UINT srvs, const TranslatedSamplers& samplers, ID3D12RootSignature** out, UINT uavs = 0, bool input_assembler = false, UINT heap_srvs = 0, UINT atomic = 0, - const UINT *atomic_registers = nullptr) + const UINT *atomic_registers = nullptr, + D3D12_ROOT_SIGNATURE_FLAGS extra_flags = D3D12_ROOT_SIGNATURE_FLAG_NONE, + bool* serialized = nullptr) { + if (serialized) *serialized = false; D3D12_ROOT_PARAMETER parameters[11]{}; parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; parameters[0].Constants.Num32BitValues = constants; @@ -157,14 +162,31 @@ inline HRESULT create_translated_root(ID3D12Device* device, UINT constants, UINT } const auto statics = decode_statics(samplers); const D3D12_ROOT_SIGNATURE_DESC desc{count, parameters, static_cast(statics.size()), statics.data(), - input_assembler ? D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT - : D3D12_ROOT_SIGNATURE_FLAG_NONE}; + static_cast( + (input_assembler ? D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT + : D3D12_ROOT_SIGNATURE_FLAG_NONE) | extra_flags)}; ComPtr blob; HRESULT hr = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &blob, nullptr); - if (SUCCEEDED(hr)) hr = device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(out)); + if (SUCCEEDED(hr)) { + if (serialized) *serialized = true; // from here on a failure is the device's, not the root's description + hr = device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(out)); + } return hr; } +// Why a compute root that failed to create is unavailable. A serialization failure (parameter count, static samplers, +// the root's own description) is always "root signature creation failed". The capability text is given only when the +// device refused a root that serialized and takes SAMPLER_HEAP_DIRECTLY_INDEXED, on an adapter that lacks what the +// flag needs (shader model 6.6 and resource binding tier 3, as tests/native_sampler_heap.cpp requires). That is an +// inference from the adapter's reported capabilities, not proof of the driver's reason: CreateRootSignature gives no +// finer cause. Both texts are fixed triage reasons. +inline const char* compute_root_refusal(bool directly_indexed_sampler_heap, bool serialized, bool adapter_lacks_capability) +{ + return directly_indexed_sampler_heap && serialized && adapter_lacks_capability + ? "the device does not take a directly indexed sampler heap" + : "root signature creation failed"; +} + struct SamplerSource { std::uintptr_t address = 0; UINT count = 0; diff --git a/tests/cmake/native_sampler_heap.cmake b/tests/cmake/native_sampler_heap.cmake index 7f17283419..91acd7a51c 100644 --- a/tests/cmake/native_sampler_heap.cmake +++ b/tests/cmake/native_sampler_heap.cmake @@ -13,3 +13,12 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ set_tests_properties(native_sampler_heap_${adapter} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 180) endforeach() endif() + +# The runtime manifest of such a program (#3076 stage 2a): the heap binding becomes one `smpidx ` line. CPU only. +if(TARGET x2w_shader_compiler) + add_executable(native_compute_manifest_check tests/native_compute_manifest_check.cpp) + target_include_directories(native_compute_manifest_check PRIVATE src) + target_link_libraries(native_compute_manifest_check PRIVATE x2w_shader_compiler) + set_property(TARGET native_compute_manifest_check PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + add_test(NAME native_compute_manifest_sampler_heap COMMAND native_compute_manifest_check) +endif() diff --git a/tests/cmake/startup_compute_sampler_heap.cmake b/tests/cmake/startup_compute_sampler_heap.cmake new file mode 100644 index 0000000000..fca83531d0 --- /dev/null +++ b/tests/cmake/startup_compute_sampler_heap.cmake @@ -0,0 +1,12 @@ +# A native compute program that reads the directly indexed sampler heap runs with the title's sampler heap (#3076, +# stage 2a): the stand-in's Dispatch path against a published manifest with an `smpidx` line. The _warp test runs the +# reader refusals and exits 77 (WARP has no 32-lane waves); the _hardware test runs the dispatch and its controls. +if(TARGET startup_stream_consumer AND TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}" + AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll" AND EXISTS "${DXC_BIN_DIR}/dxc.exe") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_dispatch_sampler_heap_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_sampler_heap_check.py" "$" + "$" "${DXC_BIN_DIR}" ${adapter}) + set_tests_properties(startup_compute_dispatch_sampler_heap_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/native_compute_manifest_check.cpp b/tests/native_compute_manifest_check.cpp new file mode 100644 index 0000000000..8e1026736e --- /dev/null +++ b/tests/native_compute_manifest_check.cpp @@ -0,0 +1,152 @@ +// The runtime manifest of a compute program that reads the directly indexed sampler heap (#3076): the heap binding is no +// view register, it becomes one `smpidx ` line after the static samplers, wherever it sits in the binding list. +// A heap binding the runtime cannot bind keeps the one reason "sampler heap" and publishes nothing. +#include "direct_compute_cache.h" +#include "native_compute_output.h" + +#include +#include +#include + +using namespace x2w; +using K = ComputeViewKind; + +static int failures = 0; + +static ComputeViewBinding view(K kind, unsigned reg, unsigned root, unsigned offset, unsigned bytes = 0) { + ComputeViewBinding b{}; + b.kind = kind; + b.root_parameter = root; + b.byte_offset = offset; + b.shader_register = reg; + b.required_bytes = bytes; + return b; +} + +static ComputeViewBinding heap_binding(unsigned bytes) { + return view(K::heap_sampler, 0, compute_sampler_heap, 0, bytes); +} + +// The shape of the sampler heap fixtures: a 2D texture at table byte 0, an output buffer at byte 32, one thread group. +static NativeComputeShader program(std::vector bindings) { + NativeComputeShader p{}; + p.group = {32, 1, 1}; + p.bindings = std::move(bindings); + return p; +} + +static ComputeViewBinding texture() { + auto b = view(K::texture_srv, 0, 0, 0); + b.image_dimension = 1; + return b; +} +static ComputeViewBinding output() { return view(K::raw_buffer_uav, 0, 0, 32); } + +static std::string revision_line() { return "native " + std::to_string(native_compute_output_revision) + "\n"; } + +static void expect_text(const char *what, const NativeComputeShader &p, const std::string &wanted) { + std::string reason = "unset"; + const auto manifest = format_compute_runtime_manifest(p, &reason); + const bool ok = manifest && *manifest == wanted && reason == "unset"; + std::printf("%s %s\n", ok ? "ok " : "FAIL", what); + if (!ok) + std::printf(" wanted: %s\n got: %s\n", wanted.c_str(), manifest ? manifest->c_str() : reason.c_str()); + failures += !ok; +} + +static void expect_refused(const char *what, const NativeComputeShader &p, const char *reason_wanted) { + std::string reason = "unset"; + const auto manifest = format_compute_runtime_manifest(p, &reason); + const bool ok = !manifest && reason == reason_wanted; + std::printf("%s %s -> \"%s\"\n", ok ? "ok " : "FAIL", what, reason_wanted); + if (!ok) + std::printf(" got: %s\n", manifest ? manifest->c_str() : reason.c_str()); + failures += !ok; +} + +int main() { + const std::string head = "x2w-manifest 2\nstage cs\ngroup 32 1 1\nud 0\n"; + const std::string views = "srv 0 tex2d table 0 0\nuav 0 table 0 32\n"; + const std::string tail = revision_line(); + + // The span is the binding's required bytes: 16 * (highest entry + 1). + expect_text("one heap sampler, entry 67 (1088 bytes)", program({texture(), output(), heap_binding(1088)}), + head + views + "smpidx 1088\n" + tail); + expect_text("entries 67 and 68 (1104 bytes)", program({texture(), output(), heap_binding(1104)}), + head + views + "smpidx 1104\n" + tail); + // Control: without the binding there is no line (a program that reads no heap is unchanged). + expect_text("no heap sampler binding, no smpidx line", program({texture(), output()}), head + views + tail); + // Control: another span gives another number (the line is not a constant). + expect_text("the lowest span, entry 0 (16 bytes)", program({texture(), output(), heap_binding(16)}), + head + views + "smpidx 16\n" + tail); + expect_text("the highest span, entry 2046 (32752 bytes)", program({texture(), output(), heap_binding(16 * 2047)}), + head + views + "smpidx 32752\n" + tail); + + // The heap binding has shader register 0 and no table: it must not tie with t0 or u0 whatever its place is. + const std::string wanted = head + views + "smpidx 1088\n" + tail; + expect_text("heap binding first", program({heap_binding(1088), texture(), output()}), wanted); + expect_text("heap binding between the views", program({texture(), heap_binding(1088), output()}), wanted); + expect_text("heap binding last", program({texture(), output(), heap_binding(1088)}), wanted); + + // Static samplers come first, in the order the runtime numbers them, then the heap line. + { + auto p = program({heap_binding(1088), texture(), output()}); + p.samplers.push_back({{0x92, 0, 0, 0}, false}); + p.samplers.push_back({{0x92, 0xfff000, 0, 0}, true}); + expect_text("static samplers then smpidx", p, + head + views + "smp 0 00000092 00000000 00000000 00000000\n" + "smpl 1 00000092 00fff000 00000000 00000000\n" + "smpidx 1088\n" + tail); + } + + // A stride source indexes the SRVs after the heap binding left the list: SRV 0 stays the raw vector SRV, whatever + // the place of the heap binding. + { + for (int place = 0; place < 3; ++place) { + std::vector bindings{view(K::raw_vector_srv, 0, 0, 0), output()}; + bindings.insert(bindings.begin() + place, heap_binding(1088)); + auto p = program(std::move(bindings)); + p.constants.push_back({0, 0, 2}); + p.stride_srvs = {0}; + expect_text(place == 0 ? "stride source, heap binding first" + : place == 1 ? "stride source, heap binding between" : "stride source, heap binding last", p, + "x2w-manifest 2\nstage cs\ngroup 32 1 1\nud 3\nudsrc 0 rootconst 0 0\nudsrc 1 rootconst 0 1\n" + "udsrc 2 stride 0\nsrv 0 buf table 0 0\nuav 0 table 0 32\nsmpidx 1088\n" + tail); + } + } + + // A heap binding the runtime cannot bind is refused with the reason of every sampler heap before this change. + expect_refused("two heap sampler bindings", program({texture(), output(), heap_binding(1088), heap_binding(1104)}), + "sampler heap"); + { + auto b = heap_binding(1088); + b.root_parameter = 0; // a table parameter, not the sampler heap + expect_refused("heap sampler with a table root parameter", program({texture(), output(), b}), "sampler heap"); + b.root_parameter = compute_resource_heap; + expect_refused("heap sampler with the resource heap root", program({texture(), output(), b}), "sampler heap"); + } + expect_refused("span 0", program({texture(), output(), heap_binding(0)}), "sampler heap"); + expect_refused("span 8 (not whole 16-byte entries)", program({texture(), output(), heap_binding(8)}), "sampler heap"); + expect_refused("span 1090", program({texture(), output(), heap_binding(1090)}), "sampler heap"); + expect_refused("span one entry over the entries below the fallback (32768)", + program({texture(), output(), heap_binding(16 * 2047 + 16)}), "sampler heap"); + expect_refused("span 65536", program({texture(), output(), heap_binding(65536)}), "sampler heap"); + { + auto b = heap_binding(1088); + b.shader_register = 1; + expect_refused("heap sampler at register 1", program({texture(), output(), b}), "sampler heap"); + b = heap_binding(1088); + b.array_count = 2; + expect_refused("heap sampler with an array count", program({texture(), output(), b}), "sampler heap"); + } + // A view kind with the sampler heap root parameter is not a sampler heap binding: still refused. + expect_refused("a texture SRV on the sampler heap root", program({view(K::texture_srv, 0, compute_sampler_heap, 0), output()}), + "sampler heap"); + // The resource heap stays refused next to a valid sampler heap binding. + expect_refused("resource heap view next to a sampler heap binding", + program({texture(), output(), heap_binding(1088), view(K::heap_buffer_srv, 1, compute_resource_heap, 0)}), + "resource heap view"); + + std::printf("%d failures\n", failures); + return failures ? 1 : 0; +} diff --git a/tests/native_sampler_heap_check.py b/tests/native_sampler_heap_check.py index c135d17a89..645eae74ad 100644 --- a/tests/native_sampler_heap_check.py +++ b/tests/native_sampler_heap_check.py @@ -13,13 +13,15 @@ The `native_sampler_heap` fixture runs them with a sampler heap of decoys, compares every lane with a CPU model, puts each decoy in place of the entry under test (the result must change), checks the frontend cache round trip and the binding record, and shows that bind() without a sampler heap throws. This script also compiles the refusal shapes and checks each -refusal text (and that no .cso is written), each with a control that compiles. Exit 77 when the fixture reports a +refusal text (and that no .cso is written), each with a control that compiles, and compares the runtime manifest that +`--requests` publishes (an `smpidx` line, #3076 stage 2a). Exit 77 when the fixture reports a capability skip (WARP has no 32-lane waves). Instruction words were assembled once with LLVM 15 (clang -cc1as -triple amdgcn-amd-amdhsa -target-cpu gfx1013 -filetype asm -show-encoding); the comment on each line is the assembler source. The test needs no LLVM. """ import pathlib +import re import struct import subprocess import sys @@ -339,13 +341,23 @@ def accepted(name, message): "createHandleFromHeap(i32 218, i32 67, i1 true, i1 false)" in listing and "createHandleFromHeap(i32 218, i32 68, i1 true, i1 false)" in listing, "TWO: one s_load_dwordx8 gives sampler heap handles 67 and 68") - marker = request("sample") - requests = marker.parent - out_dir = base / "requests_out" - code, out, err = run([compile_dxil, sdk, base / "cache_requests", "gfx1013-direct-cs@0", "--requests", requests, out_dir]) - stem = marker.stem[len("req_"):] - require(code == 0 and (out_dir / (stem + ".cs.cso")).exists() and not (out_dir / (stem + ".txt")).exists(), - "--requests publishes .cs.cso and no runtime manifest (.txt) for a sampler heap program") + # --requests publishes the runtime manifest too: the heap binding is the `smpidx ` line (#3076 stage 2a), + # after the static samplers and before the `native ` line. startup_compute_sampler_heap_check.py runs it. + views = "x2w-manifest 2\nstage cs\ngroup 32 1 1\nud 0\nsrv 0 tex2d table 0 0\nuav 0 table 0 32\n" + static = "smpl 0 00000092 00000000 00000000 00000000\n" + for name, wanted in (("sample", views + "smpidx 1088\n"), ("two", views + "smpidx 1104\n"), + ("mixed", views + static + "smpidx 1088\n")): + marker = request(name) + out_dir = base / f"requests_out_{name}" + code, out, err = run([compile_dxil, sdk, base / f"cache_requests_{name}", "gfx1013-direct-cs@0", "--requests", + marker.parent, out_dir]) + stem = marker.stem[len("req_"):] + published = out_dir / (stem + ".txt") + require(code == 0 and (out_dir / (stem + ".cs.cso")).exists() and published.exists(), + f"--requests publishes .cs.cso and a runtime manifest (.txt) for {name}") + text = published.read_text() + require(text.startswith(wanted) and re.fullmatch(r"native [0-9]+\n", text[len(wanted):]), + f"{name}: the manifest is exactly the views, the static samplers and the smpidx line ({wanted.splitlines()[-1]})") # 3. Refusals, each with its text, and controls that compile. refused("off438", "align") diff --git a/tests/startup_compute_sampler_heap_check.py b/tests/startup_compute_sampler_heap_check.py new file mode 100644 index 0000000000..09ddbe7d92 --- /dev/null +++ b/tests/startup_compute_sampler_heap_check.py @@ -0,0 +1,226 @@ +"""A native compute program that reads the directly indexed sampler heap runs with the title's sampler heap (#3076, stage 2a). + +usage: startup_compute_sampler_heap_check.py + +The program is SAMPLE of native_sampler_heap_check.py: it loads the sampler at heap byte 0x430 (entry 67) and samples a +4x4 RGBA32F texture at (1.375, -0.375), outside [0, 1]; one thread group of 32 lanes stores one float4 per lane. The +stand-in's consumer (`sampler-heap` in startup_stream_consumer.cpp) creates it as a slot 67 pipeline under the root +RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | SAMPLER_HEAP_DIRECTLY_INDEXED), DescriptorTable(SRV(t0), UAV(u0)), makes a +sampler heap of 128 title entries (the descriptor words the title writes, 16 bytes each, entry 67 a wrap/point sampler, +every other entry a decoy), sets it on the list with the view heap and records Dispatch(1, 1, 1). Steps: + +1. before translation: refused with "no translation", every output word keeps its sentinel; +2. `compile_dxil --requests` publishes .cs.cso and a .txt whose last line before `native` is `smpidx 1088`; +3. reader refusals (no GPU needed), each with its text and an untouched output: `smpidx` 0, 20, 32768, -16, twice, and + `smpidx 1088 x` (a line that is not whole); +4. the dispatch runs: all 32 lanes equal the CPU model of the wrap/point entry; +5. each decoy in slot 67 (clamp, mirror, border, a bilinear white border) gives another result, the CPU model of that + decoy where it is a point sampler, and never the sentinel: the title's entry 67 is the one that is sampled; +6. controls: the view heap alone is set -> "no sampler heap is set on the list"; a heap of 67 entries -> "the sampler heap is + smaller than the program reads"; a heap of exactly 68 entries runs; a manifest span of 1104 on 68 entries is refused; + the manifest without its `smpidx` line -> "pipeline creation failed" (the root then lacks the sampler heap flag). + +Exit 77 when the adapter has no 32-lane waves (WARP): the program is then not translated, steps 1 to 3 have run. +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +import native_sampler_heap_check as N +import startup_compute_dispatch_check as D +from startup_compute_dispatch_texture_check import clean, run +from startup_compute_request_check import DATA, prepare + +ENTRIES = 128 +ENTRY = 67 +SENTINEL = 0x69696969 +LANES = 32 +U, V = 1.375, -0.375 +WRAP, MIRROR, CLAMP, BORDER = 0, 1, 2, 6 +LAYOUT = '<%dI' % (LANES * 4) +SPAN = 16 * (ENTRY + 1) + + +def texel(x, y): + """The texture of the consumer: one distinct float4 per texel (the file the consumer copies to the GPU).""" + return (10.0 * x + 1, 10.0 * y + 2, 100.0 + x + 4 * y, 1000.0) + + +def title_sampler(address, bilinear=False, white_border=False): + """SQ_IMG_SAMP words as decode_sampler reads them: clamp modes in word 0, MAX_LOD 0, filters and a point mip filter in + word 2, border colour type in word 3 (2 = opaque white).""" + a, f = address, 1 if bilinear else 0 + return (a | a << 3 | a << 6, 0, f << 20 | f << 22 | 1 << 26, 2 << 30 if white_border else 0) + + +def model(words): + """The float4 of a point sample at (U, V) of the 4x4 texture, as native_sampler_heap.cpp computes it.""" + index = [] + for coordinate in (U, V): + i = int(coordinate * 4 // 1) + mode = words[0] & 7 + if mode == WRAP: + i %= 4 + elif mode == MIRROR: + m = i % 8 + i = m if m < 4 else 7 - m + elif mode == CLAMP: + i = max(0, min(i, 3)) + index.append(i) + if any(i < 0 or i >= 4 for i in index): + white = 1.0 if words[3] >> 30 == 2 else 0.0 + return (white,) * 4 + return texel(*index) + + +WRAP_POINT = title_sampler(WRAP) +DECOYS = [title_sampler(CLAMP), title_sampler(MIRROR), title_sampler(BORDER), title_sampler(BORDER, True, True)] +WANTED = model(WRAP_POINT) +assert WANTED == texel(1, 2), WANTED # floor(5.5) wraps to 1, floor(-1.5) = -2 wraps to 2 +assert all(model(d) != WANTED for d in DECOYS) + + +def heap_bytes(count, entry=WRAP_POINT): + words = [] + for i in range(count): + words.extend(entry if i == ENTRY else DECOYS[i % len(DECOYS)]) + return struct.pack('<%dI' % len(words), *words) + + +def lanes(got): + floats = struct.unpack('<%df' % len(got), struct.pack('<%dI' % len(got), *got)) + return [tuple(floats[4 * lane:4 * lane + 4]) for lane in range(LANES)] + + +def refusal(result): + return [line for line in D.lines(result, 'Dispatch(1, 1, 1) refused: ')] + + +def main(consumer, compile_dxil, sdk, adapter): + env = dict(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') # guest lists; debug-layer messages go to the log + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + cache, base = prepare(directory) + env = dict(base, **env) + env.pop('X2W_NATIVE_SHADERS', None) # the published route + root_source = directory / 'root.hlsl' + root_source.write_text(f'#define RS "{N.ROOT_RW}"') + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'RS', '-Fo', directory / 'compute_root', root_source], + check=True, capture_output=True) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + (directory / 'program').write_bytes(struct.pack('<%dI' % len(N.PROGRAMS['sample']), *N.PROGRAMS['sample'])) + (directory / 'data').write_bytes(DATA) + # Group 32x1x1, seven user SGPRs (s4 table, s5 resource heap, s6 sampler heap), as native_sampler_heap_check.py. + (directory / 'state').write_bytes(struct.pack('<7I', 0, 0, 0, 32 | (1 << 16), 1, 0, 7 << 1)) + (directory / 'texture').write_bytes(struct.pack('<64f', *[v for y in range(4) for x in range(4) for v in texel(x, y)])) + env['X2W_TEST_SAMPLER_TEXTURE'] = str(directory / 'texture') + env['X2W_TEST_SAMPLER_HEAP'] = str(directory / 'sampler_heap') + + def dispatch(mode, heap=None): + (directory / 'sampler_heap').write_bytes(heap_bytes(ENTRIES) if heap is None else heap) + return run(directory, consumer, env, mode, LAYOUT) + + untouched = [SENTINEL] * (LANES * 4) + + # 1. no translation yet + got, result = dispatch('sampler-heap') + print(result.stdout, end='') + assert got == untouched and len(D.lines(result, 'Dispatch(1, 1, 1) refused: no translation')) == 1, result.stderr[-3000:] + key = int(D.lines(result, 'x2w-draw compute request')[0].split()[3], 16) + + # 2. the published manifest + compiled = subprocess.run([compile_dxil, sdk, directory / 'frontend', 'gfx1013-direct-cs@0', '--requests', cache, cache], + capture_output=True, text=True) + assert compiled.returncode == 0 and 'requests=1 compiled=1 refused=0' in compiled.stdout, ( + compiled.stdout, compiled.stderr) + assert (cache / f'{key:016x}.cs.cso').read_bytes().startswith(b'DXBC') + manifest = cache / f'{key:016x}.txt' + original = manifest.read_text() + rows = original.splitlines() + assert rows[-2] == f'smpidx {SPAN}' and rows[-1].startswith('native '), original + assert sum(row.startswith('smpidx') for row in rows) == 1, original + print('published manifest:\n' + original, end='') + + # 3. reader refusals: they come before the pipeline is made, so WARP runs them too + span_text = 'a sampler heap span that is not 16-byte entries below the fallback' + line = f'smpidx {SPAN}\n' + for label, edited, reason in ( + ('span 0', original.replace(line, 'smpidx 0\n'), span_text), + ('span 20 (not whole entries)', original.replace(line, 'smpidx 20\n'), span_text), + ('span 32768 (the fallback entry)', original.replace(line, 'smpidx 32768\n'), span_text), + ('span -16', original.replace(line, 'smpidx -16\n'), span_text), + ('a second smpidx', original.replace(line, line + 'smpidx 16\n'), span_text), + ('trailing text', original.replace(line, f'smpidx {SPAN} x\n'), 'a sampler that is not a plain static one')): + assert edited != original, label + manifest.write_bytes(edited.encode()) + got, result = dispatch('sampler-heap') + refused = refusal(result) + assert got == untouched and len(refused) == 1 and refused[0].endswith('refused: ' + reason), ( + label, refused, result.stderr[-3000:]) + manifest.write_bytes(original.encode()) + + # 4. the dispatch with the published manifest + got, result = dispatch('sampler-heap') + for capability in ('adapter has no 32-lane waves', 'adapter shader model below 6.6'): + if D.lines(result, f'not translated: pipeline creation failed ({capability})'): + assert got == untouched, 'a dispatch without a pipeline wrote the output' + print(f'sampler heap: manifest and reader refusals verified; dispatch skipped ({capability})') + return 77 + assert len(D.lines(result, 'Dispatch(1, 1, 1) translated')) == 1 and not refusal(result), result.stderr[-3000:] + assert all(lane == WANTED for lane in lanes(got)), (lanes(got)[:2], WANTED, result.stderr[-3000:]) + layer = clean(result) + + # 5. a decoy in slot 67 changes the output: entry 67 of the title's heap is the one sampled + for decoy in DECOYS: + got, result = dispatch('sampler-heap', heap_bytes(ENTRIES, decoy)) + assert len(D.lines(result, 'Dispatch(1, 1, 1) translated')) == 1 and not refusal(result), result.stderr[-3000:] + seen = lanes(got) + assert all(lane == seen[0] for lane in seen) and seen[0] != WANTED and got != untouched, (decoy, seen[0]) + if (decoy[2] >> 20) & 3 == 0: # a point sampler: the CPU model is exact + assert seen[0] == model(decoy), (decoy, seen[0], model(decoy)) + clean(result) + + # 6. controls + got, result = run(directory, consumer, env, 'sampler-heap-views-only', LAYOUT) + refused = refusal(result) + assert got == untouched and len(refused) == 1 and refused[0].endswith( + 'refused: no sampler heap is set on the list'), (refused, result.stderr[-3000:]) + + got, result = dispatch('sampler-heap', heap_bytes(ENTRY)) # entries 0 to 66: one short of entry 67 + refused = refusal(result) + assert got == untouched and len(refused) == 1 and refused[0].endswith( + 'refused: the sampler heap is smaller than the program reads'), (refused, result.stderr[-3000:]) + + got, result = dispatch('sampler-heap', heap_bytes(ENTRY + 1)) # exactly 68 entries: 1088 bytes + assert len(D.lines(result, 'Dispatch(1, 1, 1) translated')) == 1 and not refusal(result), result.stderr[-3000:] + assert all(lane == WANTED for lane in lanes(got)), (lanes(got)[0], WANTED) + clean(result) + + manifest.write_bytes(original.replace(line, f'smpidx {SPAN + 16}\n').encode()) + got, result = dispatch('sampler-heap', heap_bytes(ENTRY + 1)) + refused = refusal(result) + assert got == untouched and len(refused) == 1 and refused[0].endswith( + 'refused: the sampler heap is smaller than the program reads'), (refused, result.stderr[-3000:]) + + # Without the manifest line the root has no sampler heap flag: the pipeline of the program that reads + # SamplerDescriptorHeap is not created. + manifest.write_bytes(original.replace(line, '').encode()) + got, result = dispatch('sampler-heap') + refused = refusal(result) + assert got == untouched and len(refused) == 1 and 'refused: pipeline creation failed' in refused[0], ( + refused, result.stderr[-3000:]) + manifest.write_bytes(original.encode()) + + print(f'startup_compute_sampler_heap: PASS on {adapter}: entry {ENTRY} of the title heap is sampled in all {LANES} lanes, ' + f'{len(DECOYS)} decoys change it, 6 reader refusals, 4 dispatch refusals and the 68-entry boundary; debug layer: {layer}') + return 0 + + +if __name__ == '__main__': + if len(sys.argv) != 5 or sys.argv[4] not in ('warp', 'hardware'): + sys.exit(__doc__) + sys.exit(main(*sys.argv[1:])) diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index c127eb1730..a6726369c4 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -178,6 +178,7 @@ static void* desktop_pipeline(void* device) // dispatch, dispatch-swapped, dispatch-none, dispatch-records32, dispatch-sampled, dispatch-sampled-unbound, dispatch-sampled-2x1, dispatch-sampled-depth, dispatch-heap, // dispatch-heap-outside, dispatch-heap-word*, dispatch-input-*, dispatch-output-*: one creation, then dispatch_slot67 below // texture-store and texture-array modes: one creation, then texture_slot67 below +// sampler-heap, sampler-heap-views-only: one creation, then sampler_heap_slot67 below // The unreadable cases point at a PAGE_NOACCESS page; code-past-end ends the code on the last byte before one. static void* slot67_pipeline; static void* slot67_root; @@ -1233,6 +1234,124 @@ static int texture_slot67(IDXGIAdapter* adapter, void* device, const std::string return output ? 0 : 2; } +// A compute program that reads the directly indexed sampler heap (#3076, tests/startup_compute_sampler_heap_check.py) +// through the stand-in's own list. The root is the guest's: one descriptor table at parameter 0, with flags that index +// both descriptor heaps. Table byte 0 holds the shader resource view token of a committed 4x4 R32G32B32A32_FLOAT texture +// (the floats of X2W_TEST_SAMPLER_TEXTURE, copied by CopyTextureRegion, list slot 16), byte 32 the hardware descriptor of a +// placed 128-word output buffer that aliases this process's memory. The title's sampler heap has one 16-byte entry per +// 16 bytes of X2W_TEST_SAMPLER_HEAP, descriptor words as the title writes them (a shader-visible heap with title memory, +// device slot 14). sampler-heap sets the view heap and the sampler heap (list slot 32) and records Dispatch(1, 1, 1); +// sampler-heap-views-only sets the view heap alone. The 128 output words go to X2W_TEST_DISPATCH_OUT. +static int sampler_heap_slot67(void* device, const std::string& mode) +{ + constexpr UINT words = 128, texture_bytes = 4 * 4 * 16, pitch = D3D12_TEXTURE_DATA_PITCH_ALIGNMENT; + const auto word = [](const void* value) { return reinterpret_cast(value); }; + const auto read_env = [](const char* variable, std::vector& bytes) { + char path[MAX_PATH]; + const DWORD n = GetEnvironmentVariableA(variable, path, MAX_PATH); + if (!n || n >= MAX_PATH) return false; + std::ifstream file(path, std::ios::binary); + bytes.assign(std::istreambuf_iterator(file), {}); + return !bytes.empty(); + }; + std::vector entry_bytes, floats; + if (!read_env("X2W_TEST_SAMPLER_HEAP", entry_bytes) || entry_bytes.size() % 16 || + !read_env("X2W_TEST_SAMPLER_TEXTURE", floats) || floats.size() != texture_bytes) return 2; + const UINT entries = static_cast(entry_bytes.size() / 16); + const bool views_only = mode == "sampler-heap-views-only"; + + auto* const memory = static_cast(VirtualAlloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!memory) return 70; + std::fill_n(memory, words, 0x69696969u); + const D3D12_RESOURCE_DESC output_desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, words * sizeof(UINT), 1, 1, 1, DXGI_FORMAT_UNKNOWN, + {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + void* placed = nullptr; + if (FAILED(static_cast(invoke(device, 133, word(memory), word(&output_desc), D3D12_RESOURCE_STATE_COMMON, 0, + word(&__uuidof(ID3D12Resource)), word(&placed)))) || !placed) return 71; + const UINT64 address = reinterpret_cast(memory); + const UINT output_descriptor[4] = {static_cast(address), static_cast(address >> 32) | (4u << 16), words, 0}; + + constexpr DXGI_FORMAT format = DXGI_FORMAT_R32G32B32A32_FLOAT; + const D3D12_RESOURCE_DESC texture_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 4, 4, 1, 1, format, {1, 0}}; + const D3D12_RESOURCE_DESC upload_desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, pitch * 4, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + void* const texture = make_committed(device, D3D12_HEAP_TYPE_DEFAULT, texture_desc, D3D12_RESOURCE_STATE_COMMON); + void* const upload = make_committed(device, D3D12_HEAP_TYPE_UPLOAD, upload_desc, D3D12_RESOURCE_STATE_GENERIC_READ); + void* mapped = nullptr; + if (!texture || !upload || FAILED(static_cast(invoke(upload, 8, 0, 0, word(&mapped)))) || !mapped) return 80; + for (UINT row = 0; row < 4; ++row) + std::memcpy(static_cast(mapped) + row * pitch, floats.data() + row * 64, 64); + invoke(upload, 9, 0, 0); + + // The title's sampler heap: title memory the words are written into, and a shader-visible heap of that size. + void* sampler_heap = nullptr; + if (!views_only) { + auto* const backing = static_cast( + VirtualAlloc(nullptr, entry_bytes.size(), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!backing) return 70; + std::memcpy(backing, entry_bytes.data(), entry_bytes.size()); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 address, bytes; + } sampler_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, entries, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, + reinterpret_cast(backing), entry_bytes.size()}; + if (FAILED(static_cast(invoke(device, 14, word(&sampler_desc), word(&__uuidof(ID3D12DescriptorHeap)), + word(&sampler_heap)))) || !sampler_heap) return 72; + } + + constexpr StreamWord record_bytes = 32; + const StreamWord increment = invoke(device, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + const UINT descriptor_count = 2; + // On wider heaps, a separate region holds the shader's packed 32-byte records. + const UINT table_slot = increment == record_bytes ? 0 : descriptor_count; + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, table_slot + descriptor_count, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + void *heap = nullptr, *queue = nullptr, *allocator = nullptr, *list = nullptr, *fence = nullptr; + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + const UINT list_desc[]{D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + if (FAILED(static_cast(invoke(device, 14, word(&heap_desc), word(&__uuidof(ID3D12DescriptorHeap)), word(&heap)))) || + FAILED(static_cast(invoke(device, 8, word(&queue_desc), word(&__uuidof(ID3D12CommandQueue)), word(&queue)))) || + FAILED(static_cast(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, word(&__uuidof(ID3D12CommandAllocator)), word(&allocator)))) || + FAILED(static_cast(invoke(device, 73, word(list_desc), word(allocator), 0, word(&__uuidof(ID3D12GraphicsCommandList)), word(&list)))) || + FAILED(static_cast(invoke(device, 36, 0, 0, word(&__uuidof(ID3D12Fence)), word(&fence))))) return 72; + const StreamWord cpu = invoke(heap, 9), gpu = invoke(heap, 10); + if (!cpu || !gpu || increment < record_bytes) return 73; + const StreamWord table_cpu = cpu + table_slot * increment; + D3D12_SHADER_RESOURCE_VIEW_DESC view{format, D3D12_SRV_DIMENSION_TEXTURE2D, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + view.Texture2D.MipLevels = 1; + invoke(device, 18, word(texture), word(&view), cpu); + if (table_slot) std::memcpy(reinterpret_cast(table_cpu), reinterpret_cast(cpu), record_bytes); + std::memcpy(reinterpret_cast(table_cpu + record_bytes), output_descriptor, sizeof(output_descriptor)); + + if (FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; + void* heaps[2] = {heap, sampler_heap}; + invoke(list, 32, views_only ? 1 : 2, word(heaps)); + D3D12_TEXTURE_COPY_LOCATION image{static_cast(texture), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + D3D12_TEXTURE_COPY_LOCATION source{static_cast(upload), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + source.PlacedFootprint = {0, {format, 4, 4, 1, pitch}}; + invoke(list, 16, word(&image), 0, 0, 0, word(&source), 0); + invoke(list, 25, word(slot67_pipeline)); + invoke(list, 33, word(slot67_root)); + invoke(list, 35, 0, gpu + table_slot * increment); + invoke(list, 14, 1, 1, 1); + if (FAILED(static_cast(invoke(list, 9)))) return 75; + invoke(queue, 10, 1, word(&list)); + if (FAILED(static_cast(invoke(queue, 14, word(fence), 1)))) return 76; + for (const ULONGLONG deadline = GetTickCount64() + 10000; invoke(fence, 8) < 1;) { + if (GetTickCount64() >= deadline) return 78; + Sleep(1); + } + x2w_d3d12_compute_census(); + char path[MAX_PATH]; + const DWORD n = GetEnvironmentVariableA("X2W_TEST_DISPATCH_OUT", path, MAX_PATH); + if (!n || n >= MAX_PATH) return 2; + std::ofstream output(path, std::ios::binary); + output.write(reinterpret_cast(memory), words * sizeof(UINT)); + return output ? 0 : 2; +} + static bool create_slot67(void* device, const char* code_path, const char* data_path, const char* state_path, const char* mode) { std::ifstream code_file(code_path, std::ios::binary), data_file(data_path, std::ios::binary), state_file(state_path, std::ios::binary); @@ -1370,6 +1489,8 @@ int main(int argc, char** argv) } if (argc == 9 && std::strcmp(argv[4], "slot67") == 0 && std::strncmp(argv[8], "texture", 7) == 0) return create_slot67(device, argv[5], argv[6], argv[7], argv[8]) ? texture_slot67(adapter.Get(), device, argv[8]) : 10; + if (argc == 9 && std::strcmp(argv[4], "slot67") == 0 && std::strncmp(argv[8], "sampler-heap", 12) == 0) + return create_slot67(device, argv[5], argv[6], argv[7], argv[8]) ? sampler_heap_slot67(device, argv[8]) : 10; if ((argc == 8 || argc == 9) && std::strcmp(argv[4], "slot67") == 0) return create_slot67(device, argv[5], argv[6], argv[7], argc == 9 ? argv[8] : "valid") ? 0 : 10; if (GetEnvironmentVariableW(L"X2W_TEST_TRUNCATED_ONLY", nullptr, 0)) return 0; diff --git a/tests/startup_translated_sampler_bindings_check.cpp b/tests/startup_translated_sampler_bindings_check.cpp index 5bbec00dfa..9e38abe307 100644 --- a/tests/startup_translated_sampler_bindings_check.cpp +++ b/tests/startup_translated_sampler_bindings_check.cpp @@ -337,6 +337,26 @@ int main(int argc, char** argv) other.reserved_fallback = true; if (other == first) fail("changed reserved entry", "equal", 1, 0); } + { + // A failed compute root names the missing capability only when the device refused a serialised root that takes + // the flag, on an adapter that lacks it. A serialisation failure is always the plain text. + ++cases; + const char* capability = "the device does not take a directly indexed sampler heap"; + const char* plain = "root signature creation failed"; + struct Row { const char* name; bool flag, serialized, lacks; const char* want; }; + const Row rows[] = { + {"CreateRootSignature refused, flag, lacks capability", true, true, true, capability}, + {"CreateRootSignature refused, flag, has capability", true, true, false, plain}, + {"serialisation failed, flag, lacks capability", true, false, true, plain}, + {"serialisation failed, flag, has capability", true, false, false, plain}, + {"CreateRootSignature refused, no flag, lacks capability", false, true, true, plain}, + {"CreateRootSignature refused, no flag, has capability", false, true, false, plain}, + {"serialisation failed, no flag, lacks capability", false, false, true, plain}, + {"serialisation failed, no flag, has capability", false, false, false, plain}, + }; + for (const Row& r : rows) + if (std::strcmp(compute_root_refusal(r.flag, r.serialized, r.lacks), r.want)) fail("root refusal", r.name, 0, 1); + } if (failures) { std::printf("startup_translated_sampler_bindings: %d FAILED in %d cases\n", failures, cases); diff --git a/tests/startup_triage_run_check.py b/tests/startup_triage_run_check.py index c6995933f3..c9ab0ff510 100644 --- a/tests/startup_triage_run_check.py +++ b/tests/startup_triage_run_check.py @@ -432,12 +432,14 @@ def function_body(text: str, name: str) -> str: dispatch_path = REPO_ROOT / "src" / "startup_stubs" / "d3d12_compute_dispatch.inl" draw_path = REPO_ROOT / "src" / "startup_stubs" / "d3d12_draw.inl" token_path = REPO_ROOT / "src" / "startup_stubs" / "input_view_token.h" - if not dispatch_path.exists() or not draw_path.exists() or not token_path.exists(): + root_path = REPO_ROOT / "src" / "startup_stubs" / "translated_sampler_bindings.h" + if not dispatch_path.exists() or not draw_path.exists() or not token_path.exists() or not root_path.exists(): failures.append("compute Dispatch source files not found") return found = literals(dispatch_path.read_text(encoding="utf-8")) found |= literals(function_body(draw_path.read_text(encoding="utf-8"), "indirect_table_buffer")) found |= literals(function_body(token_path.read_text(encoding="utf-8"), "input_view_token_refusal")) + found |= literals(function_body(root_path.read_text(encoding="utf-8"), "compute_root_refusal")) missing = sorted(s for s in found if s not in triage_run.COMPUTE_DISPATCH_REASONS) if missing: failures.append("source reasons missing from COMPUTE_DISPATCH_REASONS: " + ", ".join(repr(s) for s in missing)) diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py index 4ee978ed53..055cb037c4 100644 --- a/tools/startup/triage_run.py +++ b/tools/startup/triage_run.py @@ -96,6 +96,7 @@ 'a resource heap range outside the supported layout', 'a resource that is not a raw table buffer or a 1D/2D/2D-array/3D/cube texture', 'a sampler from the sampler heap', + 'a sampler heap span that is not 16-byte entries below the fallback', 'a sampler that is not a plain static one', 'a table descriptor is not bound', 'a typed input DST_SEL is not the identity', @@ -178,6 +179,7 @@ 'an output UAV covers only part of a copied placement', 'an output UAV has no supported byte interval', 'an output UAV interval crosses the end of its buffer', + 'an output UAV interval exceeds the D3D12 buffer view element limit', 'an output UAV interval is empty', 'an output UAV interval is not 16-byte aligned in its buffer', 'an output UAV interval is not whole dwords', @@ -233,6 +235,7 @@ 'native translation without a revision; rebuild it', 'no compiled program', 'no descriptor heap on this device', + 'no sampler heap is set on the list', 'no translation', 'not a compute manifest', 'pipeline creation failed', @@ -243,8 +246,12 @@ 'the adapter has no 32-lane waves', 'the adapter reports shader model below 6.6', 'the compute root set is not the one the pipeline was created with', + 'the device does not take a directly indexed sampler heap', 'the indirect argument buffer is also a bound shader resource', 'the list type has no Dispatch', + 'the sampler heap could not be created', + 'the sampler heap has no readable entries', + 'the sampler heap is smaller than the program reads', 'translated indirect Dispatch requires fixed-table raw buffers', }) RE_COMPUTE_DISPATCH_REFUSED = re.compile(