diff --git a/CMakeLists.txt b/CMakeLists.txt index df3f0e36b4..9d64c2b56d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3872,6 +3872,24 @@ if(EXISTS "${INTAKE_PYTHON}") # Vertex-stage buffer stores lower to RWByteAddressBuffer Store* under manifest version 2 (#1723). add_test(NAME startup_gfx2hlsl_buffer_store COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_buffer_store_check.py") + # Pixel-stage structured-to-raw buffer loads: translation controls, then a one-pixel draw on WARP and hardware. + # The udsrc cases are a compiled target (MSVC here, the same source rebuilt by the Python check elsewhere). + add_executable(startup_udsrc_line_check tests/startup_udsrc_line_check.cpp) + target_compile_features(startup_udsrc_line_check PRIVATE cxx_std_17) + target_include_directories(startup_udsrc_line_check PRIVATE src/startup_stubs) + add_test(NAME startup_gfx2hlsl_ps_raw_descriptor_udsrc COMMAND startup_udsrc_line_check) + set(udsrc_check_env "X2W_UDSRC_CHECK=$;X2W_CXX=${CMAKE_CXX_COMPILER}") + add_test(NAME startup_gfx2hlsl_ps_raw_descriptor COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py") + set_tests_properties(startup_gfx2hlsl_ps_raw_descriptor PROPERTIES ENVIRONMENT "${udsrc_check_env}") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_ps_raw_descriptor_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py" draw + "${DXC_EXECUTABLE}" "$" ${adapter} + $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_ps_raw_descriptor_${adapter} PROPERTIES + TIMEOUT 180 SKIP_RETURN_CODE 77 ENVIRONMENT "${udsrc_check_env}") + endforeach() # Output modifiers on float-result conversions (#1705). add_test(NAME startup_gfx2hlsl_vcvt_omod COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_vcvt_omod_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 75d3674ea3..153de6b421 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -445,6 +445,17 @@ The descriptor modifications that compute buffer stores accept are accepted here ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_buffer_store$' --output-on-failure ``` +## Pixel structured-to-raw buffer loads + +A non-indexed `buffer_load_dword` in a pixel stage lowers a descriptor that went through the structured-to-raw conversion. The conversion is the one compute and vertex stores already record: `s_bfe_u32` of DW1 with `0xe0010` (optionally `s_max_u32` with 1), `s_and_b32` of DW1 with `0xc000ffff`, `s_mul_i32` of DW2 by that stride, then `s_and_b32` of DW3 with `0xcfffffff` and `s_or_b32` with `0x30000000`. The four words are tracked in the pixel stage the same way. The load is a raw byte-address read. Each dword is kept when its end byte is at or before the 32-bit product `NUM_RECORDS * stride` (`NUM_RECORDS * max(stride, 1)` when the extract was clamped); a wrapped address reads as zero. The entry constants are that view's `stride` and `numrecords`. The graphics stand-in fills `stride` from DW1 and `numrecords` from DW2 of a table buffer descriptor, and fills `numrecords` from the element count of a buffer view the title created. An unknown `udsrc` kind refuses the translation, so a later line is not dropped while the shader still runs. Each address term is added with an overflow check before the range compare, so a sum that wraps is zero even when the truncated address would have landed in range. A `dwordx2` or `dwordx4` that crosses the product keeps the in-range dwords and zeroes the rest. A stride of 0 makes the product 0. A non-zero `soffset` is another term of the same sum. The conversion may run on an `s_mov` copy of the loaded words. A typed `tbuffer_load_format` through the converted descriptor stays refused. The offscreen fixture compares one pixel with a CPU model of the same product, and draws a wrapping address as four zeros. A load from a second, untouched descriptor does not keep the first descriptor's bound. A word overwritten by anything other than this conversion, a conversion missing the byte-count multiply or the raw out-of-range step, a stride taken from a different descriptor, and an `idxen` load stay refused (`buffer load through a modified descriptor`, or `indexed load through a modified descriptor` for `idxen`). An address that is not a multiple of four is not refused. DW1 swizzle, `ADD_TID` and the DW3 format field are kept and not checked. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_ps_raw_descriptor$' --output-on-failure +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_ps_raw_descriptor_(warp|hardware|udsrc)$' --output-on-failure +``` + +The draw runs on the Windows test PC. A capability skip (77) is separate from a pass. + ## Shared-exponent target stand-in `startup_packed_target` checks the selection rule with synthetic format support diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index a5b384dd3a..5188091eba 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -379,7 +379,7 @@ IndirectBufferView compute_root_srv_buffer(Wrapper* self, const Pass& pass, int if (bytes < 4) return refuse("a compute root SRV has fewer than 4 aligned bytes in its upload allocation"); words[2] = static_cast(bytes); - return {allocation.resource, allocation.offset, bytes, 0, true}; + return indirect_buffer_view(allocation.resource, allocation.offset, bytes, 0, 0, true, 0); } Wrapper* device = self->own().list_device; const auto first = placed_buffer_range(device, address, 4); @@ -414,7 +414,7 @@ IndirectBufferView compute_root_srv_buffer(Wrapper* self, const Pass& pass, int offset > desc.Width || bytes > desc.Width - offset) return refuse("a compute root SRV range is outside its desktop buffer"); words[2] = static_cast(bytes); - return {native, offset, bytes, 0, false}; + return indirect_buffer_view(native, offset, bytes, 0, 0, false, 0); } // Both callers have an open list and a slot 67 request. The indirect caller has checked the signature and argument range. diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 3d18422106..0d4e72b4a8 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -10,6 +10,8 @@ // upload ring / a private descriptor heap. #include "startup_stubs/typed_uav_load.h" +#include "startup_stubs/udsrc_line.h" +#include "startup_stubs/indirect_buffer_view.h" // A pixel-stage image store (#1996 item F, #2742): tools/startup/gfx2hlsl.py writes 'uav N tex2d|tex2da table P O' // for the RWTexture2D or RWTexture2DArray at u, whose descriptor is at byte O of the title's @@ -154,7 +156,11 @@ const char* pixel_uav_view(ID3D12Device* device, const D3D12_RESOURCE_DESC& reso struct Translation { struct Srv { int kind, source, a, b; }; // kind 0 buffer, 1 2D texture, 2 2D array, 3 3D texture, 4 1D texture, 5 cube; source 0 table(param a, byte b), 1 vertex stream a, 2 root parameter a - enum UdKind { rect, base_vertex, start_instance, root_constant, stride, mrt_bits, d16_unorm16, desc_word3 }; + enum UdKind { + rect = udsrc_rect, base_vertex = udsrc_base_vertex, start_instance = udsrc_start_instance, + root_constant = udsrc_root_constant, stride = udsrc_stride, mrt_bits = udsrc_mrt_bits, + d16_unorm16 = udsrc_d16_unorm16, desc_word3 = udsrc_desc_word3, num_records = udsrc_num_records + }; struct Ud { int kind, a, b; }; int state = 0; // 1 ready, 2 unavailable #ifdef X2W_NATIVE_SHADERS @@ -455,6 +461,7 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}, std: const bool previously_missing = tr.manifest_retry.pending(); tr.manifest_retry.found(); bool matched_rtv = false; + UdSrcParsed udsrc; for (std::size_t at = 0; at < manifest.size();) { std::size_t end = manifest.find('\n', at); if (end == std::string::npos) end = manifest.size(); @@ -474,17 +481,13 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}, std: // so a translation whose stores would be silently skipped is never drawn (#1723). log("x2w-draw unsupported manifest version for %016llx", tr.key); return; - } else if (std::sscanf(line.c_str(), "udsrc %d %15s %d %d", &i, source, &x, &y) >= 2) { - Translation::Ud ud{-1, x, y}; - if (!std::strcmp(source, "rect")) ud.kind = Translation::rect; - else if (!std::strcmp(source, "basevertex")) ud.kind = Translation::base_vertex; - else if (!std::strcmp(source, "startinstance")) ud.kind = Translation::start_instance; - else if (!std::strcmp(source, "rootconst")) ud.kind = Translation::root_constant; - else if (!std::strcmp(source, "stride")) ud.kind = Translation::stride; - else if (!std::strcmp(source, "d16unorm16") && x >= 0 && x < 32) ud.kind = Translation::d16_unorm16; - else if (!std::strcmp(source, "descword3")) ud.kind = Translation::desc_word3; - else if (!std::strcmp(source, "mrtbits") && !rtv_request.empty()) ud.kind = Translation::mrt_bits; - if (static_cast(i) == tr.uds.size() && ud.kind >= 0) tr.uds.push_back(ud); + } else if (!accept_udsrc_line(line.c_str(), static_cast(tr.uds.size()), !rtv_request.empty(), &udsrc)) { + // An unknown kind or a gap used to be skipped. The shader's constant slot then read 0, and every + // udsrc after the gap was skipped too because its index no longer matched the next slot. + log("x2w-draw unsupported udsrc for %016llx: %s", tr.key, line.c_str()); + return; + } else if (udsrc.is_udsrc) { + tr.uds.push_back({udsrc.kind, udsrc.a, udsrc.b}); } else if (std::sscanf(line.c_str(), "srv %d %15s %15s %d %d", &i, kind, source, &x, &y) >= 4) { const int texture_kind = !std::strcmp(kind, "tex2d") ? 1 : !std::strcmp(kind, "tex2da") ? 2 : !std::strcmp(kind, "tex3d") ? 3 : !std::strcmp(kind, "tex1d") ? 4 : @@ -2162,6 +2165,8 @@ bool indirect_shader_entry(ID3DBlob* blob, const Translation& translation, bool if (ud.kind == Translation::stride && ud.a >= 0 && static_cast(ud.a) < translation.srvs.size() && (translation.srvs[ud.a].source == 0 || (indexed && translation.srvs[ud.a].source == 1)) && translation.srvs[ud.a].kind == 0) continue; + if (ud.kind == Translation::num_records && ud.a >= 0 && static_cast(ud.a) < translation.srvs.size() && + translation.srvs[ud.a].source == 0 && translation.srvs[ud.a].kind == 0) continue; if (ud.kind != Translation::root_constant && ud.kind != Translation::rect && ud.kind != Translation::d16_unorm16) return false; } @@ -2340,13 +2345,7 @@ ID3D12Resource* validate_indexed_arguments(Wrapper* self, ID3D12GraphicsCommandL return scratch.Get(); } -struct IndirectBufferView { - ID3D12Resource* resource = nullptr; - u64 offset = 0, bytes = 0; - UINT stride = 0; - bool upload = false; - int source = 0; // 0 aliased or any other backing, 1 a GPU copy this list made (X2W_TRANSLATED_INDIRECT_COPY_RANGES), 2 a snapshot of title memory, 3 zeros for a null descriptor -}; +using IndirectBufferView = IndirectBufferViewOf; // X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT=1: a translated compute input in a placed buffer that does not alias title memory // (a committed default buffer that holds zeros) is read from title memory, snapshotted into its own recycled pool. @@ -2369,7 +2368,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor return IndirectBufferView{}; }; u64 address = 0, offset = 0, bytes = 0; - UINT stride = 0; + UINT stride = 0, records = 0; const Wrapper* owner = nullptr; bool own_memory = false; if (why) *why = nullptr; @@ -2400,6 +2399,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor offset = view.Buffer.FirstElement * element; bytes = u64{view.Buffer.NumElements} * element; stride = raw ? 0 : element; + records = view.Buffer.NumElements; if (const auto base = reinterpret_cast(owner->own().title_memory)) { // A buffer on a custom heap outside the placement index (the memory view path places it in the title's // own heap) is that memory: the view offset is bound in the token's own desktop resource. @@ -2418,6 +2418,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor } else { address = words[0] | (u64{words[1] & 0xffff} << 32); stride = (words[1] >> 16) & 0x3fff; + records = words[2]; bytes = u64{stride ? stride : 1} * words[2]; } // A compute input whose four descriptor words are all zero is an unbound (null) buffer: the hardware reads zeros from @@ -2428,7 +2429,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor unsigned char* zero_bytes = reserve_upload_ring(self, 16, &zero_offset, &zero_ring, true); if (!zero_bytes || !zero_ring) return refuse("a null input could not get its zero bytes"); std::memset(zero_bytes, 0, 16); - return {zero_ring, zero_offset, 16, 0, true, 3}; + return indirect_buffer_view(zero_ring, zero_offset, 16, 0, 0, true, 3); } if (!bytes) return refuse("an input buffer descriptor has zero records"); if (bytes > limit || bytes % 4) return refuse(limit == (16u << 20) @@ -2440,7 +2441,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor Wrapper* device = self->own().list_device; if (address) { if (const auto allocation = list_upload_range(self, address, bytes); allocation.resource) { - if (!owner) return {allocation.resource, allocation.offset, bytes, stride, true}; + if (!owner) return indirect_buffer_view(allocation.resource, allocation.offset, bytes, stride, records, true, 0); return refuse("an input buffer view token names the list's upload memory"); } const auto placed = placed_buffer_range(device, address, bytes); @@ -2452,7 +2453,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor if (!alias.resource) return refuse(in_upload ? "an input range crosses the end of its upload allocation" : "an input is in title memory outside any placed buffer"); - return {alias.resource, alias.offset, bytes, stride}; + return indirect_buffer_view(alias.resource, alias.offset, bytes, stride, records, false, 0); } owner = placed.owner; native = static_cast(owner->own().real); @@ -2470,7 +2471,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor return refuse("an input range in title memory is not readable"); if (!ring_copy(self, address, static_cast(bytes), &ring_offset, &ring, true) || !ring) return refuse("an input range could not be copied from title memory"); - return {ring, ring_offset, bytes, stride, true, 2}; + return indirect_buffer_view(ring, ring_offset, bytes, stride, records, true, 2); } else { return refuse("an input is in a placed buffer that does not alias title memory"); } @@ -2498,7 +2499,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor const auto desc = native->GetDesc(); if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || (desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) || offset > desc.Width || bytes > desc.Width - offset) return refuse("an input range is outside its desktop buffer"); - return {native, offset, bytes, stride, upload, input_source}; + return indirect_buffer_view(native, offset, bytes, stride, records, upload, input_source); } struct FormattedBufferDescriptor { @@ -2772,6 +2773,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI InterlockedExchange(&draw_heap_cursor, static_cast(views)); } std::uint32_t strides[32] = {}; + std::uint32_t record_counts[32] = {}; // Only the vertices this draw can reference are copied: [vertex_first, vertex_first + vertex_count). // The shader adds the "base vertex" entry value to the vertex index, so that value is biased by // -vertex_first and each stream's view starts at vertex_first. @@ -2992,6 +2994,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI if (!view.upload) require_state(self, view.resource, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); strides[i] = view.stride; + record_counts[i] = view.records; buffer_view(dest, view.resource, view.offset, static_cast(view.bytes)); continue; } @@ -3019,6 +3022,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI address = reinterpret_cast(resource->own().title_memory) + view.Buffer.FirstElement * element; bytes = std::size_t{view.Buffer.NumElements} * element; strides[i] = typed_view ? element : view.Buffer.StructureByteStride; + record_counts[i] = view.Buffer.NumElements; } } } @@ -3026,6 +3030,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI // A hardware buffer descriptor the title wrote itself: base address, stride and record count. address = words[0] | (static_cast(words[1] & 0xffff) << 32); strides[i] = (words[1] >> 16) & 0x3fff; + record_counts[i] = words[2]; bytes = static_cast(strides[i] ? strides[i] : 1) * words[2]; } const std::size_t view_bytes = bytes; // before the 16 MiB copy cap @@ -3186,6 +3191,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI : ud.kind == Translation::start_instance ? start_instance : ud.kind == Translation::root_constant ? ((ud.a >= 0 && ud.a < 16 && ud.b >= 0 && ud.b < 8) ? pass.constants[ud.a][ud.b] : 0) : ud.kind == Translation::stride && ud.a >= 0 && ud.a < 32 ? strides[ud.a] + : ud.kind == Translation::num_records && ud.a >= 0 && ud.a < 32 ? record_counts[ud.a] : ud.kind == Translation::d16_unorm16 && ud.a >= 0 && ud.a < 32 ? d16_unorm16[ud.a] : ud.kind == Translation::desc_word3 ? formatted_buffers[ud.a].words[3] : 0; } diff --git a/src/startup_stubs/indirect_buffer_view.h b/src/startup_stubs/indirect_buffer_view.h new file mode 100644 index 0000000000..9eb91990a9 --- /dev/null +++ b/src/startup_stubs/indirect_buffer_view.h @@ -0,0 +1,33 @@ +#pragma once +// A translated buffer binding. records is the descriptor NUM_RECORDS (or a created view's element count). +// source is 0 for an alias or any other backing, 1 for a GPU copy this list made, 2 for a snapshot of title +// memory, and 3 for zeros that stand in for a null descriptor. +// Members are assigned by name. A brace initializer put the upload flag in records and narrowed the next +// integer into the bool. +#include + +template +struct IndirectBufferViewOf { + Resource* resource = nullptr; + std::uint64_t offset = 0; + std::uint64_t bytes = 0; + unsigned stride = 0; + unsigned records = 0; + bool upload = false; + int source = 0; +}; + +template +IndirectBufferViewOf indirect_buffer_view(Resource* resource, std::uint64_t offset, std::uint64_t bytes, + unsigned stride, unsigned records, bool upload, int source) +{ + IndirectBufferViewOf view; + view.resource = resource; + view.offset = offset; + view.bytes = bytes; + view.stride = stride; + view.records = records; + view.upload = upload; + view.source = source; + return view; +} diff --git a/src/startup_stubs/udsrc_line.h b/src/startup_stubs/udsrc_line.h new file mode 100644 index 0000000000..19c121123f --- /dev/null +++ b/src/startup_stubs/udsrc_line.h @@ -0,0 +1,55 @@ +#pragma once +// Manifest `udsrc` lines for a translated draw. Kind numbers are Translation::UdKind in d3d12_draw.inl. +#include +#include + +enum { + udsrc_rect = 0, + udsrc_base_vertex = 1, + udsrc_start_instance = 2, + udsrc_root_constant = 3, + udsrc_stride = 4, + udsrc_mrt_bits = 5, + udsrc_d16_unorm16 = 6, + udsrc_desc_word3 = 7, + udsrc_num_records = 8 +}; + +struct UdSrcParsed { + bool is_udsrc = false; + int kind = -1; + int index = 0; + int a = 0; + int b = 0; +}; + +// A line that is not `udsrc` leaves is_udsrc clear and returns true so the caller can try another kind of line. +// An unknown kind, a gap, or an index that is not the next slot returns false: the translation is not used, +// so a later udsrc line is not dropped while the shader still runs. +// mrtbits is known only when the manifest is paired with an RTV request. d16unorm16 needs a view index in 0..31. +inline bool accept_udsrc_line(const char* line, int next_index, bool rtv_request, UdSrcParsed* out) +{ + out->is_udsrc = false; + out->kind = -1; + if (std::strncmp(line, "udsrc ", 6) != 0) return true; + int index = 0, a = 0, b = 0; + char source[16] = ""; + if (std::sscanf(line, "udsrc %d %15s %d %d", &index, source, &a, &b) < 2) return false; + int kind = -1; + if (!std::strcmp(source, "rect")) kind = udsrc_rect; + else if (!std::strcmp(source, "basevertex")) kind = udsrc_base_vertex; + else if (!std::strcmp(source, "startinstance")) kind = udsrc_start_instance; + else if (!std::strcmp(source, "rootconst")) kind = udsrc_root_constant; + else if (!std::strcmp(source, "stride")) kind = udsrc_stride; + else if (!std::strcmp(source, "d16unorm16") && a >= 0 && a < 32) kind = udsrc_d16_unorm16; + else if (!std::strcmp(source, "descword3")) kind = udsrc_desc_word3; + else if (!std::strcmp(source, "mrtbits") && rtv_request) kind = udsrc_mrt_bits; + else if (!std::strcmp(source, "numrecords")) kind = udsrc_num_records; + if (kind < 0 || index != next_index || next_index < 0 || next_index >= 32) return false; + out->is_udsrc = true; + out->kind = kind; + out->index = index; + out->a = a; + out->b = b; + return true; +} diff --git a/tests/checks/python-linux/startup_gfx2hlsl_ps_raw_descriptor.txt b/tests/checks/python-linux/startup_gfx2hlsl_ps_raw_descriptor.txt new file mode 100644 index 0000000000..35601c5307 --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_ps_raw_descriptor.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_ps_raw_descriptor_check.py diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index d57366ae69..037d7cae6b 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -38,6 +38,11 @@ void check_startup_flat_param(ID3D12Device* device, const char* vertex_path, con std::uint32_t* words, UINT width = 1, UINT height = 1, D3D12_CULL_MODE cull = D3D12_CULL_MODE_NONE, BOOL front_ccw = FALSE, UINT vertices = 3, const std::uint32_t* constants = nullptr); +// One pixel. The pixel stage reads t0 as a raw buffer (a descriptor table) and b0 as entry constants. +// source_dwords is the number of 32-bit elements in the raw view; the readback is the four exported words. +void check_startup_raw_buffer(ID3D12Device* device, const char* vertex_path, const char* pixel_path, + const std::uint32_t* constants, UINT constant_count, + const std::uint32_t* source, UINT source_dwords, std::uint32_t words[4]); void check_startup_entry_words(ID3D12Device* device, const char* vertex_path, const char* pixel_path, const std::uint32_t* entry, UINT entry_count, std::uint32_t* words, UINT width = 1, UINT height = 1); diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index 3d53da367c..065281afa0 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -1597,6 +1597,34 @@ OperationResult run_startup_flat_param(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } +static std::vector parse_hex_words(std::string_view text); + +// --startup-raw-buffer : draws one pixel whose +// pixel stage reads a raw buffer at t0 (a descriptor table) and entry constants at b0. and +// are comma-separated 8-digit hex words. is the four words the target must hold. +OperationResult run_startup_raw_buffer(const OperationContext& ctx) +{ + const auto constants = parse_hex_words(ctx.argv[5]); + const auto source = parse_hex_words(ctx.argv[6]); + const auto expected = parse_hex_words(ctx.argv[7]); + if (constants.empty() || constants.size() > 63) + return {OutcomeKind::fail, "entry constants are not 1..63 hex words"}; + if (source.empty() || source.size() > 4096) + return {OutcomeKind::fail, "source buffer is not 1..4096 hex words"}; + if (expected.size() != 4) + return {OutcomeKind::fail, "expected value is not four hex words"}; + std::uint32_t words[4]{}; + check_startup_raw_buffer(ctx.device, ctx.argv[3], ctx.argv[4], constants.data(), UINT(constants.size()), + source.data(), UINT(source.size()), words); + if (std::memcmp(words, expected.data(), sizeof(words)) != 0) { + std::fprintf(stderr, "startup_raw_buffer mismatch expected=%08x,%08x,%08x,%08x " + "actual=%08x,%08x,%08x,%08x\n", + expected[0], expected[1], expected[2], expected[3], words[0], words[1], words[2], words[3]); + return {OutcomeKind::fail, "raw buffer readback differs"}; + } + return {OutcomeKind::pass, nullptr}; +} + // Comma-separated 8-digit hex words, in order. An empty list or any other shape returns nothing. static std::vector parse_hex_words(std::string_view text) { @@ -1767,6 +1795,7 @@ const OperationSpec kOperations[] = { {"--startup-packed-position", 5, 5, nullptr, kNoGate, run_startup_packed_position}, {"--startup-sharedexp-target", 3, 3, nullptr, kNoGate, run_startup_sharedexp_target}, {"--startup-flat-param", 6, 7, nullptr, kNoGate, run_startup_flat_param}, + {"--startup-raw-buffer", 8, 8, nullptr, kNoGate, run_startup_raw_buffer}, {"--startup-entry-words", 7, 7, nullptr, kNoGate, run_startup_entry_words}, {"--startup-pixel-words", 8, 8, validate_pixel_words_args, kNoGate, run_startup_pixel_words}, {"--raster-reference", 10, 10, validate_raster_args, kNoGate, run_startup_pixel_words}, diff --git a/tests/startup_flat_param.cpp b/tests/startup_flat_param.cpp index 7c92eb02b8..5471fca489 100644 --- a/tests/startup_flat_param.cpp +++ b/tests/startup_flat_param.cpp @@ -125,3 +125,124 @@ void check_startup_flat_param(ID3D12Device* device, const char* vertex_path, con readback->Unmap(0, &none); std::printf("startup_flat_param words=%08x,%08x,%08x,%08x\n", words[0], words[1], words[2], words[3]); } + +void check_startup_raw_buffer(ID3D12Device* device, const char* vertex_path, const char* pixel_path, + const std::uint32_t* constants, UINT constant_count, + const std::uint32_t* source, UINT source_dwords, std::uint32_t words[4]) +{ + if (constant_count < 1 || constant_count > 63) + throw std::runtime_error("raw buffer draw needs 1..63 entry constants; the descriptor table uses the 64th root dword"); + if (source_dwords < 1 || source_dwords > 4096) + throw std::runtime_error("raw buffer draw needs 1..4096 source dwords"); + const auto vs = read_blob(vertex_path); + const auto ps = read_blob(pixel_path); + + D3D12_DESCRIPTOR_RANGE range{}; + range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + range.NumDescriptors = 1; + range.BaseShaderRegister = 0; + range.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; + D3D12_ROOT_PARAMETER params[2]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants = {0, 0, constant_count}; + params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[1].DescriptorTable = {1, &range}; + params[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + D3D12_ROOT_SIGNATURE_DESC rs{}; + rs.NumParameters = 2; + rs.pParameters = params; + ComPtr signature, errors; + if (FAILED(D3D12SerializeRootSignature(&rs, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &errors))) + throw std::runtime_error(errors ? static_cast(errors->GetBufferPointer()) + : "Serialize raw buffer root signature"); + ComPtr root; + check(device->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&root)), + "Create raw buffer root signature"); + + D3D12_GRAPHICS_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = root.Get(); + pd.VS = {vs.data(), vs.size()}; + pd.PS = {ps.data(), ps.size()}; + pd.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pd.SampleMask = UINT_MAX; + pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pd.RasterizerState.DepthClipEnable = TRUE; + pd.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + pd.NumRenderTargets = 1; + pd.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + pd.SampleDesc.Count = 1; + ComPtr pipeline; + check(device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pipeline)), "Create raw buffer PSO"); + + D3D12_RESOURCE_DESC rd{}; + rd.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rd.Width = 1; + rd.Height = 1; + rd.DepthOrArraySize = 1; + rd.MipLevels = 1; + rd.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + rd.SampleDesc.Count = 1; + rd.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + const D3D12_CLEAR_VALUE clear{DXGI_FORMAT_R32G32B32A32_FLOAT, {-1.0f, -1.0f, -1.0f, -1.0f}}; + const auto target = resource(device, rd, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_RENDER_TARGET, &clear); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 readback_size = 0; + device->GetCopyableFootprints(&rd, 0, 1, 0, &footprint, nullptr, nullptr, &readback_size); + const auto readback = make_buffer(device, readback_size, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + + const auto input = make_buffer(device, UINT64(source_dwords) * sizeof(std::uint32_t), D3D12_HEAP_TYPE_UPLOAD, + D3D12_RESOURCE_STATE_GENERIC_READ); + void* upload = nullptr; + check(input->Map(0, nullptr, &upload), "Map raw buffer upload"); + std::memcpy(upload, source, UINT64(source_dwords) * sizeof(std::uint32_t)); + input->Unmap(0, nullptr); + D3D12_DESCRIPTOR_HEAP_DESC views_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr views; + check(device->CreateDescriptorHeap(&views_desc, IID_PPV_ARGS(&views)), "Create raw buffer SRV heap"); + 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 = source_dwords; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(input.Get(), &srv, views->GetCPUDescriptorHandleForHeapStart()); + + D3D12_DESCRIPTOR_HEAP_DESC rtv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}; + ComPtr rtvs; + check(device->CreateDescriptorHeap(&rtv_desc, IID_PPV_ARGS(&rtvs)), "Create raw buffer RTV heap"); + const auto rtv = rtvs->GetCPUDescriptorHandleForHeapStart(); + device->CreateRenderTargetView(target.Get(), nullptr, rtv); + + ComputeCommands commands(device, pipeline.Get(), D3D12_COMMAND_LIST_TYPE_DIRECT); + auto* list = commands.list.Get(); + list->ClearRenderTargetView(rtv, clear.Color, 0, nullptr); + list->SetGraphicsRootSignature(root.Get()); + ID3D12DescriptorHeap* heaps[] = {views.Get()}; + list->SetDescriptorHeaps(1, heaps); + list->SetGraphicsRoot32BitConstants(0, constant_count, constants, 0); + list->SetGraphicsRootDescriptorTable(1, views->GetGPUDescriptorHandleForHeapStart()); + const D3D12_VIEWPORT viewport{0, 0, 1, 1, 0, 1}; + const D3D12_RECT scissor{0, 0, 1, 1}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->DrawInstanced(3, 1, 0, 0); + transition(list, target.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION out{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + out.PlacedFootprint = footprint; + D3D12_TEXTURE_COPY_LOCATION in{target.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + list->CopyTextureRegion(&out, 0, 0, 0, &in, nullptr); + commands.submit_and_wait(device); + + void* mapped = nullptr; + const D3D12_RANGE read{0, static_cast(readback_size)}; + const D3D12_RANGE none{0, 0}; + check(readback->Map(0, &read, &mapped), "Map raw buffer readback"); + std::memcpy(words, static_cast(mapped) + footprint.Offset, 4 * sizeof(*words)); + readback->Unmap(0, &none); + std::printf("startup_raw_buffer words=%08x,%08x,%08x,%08x\n", words[0], words[1], words[2], words[3]); +} diff --git a/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py b/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py new file mode 100644 index 0000000000..1376077dea --- /dev/null +++ b/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py @@ -0,0 +1,493 @@ +"""Pixel-stage structured-to-raw buffer loads in tools/startup/gfx2hlsl.py. + + (no arguments) translation controls, the CPU model and the udsrc parser + draw [fxc] + translate, compile and draw one pixel. The readback must match the + CPU model of a raw byte-address load bounded by NUM_RECORDS * stride. + Dropping that bound must read the word past the bound. + +The fixture is source-built. A pixel stage loads one table descriptor, clears its stride, scales NUM_RECORDS +by the extracted stride and sets OOB_SELECT to raw, then reads four dwords with buffer_load_dword offen. +""" +import os +import shutil +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + +MODIFIED = 'buffer load through a modified descriptor' +INDEXED = 'indexed load through a modified descriptor' +STRIDE = 8 +RECORDS = 4 +# Nine words the resource holds, then padding so the raw view's element count is a multiple of four. +# Word 8 sits past the converted byte count (8 * 4 = 32) and must read back as zero. +SOURCE = (0x3f800000, 0x40000000, 0x40400000, 0x40800000, 0x40a00000, 0x40c00000, 0x40e00000, 0x41000000, + 0xdeadbeef, 0, 0, 0) +OFFSETS = (0, 12, 28, 32) +DESC = 16 +TMP = 20 + +SOP2 = {'s_and_b32': 0x0e, 's_or_b32': 0x10, 's_max_u32': 0x09, 's_mul_i32': 0x26, 's_bfe_u32': 0x27} + +# One descriptor table. Graphics user data starts at s8; the pixel stage loads s[16:19] from that pointer. +RTS0 = b''.join((struct.pack('<6I', 2, 1, 24, 0, 0, 0), struct.pack('<3I', 0, 0, 36), + struct.pack('<2I', 1, 44), struct.pack('<6I', 0, 1, 0, 0, 0, 0))) +PART = b'RTS0' + struct.pack('> 3) & 1) << 21) | (((srsrc // 4) & 0x1f) << 16) + w1 |= ((vdata & 0xff) << 8) | (vaddr & 0xff) + return struct.pack('= base + base = total & 0xffffffff + return ok, base + + +def raw_dwords(parts, count, stride=STRIDE, records=RECORDS): + ok, address = add_u32(parts) + limit = (stride * records) & 0xffffffff + words = [] + for i in range(count): + end = (address + 4 * (i + 1)) & 0xffffffff + if not ok or end < address or end > limit: + words.append(0) + else: + words.append(SOURCE[address // 4 + i]) + return tuple(words) + + +def cpu_load(address, stride=STRIDE, records=RECORDS): + """One raw dword: in range when the 32-bit end byte does not wrap and is at or before the product.""" + return raw_dwords((address,), 1, stride, records)[0] + + +def expected_words(): + return tuple(cpu_load(offset) for offset in OFFSETS) + + +def ud_index(manifest, kind): + found = [int(line.split()[1]) for line in manifest.splitlines() + if line.startswith('udsrc ') and line.split()[2] == kind] + if len(found) != 1: + raise AssertionError('udsrc %s: %s' % (kind, manifest)) + return found[0] + + +def must_refuse(label, ps, message): + try: + translate(ps) + except G.Unsupported as error: + if str(error) != message: + raise AssertionError('%s: refused with %r, expected %r' % (label, str(error), message)) + print('%s: refused (%s)' % (label, message)) + return + raise AssertionError('%s: translated' % label) + + +def bound_open(stride, records, clamped=False): + factor = 'max(ud%d, 1u)' % stride if clamped else 'ud%d' % stride + return '{ uint lim = %s * ud%d; uint base = 0; bool ok = true;' % (factor, records) + + +def assert_bounded(ps, stride, records, offsets, count=1, clamped=False, terms=None): + assert bound_open(stride, records, clamped) in ps, ps + assert 'a = v0 +' not in ps, ps + for term in terms or ('v0',): + assert 'ok = ok && base + (%s) >= base; base += %s;' % (term, term) in ps, ps + for index, offset in enumerate(offsets): + assert 'ok = ok && base + (%d) >= base; base += %d;' % (offset, offset) in ps, ps + for lane in range(count): + end = 4 * (lane + 1) + line = 'v%d = (ok && a + %du >= a && a + %du <= lim) ? r0.Load(a + %d) : 0u;' % ( + 1 + index * count + lane, end, end, 4 * lane) + assert line in ps, ps + + +def controls(): + pipe = translate(program(conversion())) + ps, manifest = pipe.hlsl_ps(), pipe.manifest() + stride, records = ud_index(manifest, 'stride'), ud_index(manifest, 'numrecords') + assert 'ByteAddressBuffer r0 : register(t0);' in ps, ps + assert 'srv 0 buf table 0 0' in manifest, manifest + assert_bounded(ps, stride, records, OFFSETS) + print('raw conversion: four offen loads bounded by ud%d * ud%d' % (stride, records)) + + clamped = translate(program(conversion(clamp=True))) + cps, cmanifest = clamped.hlsl_ps(), clamped.manifest() + cstride, crecords = ud_index(cmanifest, 'stride'), ud_index(cmanifest, 'numrecords') + assert_bounded(cps, cstride, crecords, OFFSETS, clamped=True) + print('clamped raw conversion: bound is max(stride, 1) * NUM_RECORDS') + + stride0 = program(sop2('s_and_b32', DESC + 1, DESC + 1, 255, 0xc000ffff)) + text = translate(stride0).hlsl_ps() + assert 'v1 = r0.Load(a + 0);' in text and 'uint lim' not in text, text + print('stride clear only: unbounded raw load') + + # A dwordx2 at byte 28 covers bytes 28 and 32. Only the first dword is inside the 32-byte limit. + cross2 = finish(smem_load_x4(DESC, 8) + conversion() + v_mov(0, 0) + + encode_mubuf(0x0d, imm=28, offen=1, vdata=1)) + x2 = translate(cross2) + assert_bounded(x2.hlsl_ps(), ud_index(x2.manifest(), 'stride'), ud_index(x2.manifest(), 'numrecords'), + (28,), count=2) + assert raw_dwords((0, 28), 2) == (SOURCE[7], 0) + print('dwordx2: the dword that crosses NUM_RECORDS * stride is zero') + + # A dwordx4 at byte 24 covers 24, 28, 32 and 36. The last two dwords are out. + cross4 = finish(smem_load_x4(DESC, 8) + conversion() + v_mov(0, 0) + + encode_mubuf(0x0e, imm=24, offen=1, vdata=1)) + x4 = translate(cross4) + assert_bounded(x4.hlsl_ps(), ud_index(x4.manifest(), 'stride'), ud_index(x4.manifest(), 'numrecords'), + (24,), count=4) + assert raw_dwords((0, 24), 4) == (SOURCE[6], SOURCE[7], 0, 0) + print('dwordx4: two dwords inside the limit, then two zeros') + + assert raw_dwords((0,), 1, stride=0, records=4) == (0,) + assert raw_dwords((4,), 1, stride=0, records=4) == (0,) + print('stride 0: the product is zero, so every positive end is out of range') + + # soffset is an inline 8 in s21. v0 is 0, so the addresses are 8+4 and 8+28. + shifted = finish(smem_load_x4(DESC, 8) + conversion() + s_mov(21, 128 + 8) + v_mov(0, 0) + + encode_mubuf(0x0c, imm=4, offen=1, vdata=1, soffset=21) + + encode_mubuf(0x0c, imm=28, offen=1, vdata=2, soffset=21), + exports=(1, 2, 1, 2)) + shifted_ps = translate(shifted).hlsl_ps() + assert 'base + (0x00000008u)' in shifted_ps and 'base + (4)' in shifted_ps and 'base + (28)' in shifted_ps, shifted_ps + assert raw_dwords((0, 8, 4), 1) == (SOURCE[3],) + assert raw_dwords((0, 8, 28), 1) == (0,) + print('non-zero soffset: byte 12 is in range and byte 36 is not') + + # The conversion runs on a copy of the loaded words, not on the registers the load wrote. + copied = b''.join(s_mov(24 + i, DESC + i) for i in range(4)) + copy_ps = translate(program(copied + conversion(base=24, tmp=28), srsrc=24)).hlsl_ps() + assert 'uint lim' in copy_ps and 'r0.Load(a + 0)' in copy_ps, copy_ps + print('copied descriptor: the bound follows the s_mov copies') + + # v0 is 0xfffffffc. Adding 12, 28 or 32 wraps before the range test, so those loads are zero + # rather than the words at the truncated addresses 8, 24 and 28. + wrapped = wrap_program() + wrapped_ps = translate(wrapped).hlsl_ps() + assert 'ok = ok && base + (v0) >= base; base += v0;' in wrapped_ps, wrapped_ps + assert raw_dwords((0xfffffffc, 12), 1) == (0,) + assert raw_dwords((0xfffffffc, 28), 1) == (0,) + assert raw_dwords((0xfffffffc, 32), 1) == (0,) + assert (SOURCE[2], SOURCE[6], SOURCE[7]) == (0x40400000, 0x40e00000, 0x41000000) + print('address wrap: a term that overflows the 32-bit sum reads zero') + + # The converted descriptor and an untouched second descriptor. The second load must not keep the first bound. + both = finish(smem_load_x4(DESC, 8) + smem_load_x4(24, 8, 32) + conversion() + v_mov(0, 0) + + encode_mubuf(0x0c, imm=0, offen=1, vdata=1, srsrc=DESC) + + encode_mubuf(0x0c, imm=0, offen=1, vdata=2, srsrc=24), + exports=(1, 2, 1, 2)) + both_ps = translate(both).hlsl_ps() + assert 'v1 = (ok && a + 4u >= a && a + 4u <= lim) ? r0.Load(a + 0) : 0u;' in both_ps, both_ps + assert 'v2 = r1.Load(a + 0);' in both_ps and 'v2 = (ok' not in both_ps, both_ps + print('second descriptor: an untouched load does not keep the converted bound') + + typed = finish(smem_load_x4(DESC, 8) + conversion() + v_mov(0, 0) + + encode_mtbuf(0, 22, imm=32, offen=1, vdata=1), exports=(1, 1, 1, 1)) + must_refuse('typed buffer load', typed, MODIFIED) + + missing_count = (sop2('s_bfe_u32', TMP, DESC + 1, 255, 0xe0010) + + sop2('s_and_b32', DESC + 1, DESC + 1, 255, 0xc000ffff) + + sop2('s_and_b32', DESC + 3, DESC + 3, 255, 0xcfffffff) + + sop2('s_or_b32', DESC + 3, DESC + 3, 255, 0x30000000)) + missing_oob = (sop2('s_bfe_u32', TMP, DESC + 1, 255, 0xe0010) + + sop2('s_and_b32', DESC + 1, DESC + 1, 255, 0xc000ffff) + + sop2('s_mul_i32', DESC + 2, DESC + 2, TMP)) + wrong_mask = conversion().replace(struct.pack('= 0 && ud.a < 32 ? record_counts[ud.a]' in draw + assert 'x2w-draw unsupported udsrc' in draw + refusal = draw.split('x2w-draw unsupported udsrc', 1)[1][:220] + assert 'return;' in refusal and 'continue;' not in refusal, refusal + run_udsrc_driver(root) + print('udsrc: numrecords is stored, and an unknown kind or a gap refuses the manifest') + + +def compiler_is_msvc(compiler): + return Path(compiler).name.lower() in ('cl', 'cl.exe') + + +def udsrc_compiler(): + """CMake passes cl on Windows. A direct run uses cl there and g++ elsewhere. Neither is optional.""" + chosen = os.environ.get('X2W_CXX') + if chosen: + return chosen + if os.name == 'nt': + found = shutil.which('cl') + if not found: + raise AssertionError('udsrc parser check needs cl.exe (set X2W_CXX to the MSVC compiler)') + return found + for name in ('g++', 'c++'): + found = shutil.which(name) + if found: + return found + raise AssertionError('udsrc parser check needs g++') + + +def run_udsrc_driver(root): + """Run tests/startup_udsrc_line_check.cpp. CTest passes the binary it just built; otherwise compile it.""" + ready = os.environ.get('X2W_UDSRC_CHECK') + if ready: + binary = Path(ready) + if not binary.is_file(): + raise AssertionError('udsrc check executable is missing: %s' % binary) + run = subprocess.run([str(binary)], capture_output=True, text=True) + if run.returncode: + raise AssertionError('udsrc driver exit %s\n%s%s' % (run.returncode, run.stdout, run.stderr)) + return + compiler = udsrc_compiler() + source = HERE / 'startup_udsrc_line_check.cpp' + include = root / 'src' / 'startup_stubs' + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + binary = directory / ('udsrc_main.exe' if compiler_is_msvc(compiler) else 'udsrc_main') + if compiler_is_msvc(compiler): + command = [compiler, '/nologo', '/std:c++17', '/EHsc', '/W4', '/I', str(include), + str(source), '/Fe%s' % binary, '/Fo%s' % (directory / 'udsrc_main.obj')] + else: + command = [compiler, '-std=c++17', '-Wall', '-Wextra', '-I', str(include), str(source), '-o', str(binary)] + built = subprocess.run(command, cwd=directory, capture_output=True, text=True) + if built.returncode: + raise AssertionError(built.stdout + built.stderr) + run = subprocess.run([str(binary)], capture_output=True, text=True) + if run.returncode: + raise AssertionError('udsrc driver exit %s' % run.returncode) + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'draw': + controls() + check_draw(*args) + return + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_udsrc_line_check.cpp b/tests/startup_udsrc_line_check.cpp new file mode 100644 index 0000000000..81815af4e8 --- /dev/null +++ b/tests/startup_udsrc_line_check.cpp @@ -0,0 +1,38 @@ +// The draw stand-in accepts a numrecords udsrc and refuses an unknown kind or a gap. +// Exit codes are the cases tests/startup_gfx2hlsl_ps_raw_descriptor_check.py reports. +#include "udsrc_line.h" +#include "indirect_buffer_view.h" + +struct HostResource {}; + +int main() +{ + UdSrcParsed parsed{}; + if (!accept_udsrc_line("udsrc 0 rect", 0, false, &parsed) || !parsed.is_udsrc || parsed.kind != udsrc_rect) + return 1; + if (!accept_udsrc_line("udsrc 4 numrecords 0", 4, false, &parsed) || parsed.kind != udsrc_num_records || parsed.a != 0) + return 2; + if (accept_udsrc_line("udsrc 5 notakind 0", 5, false, &parsed)) + return 3; + if (accept_udsrc_line("udsrc 6 stride 0", 5, false, &parsed)) + return 4; + if (!accept_udsrc_line("udsrc 5 stride 0", 5, false, &parsed) || parsed.kind != udsrc_stride) + return 5; + if (!accept_udsrc_line("srv 0 buf table 0 0", 0, false, &parsed) || parsed.is_udsrc) + return 6; + if (accept_udsrc_line("udsrc 0 mrtbits", 0, false, &parsed)) + return 7; + if (!accept_udsrc_line("udsrc 0 mrtbits", 0, true, &parsed) || parsed.kind != udsrc_mrt_bits) + return 8; + HostResource resource; + const auto null_input = indirect_buffer_view(&resource, std::uint64_t{8}, std::uint64_t{16}, 0u, 0u, true, 3); + if (null_input.records != 0 || !null_input.upload || null_input.source != 3 || null_input.bytes != 16 || null_input.offset != 8) + return 9; + const auto snapshot = indirect_buffer_view(&resource, std::uint64_t{4}, std::uint64_t{32}, 8u, 4u, true, 2); + if (snapshot.records != 4 || !snapshot.upload || snapshot.source != 2 || snapshot.stride != 8) + return 10; + const auto copied = indirect_buffer_view(&resource, std::uint64_t{0}, std::uint64_t{32}, 8u, 7u, false, 1); + if (copied.records != 7 || copied.upload || copied.source != 1 || copied.resource != &resource) + return 11; + return 0; +} diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 9ed3372a55..21e44224d5 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1008,7 +1008,9 @@ def raw_descriptor_alu(base, syms, constants): return ('descnum', 'stride', word) if plain and field == 2 and base == 's_mul_i32': if syms[other] in (('descnum', kind, desc_word(word, word[3] - 1)) for kind in ('stride', 'stride_min1')): - return word + ('byte_count',) + # The clamp (s_max_u32 with 1) makes a stride of 0 count as one byte per record. The extra tag is + # how a pixel load bounds the read by that product; stores accept either tag. + return word + (('byte_count', 'min1') if syms[other][1] == 'stride_min1' else ('byte_count',)) if field == 3: if plain and base == 's_and_b32' and constants[other] == 0xcfffffff: return word + ('oob0',) @@ -1017,6 +1019,17 @@ def raw_descriptor_alu(base, syms, constants): return None +def raw_conversion_shapes(loaded): + """The two four-word forms of one descriptor load after the structured-to-raw conversion. + + Word 1 has its stride cleared, word 2 is the byte count (the plain product, or the product after the stride + was clamped to at least 1), and word 3 selects raw out-of-range behavior.""" + cleared = loaded[1] + ('stride0',) + oob = loaded[3] + ('oob3',) + return ((loaded[0], cleared, loaded[2] + ('byte_count',), oob), + (loaded[0], cleared, loaded[2] + ('byte_count', 'min1'), oob)) + + def smem_offset(tok): """The SMEM offset operand as a token: 'off' (no offset operand) is the literal 0, anything else unchanged.""" return '0' if tok == 'off' else tok @@ -6054,7 +6067,7 @@ def src_sym(t): d = dst[1] own = self.sym.get(d) raw = (raw_descriptor_alu(base, syms, [self.const_u32(t) for t in srcs]) - if getattr(self, 'kind', None) in ('cs', 'vs') and len(syms) == 2 else None) + if getattr(self, 'kind', None) in ('cs', 'vs', 'ps') and len(syms) == 2 else None) if base in ('s_mov_b32', 's_mov_b64'): self.sym[d] = syms[0] if pair: @@ -7209,7 +7222,7 @@ def op_s_buffer_load_dwordx8(self, ops, mods): def op_s_buffer_load_dwordx16(self, ops, mods): self.op_s_buffer_load_dword(ops, mods, 16) - def buffer_address(self, ops, mods, *, is_formatted=False): + def buffer_address(self, ops, mods, *, is_formatted=False, raw_conversion_ok=None): # MUBUF and MTBUF share the same address calculation: optional index * stride (idxen), # optional byte VGPR offset (offen), scalar byte offset (soffset) and 12-bit immediate # offset. Cache-policy flags (glc, slc, dlc) do not change the loaded bytes; lds, tfe @@ -7224,8 +7237,11 @@ def buffer_address(self, ops, mods, *, is_formatted=False): raise Unsupported('buffer load with %d operands, expected 4' % len(ops)) idxen, offen = 'idxen' in mods, 'offen' in mods what = 'indexed load' if idxen else 'buffer load' + # A typed MTBUF load does not use the raw bound (raw_conversion_ok is False there). Leaving the + # conversion accepted would read past NUM_RECORDS * stride as an ordinary Load. + allow_raw = (not idxen) if raw_conversion_ok is None else bool(raw_conversion_ok) and not idxen if not is_formatted: - key = self.load_descriptor(ops[2], what, stride0_ok=not idxen, raw_conversion_ok=not idxen) + key = self.load_descriptor(ops[2], what, stride0_ok=not idxen, raw_conversion_ok=allow_raw) else: key = self.descriptor(ops[2]) if isinstance(key[0], tuple) and key[0][:2] == ('resheap', 'per_lane') and idxen: @@ -7267,6 +7283,7 @@ def buffer_address(self, ops, mods, *, is_formatted=False): if soffset is not None: terms.append(soffset) terms.append('%d' % offset) + self.address_terms = terms return buf, ' + '.join(terms) def op_buffer_load_dword(self, ops, mods, count=1): @@ -7277,9 +7294,30 @@ def op_buffer_load_dword(self, ops, mods, count=1): raise Unsupported('buffer load with 0 operands, expected 4') dst = reg_range(ops[0]) buf, address = self.buffer_address(ops, mods) - self.emit('a = %s;' % address) - for i in range(count): - self.set_v(dst[1] + i, '%s.Load(a + %d)' % (buf, 4 * i)) + # A pixel load through the full conversion is a raw byte-address read. The hardware compares the address + # against the converted NUM_RECORDS, which is the 32-bit product of the original record count and stride + # (at least 1 when the extract was clamped). The entry constants are that view's stride and record count. + # Each term of the address is added first: a wrapped sum is out of range even when the truncated value + # would have landed inside the buffer. + bound = getattr(self, 'raw_load_bound', None) if getattr(self, 'kind', None) == 'ps' else None + if bound: + index = self.pipe.resources[bound[0]]['index'] + stride = self.pipe.ud(('stride', index)) + records = self.pipe.ud(('numrecords', index)) + factor = 'max(ud%d, 1u)' % stride if bound[1] else 'ud%d' % stride + self.emit('{ uint lim = %s * ud%d; uint base = 0; bool ok = true;' % (factor, records)) + for term in self.address_terms: + self.emit('ok = ok && base + (%s) >= base; base += %s;' % (term, term)) + self.emit('a = base;') + for i in range(count): + end = 4 * (i + 1) + self.set_v(dst[1] + i, + '(ok && a + %du >= a && a + %du <= lim) ? %s.Load(a + %d) : 0u' % (end, end, buf, 4 * i)) + self.emit('}') + else: + self.emit('a = %s;' % address) + for i in range(count): + self.set_v(dst[1] + i, '%s.Load(a + %d)' % (buf, 4 * i)) def op_buffer_load_dwordx2(self, ops, mods): self.op_buffer_load_dword(ops, mods, 2) @@ -7412,7 +7450,10 @@ def load_descriptor(self, tok, what, *, stride0_ok=False, raw_conversion_ok=Fals and word 3 OOB_SELECT set to raw mode (`oob3` via 0x30000000). Permitted when the load is non-indexed and the resulting byte range is validated. Any other scalar ALU modifications or unproven overwrites raise Unsupported. + A pixel-stage load that matches the full conversion records raw_load_bound so the read can be limited + to the converted byte count. """ + self.raw_load_bound = None key = self.descriptor(tok) rsrc = reg_range(tok) first = self.sym.get(rsrc[1]) if rsrc and rsrc[0] == 's' and rsrc[2] - rsrc[1] == 3 else None @@ -7424,7 +7465,13 @@ def load_descriptor(self, tok, what, *, stride0_ok=False, raw_conversion_ok=Fals cleared = loaded[1] + ('stride0',) valid = valid or actual == (loaded[0], cleared, *loaded[2:]) if not valid and raw_conversion_ok: - valid = actual == (loaded[0], cleared, loaded[2] + ('byte_count',), loaded[3] + ('oob3',)) + shapes = raw_conversion_shapes(loaded) + if actual == shapes[0]: + valid = True + self.raw_load_bound = (key, False) + elif actual == shapes[1]: + valid = True + self.raw_load_bound = (key, True) if (not valid or key in getattr(self.pipe, 'other_modified', ()) or (key in getattr(self.pipe, 'modified', ()) and not stride0_ok)): raise Unsupported('%s through a modified descriptor' % what) @@ -7445,7 +7492,7 @@ def store_descriptor(self, tok, words, what, stride0_ok=False, raw_conversion_ok cleared = loaded[1] + ('stride0',) valid = valid or actual == (loaded[0], cleared, *loaded[2:]) if not valid and raw_conversion_ok: - valid = actual == (loaded[0], cleared, loaded[2] + ('byte_count',), loaded[3] + ('oob3',)) + valid = actual in raw_conversion_shapes(loaded) if (not valid or key in getattr(self.pipe, 'other_modified', ()) or (key in getattr(self.pipe, 'modified', ()) and not stride0_ok)): raise Unsupported('%s through a modified descriptor' % what) @@ -7663,7 +7710,8 @@ def tbuffer(self, ops, mods, count): dst = reg_range(ops[0]) formats = [m for m in mods if m.startswith('format:')] fmt = formats[0][8:-1] if formats else 'BUF_FMT_8_UNORM' # the disassembler omits the default format - buf, address = self.buffer_address(ops, [m for m in mods if not m.startswith('format:')]) + buf, address = self.buffer_address( + ops, [m for m in mods if not m.startswith('format:')], raw_conversion_ok=False) self.emit('a = %s;' % address) self.load_format(fmt, buf, dst[1], count)