diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 3d3ff1750..6692ac591 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -85,6 +85,8 @@ jobs: (["tests/startup_image_2d_array_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_sample_a16_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_sample_a16_check.py", "decode", "libLLVM-15.so.1"], {}), + (["tests/startup_image_load_d16_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_image_load_d16_check.py", "decode", "libLLVM-15.so.1"], {}), (["tests/startup_flat_param_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_bit_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_mad_check.py", "binary", "llvm-mc-15"], {}), @@ -203,6 +205,7 @@ jobs: tests/startup_gfx2hlsl_operand_count_check.py \ tests/startup_image_2d_array_check.py \ tests/startup_image_sample_a16_check.py \ + tests/startup_image_load_d16_check.py \ tests/startup_host_cpu_check.py \ tests/startup_live_telemetry_check.py \ tests/startup_gfx2hlsl_cvt_alu_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 4ab50f4b8..861793cd7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -152,6 +152,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py ./out/pe-env/bin/python -B tests/startup_image_2d_array_check.py ./out/pe-env/bin/python -B tests/startup_image_sample_a16_check.py +./out/pe-env/bin/python -B tests/startup_image_load_d16_check.py ./out/pe-env/bin/python -B tests/startup_host_cpu_check.py ./out/pe-env/bin/python -B tests/startup_live_telemetry_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_capture_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index d9818b021..6c97d0c19 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1560,6 +1560,13 @@ target_compile_features(startup_export_write_mask_check PRIVATE cxx_std_17) add_test(NAME startup_export_write_mask COMMAND startup_export_write_mask_check) add_test(NAME startup_export_write_mask_shared_blend_control COMMAND startup_export_write_mask_check --mutate shared-blend) set_tests_properties(startup_export_write_mask_shared_blend_control PROPERTIES WILL_FAIL TRUE) +# Bound SRV format classification and 'd16srv' manifest parsing for D16 image_load (#2023). +add_executable(startup_d16_image_format_check tests/startup_d16_image_format_check.cpp) +target_include_directories(startup_d16_image_format_check PRIVATE src) +target_compile_features(startup_d16_image_format_check PRIVATE cxx_std_17) +add_test(NAME startup_d16_image_format COMMAND startup_d16_image_format_check) +add_test(NAME startup_d16_image_format_accept_uint_control COMMAND startup_d16_image_format_check --mutate accept-uint) +set_tests_properties(startup_d16_image_format_accept_uint_control PROPERTIES WILL_FAIL TRUE) # Composite provenance (#1628): one VS and two pixel shaders from one HLSL file. set(startup_composite_provenance_headers "") foreach(stage IN ITEMS "vs_6_0;vs_main;vs" "ps_6_0;ps_fill;fill" "ps_6_0;ps_composite;composite") @@ -2585,6 +2592,15 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_image_sample_a16_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl level-zero D16 image_load narrowing and pairwise packing (#2023). + add_test(NAME startup_image_load_d16_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_load_d16_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_image_load_d16_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_load_d16_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_image_load_d16_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl flat parameters keep the exported words (#1259): translation controls, then a desktop # draw of the translated pair with FXC 5_1 (the --pending path) and DXC 6_0. add_test(NAME startup_flat_param_controls COMMAND "${INTAKE_PYTHON}" -B @@ -2807,6 +2823,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_buffer_srv_check.py" "$" "${backend}") set_tests_properties(startup_address_buffer_srv_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_d16_srv_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_d16_srv_check.py" + "$" "${backend}") + set_tests_properties(startup_d16_srv_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) add_test(NAME startup_frame_copy_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_frame_copy_check.py" "$" ${backend}) diff --git a/docs/experiments.md b/docs/experiments.md index a0a10299e..862dde20b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -11960,7 +11960,7 @@ For plain 2D `image_load`, the startup translator reads `a16` coordinates from t halves of one VGPR and emits `Texture2D.Load` at mip zero. The synthetic case in `python -B tests/startup_image_load_mip_check.py` packs x=1 and y=2 into v0 and assigns 63 to v1, which the old lowering used as y. Full-width loads still accept cache-policy flags. Plain loads refuse an empty -`dmask`, `r128`, `lwe`, `d16`, `tfe` and reserved bits. The fixture also checks that 3D `a16` and a +`dmask`, `r128`, `lwe`, `tfe` and reserved bits. The fixture also checks that 3D `a16` and a patched 2D `a16` instruction carrying an unexpected NSA extension are refused, and that the runtime and offline cache keys use the same revision. The check verifies translation on the CPU. @@ -11975,6 +11975,17 @@ cmake --build --preset dev --target offscreen_check d3d12_xs_shim ctest --preset dev --no-tests=error -R '^startup_image_sample_a16_(controls|warp|hardware)$' -V ``` +## Startup translator: level-zero D16 image loads + +For level-zero `image_load` with `d16` on 2D (including `a16` and NSA), 3D and 2D-array resources, `tools/startup/gfx2hlsl.py` narrows each enabled `dmask` component of the `Load` result to IEEE binary16 and packs the halves pairwise into `ceil(popcount(dmask) / 2)` consecutive VGPRs (low half first, high half second). HLSL `f32tof16` truncates toward zero on WARP (lowering 31,740 of the 65,536 `DXGI_FORMAT_R16_UNORM` depth values by 1 ULP relative to RDNA hardware), while narrowing an intermediate binary32 `Load` value still double-rounds `R16_UNORM` at `0xffaf` (`0x3bfe` instead of `0x3bfd`) and `0xffef` (`0x3c00` instead of `0x3bff`). `gfx2hlsl.py` therefore emits both an integer binary32-to-binary16 round-to-nearest-even helper (`pack16_rne`, quieting NaNs while preserving sign) and an exact `UNORM16` helper (`pack16_unorm16`, recovering `u = uint(saturate(v) * 65535.0 + 0.5)` and rounding `u / 65535` directly to binary16), selected per SRV via `udsrc d16unorm16 `, and writes `d16srv exact` to `.txt`. Before drawing, `src/startup_stubs/d3d12_draw.inl` (`src/startup_stubs/d16_image_format.h`) validates the bound view's effective `DXGI_FORMAT` against the 14 independently GPU-verified exact formats (five 32-bit float views, six 8-bit `UNORM` views, and three 16-bit `UNORM` views), setting `d16unorm16` to `1` for `R16*_UNORM` and `0` for the exact binary32/`UNORM8` formats while refusing integer (`UINT`/`SINT`), typeless, depth-stencil-only, `SNORM16`, `R24_UNORM`, `SRGB`, block-compressed, packed-target stand-in, console extension, null-resource and unbound views. When `popcount(dmask)` is odd (`1` or `3`), bits `31:16` of the final destination VGPR are hardware-undefined on RDNA 2; `gfx2hlsl.py` tracks those registers across expressions and basic blocks and refuses whole-word reads unless consumed through a low-16-bit operation (`v_cvt_f32_f16`, `v_cvt_f32_ubyte0`/`1`, `SDWA` `BYTE_0`/`BYTE_1`/`WORD_0`, `v_and_b32` with constant mask `<= 0xffff`, `v_cmp_class_f16`/`v_cmpx_class_f16`, or `v_fma_mix*` half operands). Pipelines without `image_load` `d16` omit all helpers and `d16srv` lines; `image_load_mip` with `d16`, sampler MIMG forms with `d16`, 1D and cube dimensions, 3D or 2D-array `a16`, `tfe`, `lwe`, `r128`, set reserved MIMG bits, an empty `dmask`, and mismatched register counts remain refused. + +Verified on commit base `009153b7` on Windows 11 26H2 (build `26300.9974`) across Microsoft Basic Render Driver (`1414:008c`, driver `10.0.26100.9818`) and AMD Radeon RX 9070 XT (`1002:7550`, driver `32.0.32029.2010`), D3D12 debug layer enabled (`debug_errors=0 debug_warnings=0`): exhaustive GPU probes across all 65,536 `DXGI_FORMAT_R16_UNORM` texels (DXC `cs_6_2` and FXC `cs_5_0`) and all 256 `DXGI_FORMAT_R8_UNORM` texels match RDNA 2 hardware `d16` loads with 0 mismatches (`65,536 / 65,536` and `256 / 256`, including `0xffaf -> 0x3bfd` and `0xffef -> 0x3bff`). In `offscreen_check --startup-image-load-d16` (DXC `ps_6_0` and FXC `ps_5_1`), fixtures A and B match all 128 output words (32 pixels) on `8x2` `R16_UNORM` and `8x2` `R32G32B32A32_FLOAT` textures, remain invariant when `0xdead0000` is injected into bits `31:16` of the odd-`dmask` registers, and reject eight mutated HLSL controls (truncation toward zero, binary32 `double_round` on `0xffaf`/`0xffef`, unpacked 32-bit `U(t.x)`, swapped low/high halves, dropped `<< 16` shift, dropped `a16` coordinate unpack, ignored NSA register list, and unmasked odd-`dmask` upper half). Through `d3d12_xs.dll` (`startup_d16_srv_{warp,hardware}`), `R16_UNORM` (`0xffef -> 0x3bff`), `R32_FLOAT` (`0x3f7ff000 -> 0x3c00`) and `R16_TYPELESS` viewed as `R16_UNORM` (`0xaaaa -> 0x3955`) dispatch the exact per-SRV mode on one PSO while `R16_UINT`, `R16_SNORM`, null-resource and unwritten views are refused and malformed `d16srv` manifests are rejected. + +```powershell +cmake --build --preset dev --target offscreen_check startup_d16_image_format_check startup_stream_consumer +ctest --preset dev --no-tests=error -R '^startup_(image_load_d16_(controls|warp|hardware)|d16_image_format.*|d16_srv_(warp|hardware))$' -V +``` + ## Startup translator: pixel depth export The startup translator emits `SV_Depth` for an uncompressed `exp mrtz vN, off, off, off` in a straight-line pixel shader that still uses its entry execution mask. Color exports in the same shader keep their `SV_Target` outputs. Additional MRTZ channels, packed exports, multiple depth exports, branches and changes to the execution mask before the depth export are refused. diff --git a/src/startup_stubs/d16_image_format.h b/src/startup_stubs/d16_image_format.h new file mode 100644 index 000000000..6fff023a5 --- /dev/null +++ b/src/startup_stubs/d16_image_format.h @@ -0,0 +1,107 @@ +// Experimental (docs/startup-runtime.md): bound SRV format validation and conversion mode selection +// for translated shaders that execute level-zero MIMG image_load with the d16 modifier (#2023, item D). +// +// gfx2hlsl writes 'd16srv exact' and an entry constant 'udsrc d16unorm16 ' when SRV +// is read by image_load ... d16. Only formats independently verified exact against RDNA 2 D16 +// image_load are accepted: +// - D16SrvMode::float_exact (d16unorm16 = 0): 32-bit float views (including R32_FLOAT_X8X24_TYPELESS) +// and 8-bit UNORM views (256/256 exact under pack16_rne(Texture*.Load)). +// - D16SrvMode::unorm16 (d16unorm16 = 1): 16-bit UNORM views (65,536/65,536 exact when recovering the +// 16-bit code from Load and rounding u / 65535 directly to binary16, avoiding binary32 double-rounding +// at 0xffaf and 0xffef). +// Integer (UINT/SINT), typeless, depth-stencil-only, SNORM16, SRGB, block-compressed, packed-target +// stand-in, console extension and unknown/unbound views are refused. +#pragma once + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include + +#include +#include +#include + +namespace x2w_startup { + +enum class D16SrvMode : std::uint8_t { + refused = 0, + float_exact = 1, + unorm16 = 2, +}; + +inline constexpr D16SrvMode d16_srv_mode(DXGI_FORMAT format) +{ + switch (format) { + case DXGI_FORMAT_R32G32B32A32_FLOAT: + case DXGI_FORMAT_R32G32B32_FLOAT: + case DXGI_FORMAT_R32G32_FLOAT: + case DXGI_FORMAT_R32_FLOAT: + case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: + case DXGI_FORMAT_R8G8B8A8_UNORM: + case DXGI_FORMAT_R8G8_UNORM: + case DXGI_FORMAT_R8_UNORM: + case DXGI_FORMAT_A8_UNORM: + case DXGI_FORMAT_B8G8R8A8_UNORM: + case DXGI_FORMAT_B8G8R8X8_UNORM: + return D16SrvMode::float_exact; + case DXGI_FORMAT_R16G16B16A16_UNORM: + case DXGI_FORMAT_R16G16_UNORM: + case DXGI_FORMAT_R16_UNORM: + return D16SrvMode::unorm16; + default: + return D16SrvMode::refused; + } +} + +inline constexpr bool d16_exact_srv_format(DXGI_FORMAT format) +{ + return d16_srv_mode(format) != D16SrvMode::refused; +} + +struct D16ImageSrvs { + std::uint32_t exact_mask = 0; + + // Parses 'd16srv exact' for 0 <= index < 32 without leading zeroes or duplicates. + bool read_manifest_line(std::string_view line) + { + constexpr std::string_view prefix = "d16srv "; + constexpr std::string_view suffix = " exact"; + if (line.size() <= prefix.size() + suffix.size() || + line.substr(0, prefix.size()) != prefix || + line.substr(line.size() - suffix.size()) != suffix) + return false; + const std::string_view digits = line.substr(prefix.size(), line.size() - prefix.size() - suffix.size()); + if (digits.empty() || digits.size() > 2 || (digits.size() == 2 && digits[0] == '0')) + return false; + unsigned index = 0; + for (char c : digits) { + if (c < '0' || c > '9') return false; + index = index * 10 + static_cast(c - '0'); + } + if (index >= 32 || (exact_mask & (std::uint32_t{1} << index))) return false; + exact_mask |= std::uint32_t{1} << index; + return true; + } + + bool any() const { return exact_mask != 0; } + + bool requires_exact(unsigned index) const + { + return index < 32 && (exact_mask & (std::uint32_t{1} << index)) != 0; + } + + template + bool valid_for_srvs(const SrvVec& srvs) const + { + if (!exact_mask) return true; + if (srvs.size() < 32 && (exact_mask >> srvs.size()) != 0) return false; + for (std::size_t i = 0; i < srvs.size() && i < 32; ++i) { + if (requires_exact(static_cast(i)) && (srvs[i].kind < 1 || srvs[i].kind > 4)) + return false; + } + return true; + } +}; + +} // namespace x2w_startup diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 4165e9377..3bb9512a5 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -11,7 +11,7 @@ struct Translation { struct Srv { int kind, source, a, b; }; // kind 0 buffer, 1 2D texture, 2 2D array, 3 3D texture, 4 1D texture; 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 }; + enum UdKind { rect, base_vertex, start_instance, root_constant, stride, mrt_bits, d16_unorm16 }; struct Ud { int kind, a, b; }; int state = 0; // 1 ready, 2 unavailable ULONGLONG retry_manifest_at = 0; // Only an absent manifest can become ready on a later draw. @@ -19,6 +19,7 @@ struct Translation { std::vector uds; x2w_startup::TranslatedSamplers samplers; x2w_startup::ExportWriteMasks write_masks; // manifest 'wmask': channels each export leaves unwritten (#1674) + x2w_startup::D16ImageSrvs d16_srvs; // manifest 'd16srv': texture views that must match proven D16 formats (#2023) ID3DBlob* vs = nullptr; ID3DBlob* ps = nullptr; ID3D12RootSignature* root = nullptr; @@ -164,6 +165,7 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) 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, "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 (std::sscanf(line.c_str(), "srv %d %15s %15s %d %d", &i, kind, source, &x, &y) >= 4) { @@ -176,6 +178,11 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) log("x2w-draw invalid write mask manifest line for %016llx: %s", tr.key, line.c_str()); return; } + } else if (line.compare(0, 7, "d16srv ") == 0) { + if (!tr.d16_srvs.read_manifest_line(line)) { + log("x2w-draw invalid d16srv manifest line for %016llx: %s", tr.key, line.c_str()); + return; + } } else if (!tr.samplers.read_manifest_line(line.c_str())) { log("x2w-draw invalid sampler heap manifest for %016llx", tr.key); return; @@ -185,7 +192,12 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) log("x2w-draw RTV manifest missing for %016llx", tr.key); return; } - if (tr.uds.empty() || tr.uds.size() > 32 || tr.srvs.size() > 32) return; + if (tr.uds.empty() || tr.uds.size() > 32 || tr.srvs.size() > 32 || !tr.d16_srvs.valid_for_srvs(tr.srvs)) return; + for (const Translation::Ud& ud : tr.uds) { + if (ud.kind == Translation::d16_unorm16 && + (ud.a < 0 || static_cast(ud.a) >= tr.srvs.size() || !tr.d16_srvs.requires_exact(static_cast(ud.a)))) + return; + } if (!cache_path(path, L"", tr.key, L".vs.cso") || FAILED(D3DReadFileToBlob(path, &tr.vs))) return; if (!cache_path(path, L"", tr.key, L".ps.cso") || FAILED(D3DReadFileToBlob(path, &tr.ps))) return; const HRESULT hr = x2w_startup::create_translated_root(device_of(the_device), static_cast(tr.uds.size()), @@ -930,6 +942,70 @@ void draw_dump_flush() log("x2w-draw per-draw dump: %d of %zu completed target copies written to %s", written, completed.size(), folder); } +bool d16_srvs_ready(const Translation& tr, const Pass& pass, std::uint32_t (&d16_unorm16)[32]) +{ + if (!tr.d16_srvs.any()) return true; + const auto refuse = [&](UINT slot, const char* reason, int detail) { + static LONG refused; + if (first_calls(refused, 6)) + log("x2w-draw %016llx srv %u: d16 exact refused (%s %d)", tr.key, slot, reason, detail); + return false; + }; + for (UINT i = 0; i < tr.srvs.size(); ++i) { + if (!tr.d16_srvs.requires_exact(i)) continue; + const Translation::Srv& srv = tr.srvs[i]; + if (srv.kind < 1 || srv.kind > 4 || srv.source != 0 || srv.a < 0 || srv.a >= 16 || srv.b < 0) + return refuse(i, "non-table texture binding", srv.kind); + const auto dimension = srv.kind == 1 ? D3D12_SRV_DIMENSION_TEXTURE2D : + srv.kind == 2 ? D3D12_SRV_DIMENSION_TEXTURE2DARRAY : + srv.kind == 4 ? D3D12_SRV_DIMENSION_TEXTURE1D : D3D12_SRV_DIMENSION_TEXTURE3D; + const u64 entry = pass.view_tables[srv.a].record(static_cast(srv.b), 32); + std::uint32_t words[8] = {}; + if (!entry || !x2w_local::readable(reinterpret_cast(entry), 32)) + return refuse(i, "unreadable table entry", srv.a); + std::memcpy(words, reinterpret_cast(entry), 32); + if (words[0] != view_token_magic) return refuse(i, "missing view token", 0); + ViewRecord record{}; + bool known = false; + AcquireSRWLockShared(¬e_lock); + known = words[1] < view_records().size(); + if (known) record = view_records()[words[1]]; + ReleaseSRWLockShared(¬e_lock); + if (!known || record.slot != 18) return refuse(i, "view slot", static_cast(record.slot)); + Wrapper* resource = as_wrapper(reinterpret_cast(record.resource)); + ID3D12Resource* texture = sampled_address_texture(resource); + if (!texture) return refuse(i, "missing texture resource", 0); + if (x2w_startup::packed_stand_in_of(texture) != DXGI_FORMAT_UNKNOWN) + return refuse(i, "packed stand-in resource", static_cast(x2w_startup::packed_stand_in_of(texture))); + const D3D12_RESOURCE_DESC tex_desc = texture->GetDesc(); + if (srv.kind == 4 && (tex_desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE1D || tex_desc.DepthOrArraySize != 1)) + return refuse(i, "1D resource mismatch", static_cast(tex_desc.Dimension)); + const auto* original = resource_info(resource); + DXGI_FORMAT effective = original ? original->console.Format : tex_desc.Format; + if (record.desc_bytes >= 40) { + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + std::memcpy(&desc, record.desc, 40); + if (desc.ViewDimension != dimension) + return refuse(i, "view dimension", static_cast(desc.ViewDimension)); + if (desc.Format != DXGI_FORMAT_UNKNOWN) effective = desc.Format; + } else if (record.desc_bytes == 0) { + const bool dim_ok = + (srv.kind == 1 && tex_desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && tex_desc.DepthOrArraySize == 1) || + (srv.kind == 2 && tex_desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D) || + (srv.kind == 3 && tex_desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) || + (srv.kind == 4 && tex_desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && tex_desc.DepthOrArraySize == 1); + if (!dim_ok) return refuse(i, "default view dimension", static_cast(tex_desc.Dimension)); + } else { + return refuse(i, "truncated view desc", static_cast(record.desc_bytes)); + } + const auto mode = x2w_startup::d16_srv_mode(effective); + if (mode == x2w_startup::D16SrvMode::refused) + return refuse(i, "format", static_cast(effective)); + d16_unorm16[i] = mode == x2w_startup::D16SrvMode::unorm16 ? 1u : 0u; + } + return true; +} + bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UINT start, INT base_vertex, UINT start_instance) { auto* list = recording(self); @@ -939,7 +1015,12 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI AcquireSRWLockExclusive(&draw_lock); BoundPipeline* bound = translation_for(pass.pipeline); Translation* tr = bound ? translation_for_targets(bound->translation, pass) : nullptr; - ID3D12PipelineState* pipeline = tr && tr->state == 1 && ensure_draw_heap(self->own().list_device) ? pipeline_for(*bound, *tr, pass) : nullptr; + std::uint32_t d16_unorm16[32] = {}; + if (!tr || tr->state != 1 || !d16_srvs_ready(*tr, pass, d16_unorm16)) { + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + ID3D12PipelineState* pipeline = ensure_draw_heap(self->own().list_device) ? pipeline_for(*bound, *tr, pass) : nullptr; if (!pipeline || (tr->samplers.heap && !prepare_draw_sampler_heap(pass, list, tr->samplers.reserved_fallback))) { ReleaseSRWLockExclusive(&draw_lock); return false; @@ -1175,7 +1256,8 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI : ud.kind == Translation::base_vertex ? static_cast((indexed ? base_vertex : static_cast(start)) - vertex_first) : 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] : 0; + : ud.kind == Translation::stride && ud.a >= 0 && ud.a < 32 ? strides[ud.a] + : ud.kind == Translation::d16_unorm16 && ud.a >= 0 && ud.a < 32 ? d16_unorm16[ud.a] : 0; } // A desktop list with no viewport or scissor draws nothing: cover the first render target unless the title set its own. if (pass.target0 && (!pass.viewport_set || !pass.scissor_set)) { diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 0859fd3cd..34b915ee5 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -21,6 +21,7 @@ #include "startup_stubs/translated_sampler_bindings.h" #include "startup_stubs/export_write_mask.h" #include "startup_stubs/depth_state_apply.h" +#include "startup_stubs/d16_image_format.h" #include "startup_stubs/heap_indexed_root.h" #include "startup_stubs/bc7_4k_s.h" #include "startup_stubs/bc64_chain.h" diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index ec622933d..303325cfd 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -24,6 +24,8 @@ float check_startup_sampler_heap(ID3D12Device* device, const char* vertex_path, void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const char* pixel_path, float z, float color[4], const char* sampler_line, bool array = false, UINT levels = 1, bool one_dimensional = false, bool two_dimensional = false); +void check_startup_image_load_d16(ID3D12Device* device, const char* vertex_path, const char* pixel_path, + bool depth16, std::uint32_t words[64]); void check_startup_flat_param(ID3D12Device* device, const char* vertex_path, const char* pixel_path, std::uint32_t* words, UINT width = 1, UINT height = 1); void dump_raw_uav(ID3D12Device* device, const char* shader_path, const char* groups, diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index ca6ee27e4..d24e46b9b 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -1226,6 +1226,40 @@ OperationResult run_startup_image_3d(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } +// --startup-image-load-d16 : draws an 8x2 full-screen +// pair to an R32G32B32A32_UINT target against an 8x2 R16_UNORM or R32G32B32A32_FLOAT source texture and +// compares all 64 little-endian words with expected.bin. +OperationResult run_startup_image_load_d16(const OperationContext& ctx) +{ + const bool depth16 = std::strcmp(ctx.argv[3], "r16_unorm") == 0; + if (!depth16 && std::strcmp(ctx.argv[3], "rgba32f") != 0) + return {OutcomeKind::fail, "image_load d16 source mode must be r16_unorm or rgba32f"}; + std::uint32_t expected[64]{}; + std::ifstream file(ctx.argv[6], std::ios::binary); + file.read(reinterpret_cast(expected), sizeof(expected)); + if (!file || file.peek() != std::char_traits::eof()) + return {OutcomeKind::fail, "expected file does not hold 64 words"}; + std::uint32_t actual[64]{}; + check_startup_image_load_d16(ctx.device, ctx.argv[4], ctx.argv[5], depth16, actual); + unsigned differing = 0; + for (unsigned i = 0; i < 16; ++i) { + const std::uint32_t* want = &expected[i * 4]; + const std::uint32_t* got = &actual[i * 4]; + if (std::memcmp(want, got, 4 * sizeof(std::uint32_t)) == 0) continue; + if (differing++ == 0) { + std::fprintf(stderr, + "startup_image_load_d16 (%s) pixel (%u,%u) mismatch: expected %08x,%08x,%08x,%08x actual %08x,%08x,%08x,%08x\n", + ctx.argv[3], i % 8, i / 8, want[0], want[1], want[2], want[3], got[0], got[1], got[2], got[3]); + } + } + if (differing) { + std::fprintf(stderr, "%u of 16 pixels differ\n", differing); + return {OutcomeKind::fail, "image_load d16 readback differs"}; + } + std::printf("startup_image_load_d16 %s: all 16 pixels (64 words) matched\n", ctx.argv[3]); + return {OutcomeKind::pass, nullptr}; +} + OperationResult run_startup_packed_position(const OperationContext& ctx) { constexpr UINT width = 13, height = 7; @@ -1418,6 +1452,7 @@ const OperationSpec kOperations[] = { {"--startup-image-3d", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-2d-array", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-2d-array-mips", 7, 8, nullptr, kNoGate, run_startup_image_3d}, + {"--startup-image-load-d16", 7, 7, nullptr, kNoGate, run_startup_image_load_d16}, {"--startup-packed-position", 5, 5, nullptr, kNoGate, run_startup_packed_position}, {"--startup-flat-param", 6, 6, nullptr, kNoGate, run_startup_flat_param}, {"--startup-pixel-words", 8, 8, nullptr, kNoGate, run_startup_pixel_words}, diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index 9f1d3950f..4bb3598e2 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -531,3 +531,98 @@ int draw_single_element_srvs(void* guest, void* list) publish(aligned, view_of(aligned, ptr(memory[0]))); draw(7); return 0; } + +// Exercise runtime bound-SRV format validation and d16unorm16 mode selection on a shader carrying +// 'd16srv 0 exact' and 'udsrc 3 d16unorm16 0' (#2023): +// - col 0: R16_UNORM (0xffef) + explicit R16_UNORM SRV -> d16unorm16=1 gives exact 0x3bff (yellow 255, 255, 0) +// - col 1: R32_FLOAT (0x3f7ff000 = binary32(0xffef/65535)) + default SRV -> d16unorm16=0 gives 0x3c00 (red 255, 0, 0) +// - col 2: R16_TYPELESS (0xaaaa) + explicit R16_UNORM SRV -> d16unorm16=1 gives 0x3955 (170, 0, 0) +// - cols 3..6: R16_UINT, R16_SNORM, null-resource SRV and unwritten descriptor -> refused (clear blue 0, 0, 255) +// - col 7: rebind R16_UNORM (0xffef) + default SRV -> d16unorm16=1 recovers cleanly (yellow 255, 255, 0) +int draw_d16_srvs(ID3D12Device* desktop, void* guest, void* list) +{ + D3D12_RESOURCE_DESC probe16{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 1, 1, 1, 1, + DXGI_FORMAT_R16_UNORM, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + D3D12_RESOURCE_DESC probe32 = probe16; + probe32.Format = DXGI_FORMAT_R32_FLOAT; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp16{}, fp32{}; + UINT64 total16 = 0, total32 = 0; + desktop->GetCopyableFootprints(&probe16, 0, 1, 0, &fp16, nullptr, nullptr, &total16); + desktop->GetCopyableFootprints(&probe32, 0, 1, 0, &fp32, nullptr, nullptr, &total32); + if (!total16 || total16 == ~UINT64{0} || !total32 || total32 == ~UINT64{0}) return 48; + + static std::array, 5> planes; + const DXGI_FORMAT resource_formats[5] = { + DXGI_FORMAT_R16_UNORM, + DXGI_FORMAT_R32_FLOAT, + DXGI_FORMAT_R16_TYPELESS, + DXGI_FORMAT_R16_UINT, + DXGI_FORMAT_R16_SNORM, + }; + const std::uint16_t u16_unorm = 0xffefu, u16_typeless = 0xaaaau, u16_uint = 200u, u16_snorm = 0x4000u; + const std::uint32_t f32_bits = 0x3f7ff000u; // binary32(65519 / 65535.0): rounds to 0x3c00 under pack16_rne + void* textures[5]{}; + for (int i = 0; i < 5; ++i) { + const bool is32 = i == 1; + const UINT64 total = is32 ? total32 : total16; + const UINT64 offset = is32 ? fp32.Offset : fp16.Offset; + planes[i].assign(static_cast(total), 0); + if (i == 0) std::memcpy(planes[i].data() + offset, &u16_unorm, sizeof(std::uint16_t)); + else if (i == 1) std::memcpy(planes[i].data() + offset, &f32_bits, sizeof(std::uint32_t)); + else if (i == 2) std::memcpy(planes[i].data() + offset, &u16_typeless, sizeof(std::uint16_t)); + else if (i == 3) std::memcpy(planes[i].data() + offset, &u16_uint, sizeof(std::uint16_t)); + else std::memcpy(planes[i].data() + offset, &u16_snorm, sizeof(std::uint16_t)); + auto desc = is32 ? probe32 : probe16; + desc.Format = resource_formats[i]; + if (FAILED(static_cast(invoke(guest, 133, ptr(planes[i].data()), ptr(&desc), + D3D12_RESOURCE_STATE_COMMON, 0, + ptr(&__uuidof(ID3D12Resource)), ptr(&textures[i]))))) + return 49; + } + + struct Extended { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word address, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 9, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + void* heap = nullptr; + if (FAILED(static_cast(invoke(guest, 14, ptr(&heap_desc), ptr(&__uuidof(ID3D12DescriptorHeap)), ptr(&heap))))) + return 42; + const Word cpu = invoke(heap, 9); + const Word gpu = invoke(heap, 10); + const UINT stride = static_cast(invoke(guest, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)); + if (!cpu || !gpu || stride < 32) return 42; + invoke(list, 32, 1, ptr(&heap)); + + const auto make_view = [](DXGI_FORMAT fmt) { + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = fmt; + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.Texture2D.MipLevels = 1; + return v; + }; + const auto v_unorm = make_view(DXGI_FORMAT_R16_UNORM); + const auto v_uint = make_view(DXGI_FORMAT_R16_UINT); + const auto v_snorm = make_view(DXGI_FORMAT_R16_SNORM); + + invoke(guest, 18, ptr(textures[0]), ptr(&v_unorm), cpu + 0 * stride); // 0: R16_UNORM (0xffef) + explicit R16_UNORM + invoke(guest, 18, ptr(textures[1]), 0, cpu + 1 * stride); // 1: R32_FLOAT (0x3f7ff000) + default SRV + invoke(guest, 18, ptr(textures[2]), ptr(&v_unorm), cpu + 2 * stride); // 2: R16_TYPELESS (0xaaaa) + explicit R16_UNORM + invoke(guest, 18, ptr(textures[2]), ptr(&v_uint), cpu + 3 * stride); // 3: R16_TYPELESS + explicit R16_UINT (refused) + invoke(guest, 18, ptr(textures[3]), 0, cpu + 4 * stride); // 4: R16_UINT + default SRV (refused) + invoke(guest, 18, ptr(textures[4]), ptr(&v_snorm), cpu + 5 * stride); // 5: R16_SNORM + explicit R16_SNORM (refused) + invoke(guest, 18, 0, ptr(&v_unorm), cpu + 6 * stride); // 6: null resource SRV (refused) + // Slot 7 is intentionally left unwritten (missing view token -> refused). + invoke(guest, 18, ptr(textures[0]), 0, cpu + 8 * stride); // 8: R16_UNORM (0xffef) + default SRV + + const auto draw_at = [&](LONG x, UINT slot) { + invoke(list, 36, 0, gpu + Word{slot} * stride); + const D3D12_RECT strip{x, 0, x + 1, 4}; + invoke(list, 22, 1, ptr(&strip)); + invoke(list, 12, 3, 1); + }; + for (UINT col = 0; col < 7; ++col) draw_at(static_cast(col), col); + draw_at(6, 7); // Also test unwritten descriptor slot on column 6; must stay clear. + draw_at(7, 8); // Rebind R16_UNORM default SRV on column 7; must draw yellow (0x3bff) cleanly. + return 0; +} diff --git a/tests/startup_d16_image_format_check.cpp b/tests/startup_d16_image_format_check.cpp new file mode 100644 index 000000000..89eb2031a --- /dev/null +++ b/tests/startup_d16_image_format_check.cpp @@ -0,0 +1,163 @@ +// Unit check for src/startup_stubs/d16_image_format.h (#2023, item D). +#include "startup_stubs/d16_image_format.h" + +#include +#include +#include + +namespace { +struct FakeSrv { + int kind; +}; + +constexpr DXGI_FORMAT kFloatExact[] = { + DXGI_FORMAT_R32G32B32A32_FLOAT, + DXGI_FORMAT_R32G32B32_FLOAT, + DXGI_FORMAT_R32G32_FLOAT, + DXGI_FORMAT_R32_FLOAT, + DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS, + DXGI_FORMAT_R8G8B8A8_UNORM, + DXGI_FORMAT_R8G8_UNORM, + DXGI_FORMAT_R8_UNORM, + DXGI_FORMAT_A8_UNORM, + DXGI_FORMAT_B8G8R8A8_UNORM, + DXGI_FORMAT_B8G8R8X8_UNORM, +}; + +constexpr DXGI_FORMAT kUnorm16[] = { + DXGI_FORMAT_R16G16B16A16_UNORM, + DXGI_FORMAT_R16G16_UNORM, + DXGI_FORMAT_R16_UNORM, +}; + +x2w_startup::D16SrvMode expected_mode(DXGI_FORMAT fmt) +{ + for (DXGI_FORMAT candidate : kFloatExact) { + if (candidate == fmt) return x2w_startup::D16SrvMode::float_exact; + } + for (DXGI_FORMAT candidate : kUnorm16) { + if (candidate == fmt) return x2w_startup::D16SrvMode::unorm16; + } + return x2w_startup::D16SrvMode::refused; +} +} // namespace + +int main(int argc, char** argv) +{ + const bool mutate_accept_uint = argc == 3 && std::strcmp(argv[1], "--mutate") == 0 && + std::strcmp(argv[2], "accept-uint") == 0; + if (argc != 1 && !mutate_accept_uint) return 2; + + const auto classify = [mutate_accept_uint](DXGI_FORMAT fmt) { + if (mutate_accept_uint && fmt == DXGI_FORMAT_R16_UINT) + return x2w_startup::D16SrvMode::float_exact; + return x2w_startup::d16_srv_mode(fmt); + }; + + for (unsigned raw = 0; raw <= 255; ++raw) { + const auto fmt = static_cast(raw); + const auto got = classify(fmt); + if (got != expected_mode(fmt)) { + std::fprintf(stderr, "format %u mode mismatch (%u)\n", raw, static_cast(got)); + return 1; + } + if (!mutate_accept_uint && x2w_startup::d16_exact_srv_format(fmt) != + (got != x2w_startup::D16SrvMode::refused)) { + std::fprintf(stderr, "format %u exact flag mismatch\n", raw); + return 1; + } + } + + // Explicit family checks: integer, typeless, depth-stencil-only, SNORM16, R24_UNORM, SRGB, BCn and console stand-ins must be refused. + constexpr DXGI_FORMAT kRefusedSpotChecks[] = { + DXGI_FORMAT_UNKNOWN, + DXGI_FORMAT_R32G32B32A32_TYPELESS, + DXGI_FORMAT_R32G32B32A32_UINT, + DXGI_FORMAT_R32G32B32A32_SINT, + DXGI_FORMAT_R16G16B16A16_TYPELESS, + DXGI_FORMAT_R16G16B16A16_SNORM, + DXGI_FORMAT_R16G16B16A16_UINT, + DXGI_FORMAT_R16G16B16A16_SINT, + DXGI_FORMAT_D32_FLOAT_S8X24_UINT, + DXGI_FORMAT_X32_TYPELESS_G8X24_UINT, + DXGI_FORMAT_R10G10B10A2_TYPELESS, + DXGI_FORMAT_R10G10B10A2_UNORM, + DXGI_FORMAT_R10G10B10A2_UINT, + DXGI_FORMAT_R8G8B8A8_TYPELESS, + DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, + DXGI_FORMAT_R8G8B8A8_SNORM, + DXGI_FORMAT_R8G8B8A8_UINT, + DXGI_FORMAT_R8G8B8A8_SINT, + DXGI_FORMAT_R16G16_SNORM, + DXGI_FORMAT_R32_TYPELESS, + DXGI_FORMAT_D32_FLOAT, + DXGI_FORMAT_R32_UINT, + DXGI_FORMAT_R32_SINT, + DXGI_FORMAT_D24_UNORM_S8_UINT, + DXGI_FORMAT_R24_UNORM_X8_TYPELESS, + DXGI_FORMAT_X24_TYPELESS_G8_UINT, + DXGI_FORMAT_R16_TYPELESS, + DXGI_FORMAT_D16_UNORM, + DXGI_FORMAT_R16_UINT, + DXGI_FORMAT_R16_SNORM, + DXGI_FORMAT_R16_SINT, + DXGI_FORMAT_R8_TYPELESS, + DXGI_FORMAT_R8_UINT, + DXGI_FORMAT_R8_SINT, + DXGI_FORMAT_BC1_UNORM, + DXGI_FORMAT_BC6H_UF16, + DXGI_FORMAT_BC7_UNORM, + DXGI_FORMAT_B5G6R5_UNORM, + static_cast(116), + static_cast(117), + static_cast(118), + static_cast(119), + static_cast(120), + }; + for (DXGI_FORMAT fmt : kRefusedSpotChecks) { + if (classify(fmt) != x2w_startup::D16SrvMode::refused) { + std::fprintf(stderr, "refused format %d accepted\n", static_cast(fmt)); + return 1; + } + } + + x2w_startup::D16ImageSrvs srvs; + if (srvs.any() || !srvs.valid_for_srvs(std::vector{})) return 1; + if (!srvs.read_manifest_line("d16srv 0 exact") || !srvs.read_manifest_line("d16srv 31 exact")) + return 1; + if (!srvs.any() || !srvs.requires_exact(0) || !srvs.requires_exact(31) || + srvs.requires_exact(1) || srvs.requires_exact(32)) + return 1; + + constexpr const char* kBadLines[] = { + "d16srv 0 exact", // duplicate index 0 + "d16srv 00 exact", // leading zero + "d16srv 01 exact", // leading zero + "d16srv 32 exact", // out of range + "d16srv -1 exact", // negative + "d16srv exact", // missing index + "d16srv 2 float_norm", // obsolete tag + "d16srv 2 uint", // unsupported expectation + "d16srv 2 exact ", // trailing whitespace + "wmask 0 0x1", // wrong tag + }; + for (const char* bad : kBadLines) { + if (srvs.read_manifest_line(bad)) { + std::fprintf(stderr, "accepted bad manifest line: %s\n", bad); + return 1; + } + } + + std::vector bindings(32, FakeSrv{1}); + if (!srvs.valid_for_srvs(bindings)) return 1; + bindings[31].kind = 4; // tex1d is a texture SRV + if (!srvs.valid_for_srvs(bindings)) return 1; + bindings[0].kind = 0; // buffer SRV cannot satisfy d16srv + if (srvs.valid_for_srvs(bindings)) return 1; + bindings[0].kind = 3; // tex3d + bindings.pop_back(); // index 31 now out of range + if (srvs.valid_for_srvs(bindings)) return 1; + + std::printf("d16_image_format: 14 exact formats (11 float_exact + 3 unorm16), 242 refused values and manifest parser verified\n"); + return 0; +} diff --git a/tests/startup_d16_srv_check.py b/tests/startup_d16_srv_check.py new file mode 100644 index 000000000..36e7802dc --- /dev/null +++ b/tests/startup_d16_srv_check.py @@ -0,0 +1,124 @@ +"""End-to-end bound SRV format validation and UNORM16 mode dispatch for D16 image_load (#2023, item D). + +Translates a gfx1013 pixel stage using level-zero image_load ... d16, checks whether the narrowed half equals +0x3bff (green = 1.0 when v4[15:0] == 0x3bff, 0.0 otherwise), widens v4 via v_cvt_f32_f16, verifies 'd16srv 0 exact' +and 'udsrc 3 d16unorm16 0' in the published manifest, and draws eight columns through d3d12_xs.dll: + col 0: R16_UNORM (0xffef) + explicit R16_UNORM SRV -> d16unorm16=1 gives exact 0x3bff -> (255, 255, 0, 255) + col 1: R32_FLOAT (0x3f7ff000) + default SRV -> d16unorm16=0 gives 0x3c00 -> (255, 0, 0, 255) + col 2: R16_TYPELESS (0xaaaa) + explicit R16_UNORM -> d16unorm16=1 gives 0x3955 -> (170, 0, 0, 255) + col 3: R16_TYPELESS + explicit R16_UINT SRV -> refused, stays clear -> (0, 0, 255, 255) + col 4: R16_UINT + default SRV -> refused, stays clear -> (0, 0, 255, 255) + col 5: R16_SNORM + explicit R16_SNORM SRV -> refused (unverified format) -> (0, 0, 255, 255) + col 6: null-resource SRV and unwritten slot -> both refused, stays clear -> (0, 0, 255, 255) + col 7: rebind R16_UNORM (0xffef) + default SRV -> d16unorm16=1 gives exact 0x3bff -> (255, 255, 0, 255) +Also checks that a malformed 'd16srv' manifest line is rejected by load_translation. +""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from startup_image_load_d16_check import IMG_LOAD, encode_mimg +from startup_stream_check import container +from startup_stream_draw_check import gfx2hlsl, vertex + + +def d16_pixel_container(): + code = ( + bytes.fromhex( + '04040cf4000000fa' # s_load_dwordx8 s[16:23], s[8:9], 0x0 + '8002007e' # v_mov_b32_e32 v0, 0 + '8002027e' # v_mov_b32_e32 v1, 0 + 'f202047e' # v_mov_b32_e32 v2, 1.0 + '7fc08cbf' # s_waitcnt lgkmcnt(0) + ) + + encode_mimg(IMG_LOAD, dmask=0x1, vaddr=0, vdata=4, srsrc=16, d16=1) + + bytes.fromhex( + '703f8cbf' # s_waitcnt vmcnt(0) + 'ff080a36ffff0000' # v_and_b32_e32 v5, 0xffff, v4 + 'ff0a847dff3b0000' # v_cmp_eq_u32_e32 vcc_lo, 0x3bff, v5 + '80040a02' # v_cndmask_b32_e32 v5, 0, v2, vcc_lo + '0417087e' # v_cvt_f32_f16_e32 v4, v4 + '0f1800f804050002' # exp mrt0 v4, v5, v0, v2 done vm + '000081bf' # s_endpgm + ) + ) + words = struct.unpack('<%dI' % (len(code) // 4), code) + return container(0, words) + + +def check(directory, consumer, backend): + cache = directory / 'cache' + cache.mkdir() + vs, ps, root, output = (directory / name for name in ('vs', 'ps', 'root', 'pixels')) + trap_log = directory / 'trap.log' + vs.write_bytes(vertex()) + ps.write_bytes(d16_pixel_container()) + + env = dict( + os.environ, + X2W_D3D12_PERMISSIVE='1', + X2W_D3D12_LIST_NOOP='1', + X2W_D3D12_RENDER='1', + X2W_D3D12_DEBUG='0', + X2W_D3D12_DEVICE_NOOP='1', + X2W_SHADER_CACHE=str(cache), + X2W_TEST_D16_SRV='1', + X2W_TRAP_LOG=str(trap_log), + ) + args = [consumer, vs, ps, root] + subprocess.run(args, env=env, check=True) + subprocess.run([sys.executable, '-B', gfx2hlsl.__file__, '--pending', cache], env=env, check=True) + + manifest, = cache.glob('*.txt') + manifest_text = manifest.read_text(encoding='ascii') + manifest_lines = manifest_text.splitlines() + assert 'udsrc 3 d16unorm16 0' in manifest_lines, manifest_text + assert 'srv 0 tex2d table 0 0' in manifest_lines, manifest_text + assert 'd16srv 0 exact' in manifest_lines, manifest_text + + result = subprocess.run([*args, backend, output], env=env, capture_output=True, text=True) + print(result.stdout, end='') + if result.returncode == 77: + return 77 + if result.returncode: + raise RuntimeError(f'consumer failed ({result.returncode})\n{result.stderr[-5000:]}') + + actual = output.read_bytes() + rgba_at_x = ( + (255, 255, 0, 255), # col 0: R16_UNORM 0xffef -> exact 0x3bff (d16unorm16=1) + (255, 0, 0, 255), # col 1: R32_FLOAT 0x3f7ff000 -> 0x3c00 (d16unorm16=0) + (170, 0, 0, 255), # col 2: R16_TYPELESS 0xaaaa + R16_UNORM -> 0x3955 + (0, 0, 255, 255), # col 3: R16_TYPELESS + R16_UINT -> refused + (0, 0, 255, 255), # col 4: R16_UINT -> refused + (0, 0, 255, 255), # col 5: R16_SNORM -> refused + (0, 0, 255, 255), # col 6: null resource + unwritten slot -> refused + (255, 255, 0, 255), # col 7: R16_UNORM 0xffef default SRV -> exact 0x3bff + ) + expected = bytes(c for _ in range(4) for pixel in rgba_at_x for c in pixel) + if actual != expected: + raise AssertionError(f'actual {actual.hex()} expected {expected.hex()}') + + log_text = trap_log.read_text(errors='replace') + for expected_reason in ('(format 57)', '(format 58)', '(missing texture resource 0)', '(missing view token 0)'): + assert f'srv 0: d16 exact refused {expected_reason}' in log_text, (expected_reason, log_text) + + # Negative control: a malformed d16srv manifest line must be rejected by load_translation (all draws skipped). + bad_log = directory / 'bad_trap.log' + bad_out = directory / 'bad_pixels' + manifest.write_text(manifest_text.replace('d16srv 0 exact', 'd16srv 0 uint'), encoding='ascii') + bad_env = dict(env, X2W_TRAP_LOG=str(bad_log)) + bad_run = subprocess.run([*args, backend, bad_out], env=bad_env, capture_output=True, text=True) + assert bad_run.returncode == 0, bad_run.stderr + assert bad_out.read_bytes() == bytes((0, 0, 255, 255)) * 32 + assert 'invalid d16srv manifest line' in bad_log.read_text(errors='replace') + + print(f'{backend}: exact UNORM16 (0xffef->0x3bff) vs R32_FLOAT (0x3c00) dispatched, 5 invalid SRVs refused, bad manifest rejected') + return 0 + + +if __name__ == '__main__': + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_image_3d.cpp b/tests/startup_image_3d.cpp index fe7853391..95755dc7c 100644 --- a/tests/startup_image_3d.cpp +++ b/tests/startup_image_3d.cpp @@ -204,3 +204,147 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const one_dimensional ? "1d" : two_dimensional ? "2d" : array ? "2d_array" : "3d", z, color[0], color[1], color[2], color[3]); } + +// Draws an 8x2 R32G32B32A32_UINT target against an 8x2 2D source texture with no static samplers: +// depth16 == true: DXGI_FORMAT_R16_UNORM (16-bit depth SRV format) covering zero, binary16 subnormals, +// exact fractions and values where IEEE round-to-nearest-even differs from RTZ; +// depth16 == false: DXGI_FORMAT_R32G32B32A32_FLOAT covering four distinct channels per texel, halfway ties +// to even, 1-ULP midpoint neighbours, subnormals, signed zero, overflow and quiet NaNs. +void check_startup_image_load_d16(ID3D12Device* device, const char* vertex_path, const char* pixel_path, + bool depth16, std::uint32_t words[64]) +{ + constexpr UINT width = 8, height = 2; + static constexpr std::uint16_t kDepthTexels[width * height] = { + 0x0000, 0x0001, 0x0003, 0x1234, 0x2aad, 0x4008, 0x5555, 0x8000, + 0x8010, 0xa018, 0xc018, 0xe00c, 0xffaf, 0xffef, 0xfffe, 0xffff, + }; + static constexpr std::uint32_t kFloatTexels[width * height][4] = { + {0x3f801000u, 0x3f803000u, 0x3f801001u, 0x3f7fffffu}, + {0x387fe000u, 0x387fdfffu, 0x33800000u, 0x33000000u}, + {0x33000001u, 0xb5c00000u, 0x80000000u, 0x00000000u}, + {0xbf803000u, 0xbf801000u, 0x477fefffu, 0x477ff000u}, + {0xc77ff000u, 0x7f800000u, 0xff800000u, 0x7fc00001u}, + {0x40490fdbu, 0x35555555u, 0xbeaaaaabu, 0xffc00123u}, + {0x3c000000u, 0xbc800000u, 0x3d000000u, 0xbd800000u}, + {0x42000000u, 0xc2200000u, 0x42400000u, 0xc2600000u}, + {0x3e200000u, 0x3ea00000u, 0x3ef00000u, 0x3f100000u}, + {0xbe200000u, 0xbea00000u, 0xbef00000u, 0xbf100000u}, + {0x39001000u, 0x39003000u, 0xb9003000u, 0x39001001u}, + {0x44002000u, 0x44006000u, 0xc4006000u, 0x44002001u}, + {0x34000000u, 0x34800000u, 0x35000000u, 0x35800000u}, + {0xb4000000u, 0xb4800000u, 0xb5000000u, 0xb5800000u}, + {0x3fc00000u, 0xc0000000u, 0x40200000u, 0xc0400000u}, + {0x477fe000u, 0xc77fe000u, 0x38800000u, 0xb8800000u}, + }; + + const auto vs = read_blob(vertex_path); + const auto ps = read_blob(pixel_path); + constexpr UINT d16_entry_constants = 5; // ud0..ud3 from FULLSCREEN_VS plus ud4 ('d16unorm16 0') + const x2w_startup::TranslatedSamplers no_samplers{}; + ComPtr root; + check(x2w_startup::create_translated_root(device, d16_entry_constants, 1, no_samplers, &root), + "Create translated image_load d16 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_UINT; + pd.SampleDesc.Count = 1; + ComPtr pipeline; + check(device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pipeline)), "Create image_load d16 PSO"); + + D3D12_RESOURCE_DESC td{}; + td.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + td.Width = width; + td.Height = height; + td.DepthOrArraySize = 1; + td.MipLevels = 1; + td.Format = depth16 ? DXGI_FORMAT_R16_UNORM : DXGI_FORMAT_R32G32B32A32_FLOAT; + td.SampleDesc.Count = 1; + const auto texture = resource(device, td, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST); + + D3D12_PLACED_SUBRESOURCE_FOOTPRINT src_footprint{}; + UINT64 upload_size = 0; + device->GetCopyableFootprints(&td, 0, 1, 0, &src_footprint, nullptr, nullptr, &upload_size); + const auto upload = make_buffer(device, upload_size, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + void* mapped = nullptr; + const D3D12_RANGE none{0, 0}; + check(upload->Map(0, &none, &mapped), "Map image_load d16 texels"); + auto* const dst_bytes = static_cast(mapped) + src_footprint.Offset; + const UINT row_bytes = depth16 ? width * sizeof(std::uint16_t) : width * 4 * sizeof(std::uint32_t); + for (UINT y = 0; y < height; ++y) { + const void* row_src = depth16 ? static_cast(&kDepthTexels[y * width]) + : static_cast(&kFloatTexels[y * width][0]); + std::memcpy(dst_bytes + y * src_footprint.Footprint.RowPitch, row_src, row_bytes); + } + upload->Unmap(0, nullptr); + + D3D12_RESOURCE_DESC rd{}; + rd.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rd.Width = width; + rd.Height = height; + rd.DepthOrArraySize = 1; + rd.MipLevels = 1; + rd.Format = DXGI_FORMAT_R32G32B32A32_UINT; + rd.SampleDesc.Count = 1; + rd.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + const auto target = resource(device, rd, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_RENDER_TARGET); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT target_footprint{}; + UINT64 readback_size = 0; + device->GetCopyableFootprints(&rd, 0, 1, 0, &target_footprint, nullptr, nullptr, &readback_size); + const auto readback = make_buffer(device, readback_size, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr views, rtvs; + check(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&views)), "Create image_load d16 SRV heap"); + device->CreateShaderResourceView(texture.Get(), nullptr, views->GetCPUDescriptorHandleForHeapStart()); + hd = {D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}; + check(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&rtvs)), "Create image_load d16 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(); + D3D12_TEXTURE_COPY_LOCATION to{texture.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + to.SubresourceIndex = 0; + D3D12_TEXTURE_COPY_LOCATION from{upload.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + from.PlacedFootprint = src_footprint; + list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + transition(list, texture.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + list->SetGraphicsRootSignature(root.Get()); + ID3D12DescriptorHeap* heaps[]{views.Get()}; + list->SetDescriptorHeaps(1, heaps); + const std::uint32_t constants[d16_entry_constants] = {0, 0, 0, 0, depth16 ? 1u : 0u}; + list->SetGraphicsRoot32BitConstants(0, d16_entry_constants, constants, 0); + list->SetGraphicsRootDescriptorTable(1, views->GetGPUDescriptorHandleForHeapStart()); + const D3D12_VIEWPORT viewport{0, 0, static_cast(width), static_cast(height), 0, 1}; + const D3D12_RECT scissor{0, 0, static_cast(width), static_cast(height)}; + 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 = target_footprint; + D3D12_TEXTURE_COPY_LOCATION in{target.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + in.SubresourceIndex = 0; + list->CopyTextureRegion(&out, 0, 0, 0, &in, nullptr); + commands.submit_and_wait(device); + + const D3D12_RANGE read{0, static_cast(readback_size)}; + check(readback->Map(0, &read, &mapped), "Map image_load d16 readback"); + const auto* const rb_bytes = static_cast(mapped) + target_footprint.Offset; + for (UINT y = 0; y < height; ++y) + std::memcpy(&words[y * width * 4], rb_bytes + y * target_footprint.Footprint.RowPitch, + width * 4 * sizeof(std::uint32_t)); + readback->Unmap(0, &none); +} diff --git a/tests/startup_image_load_d16_check.py b/tests/startup_image_load_d16_check.py new file mode 100644 index 000000000..eada2d0d7 --- /dev/null +++ b/tests/startup_image_load_d16_check.py @@ -0,0 +1,986 @@ +"""Level-zero D16 image_load lowering in tools/startup/gfx2hlsl.py (Part of #2023, item D). + + (no arguments) emitted-HLSL rounding, decoder, SRV format and odd-dmask controls + binary reassemble every fixture source and compare it with the recorded words + decode disassemble the MIMG words with LLVM's C API and compare with disasm_rdna2.py + draw [fxc] + translate, compile (DXC ps_6_0, and FXC ps_5_1 when given) and draw two + pixel fixtures against 8x2 R16_UNORM (including 0xffaf and 0xffef) and 8x2 + R32G32B32A32_FLOAT textures into an R32G32B32A32_UINT target, checking all + 64 output words per draw, high-half odd-dmask isolation and eight mutations + +On RDNA 2 (gfx1013), image_load with d16 narrows the enabled dmask channels to IEEE binary16 (round to nearest even) +and packs them pairwise into ceil(popcount(dmask) / 2) consecutive VGPRs (low half first, high half second; when +popcount(dmask) is odd, bits 31:16 of the final destination VGPR are hardware-undefined). HLSL f32tof16 truncates +toward zero on WARP (lowering 31,740 of the 65,536 R16_UNORM values by 1 ULP), while narrowing a binary32 intermediate +still double-rounds R16_UNORM at 0xffaf (0x3bfe vs 0x3bfd) and 0xffef (0x3c00 vs 0x3bff). gfx2hlsl.py therefore emits +both integer binary32-to-binary16 RNE (pack16_rne) and exact UNORM16 ratio-to-half (pack16_unorm16) selected per SRV +via 'udsrc d16unorm16 ', restricts 'd16srv exact' to the 14 independently GPU-verified exact +formats, and refuses whole-word reads of odd-dmask destination VGPRs unless consumed through a low-16-bit operation. +""" +from fractions import Fraction +import re +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')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, assemble, compile_hlsl, root_blob # noqa: E402 + +IMG_LOAD = 0x00 +IMG_LOAD_MIP = 0x01 +IMG_SAMPLE = 0x20 +IMG_SAMPLE_LZ = 0x27 +DIM_1D = 0 +DIM_2D = 1 +DIM_3D = 2 +DIM_CUBE = 3 +DIM_2D_ARRAY = 5 + +WIDTH = 8 +HEIGHT = 2 +PACKED_INPUT = (0x8000, 0x8000) +UINT_RTV = (42,) # DXGI_FORMAT_R32G32B32A32_UINT + +# Includes both R16_UNORM double-rounding discriminators (0xffaf -> 0x3bfd, 0xffef -> 0x3bff). +DEPTH_TEXELS = ( + 0x0000, 0x0001, 0x0003, 0x1234, 0x2aad, 0x4008, 0x5555, 0x8000, + 0x8010, 0xa018, 0xc018, 0xe00c, 0xffaf, 0xffef, 0xfffe, 0xffff, +) + +FLOAT_TEXELS = ( + (0x3f801000, 0x3f803000, 0x3f801001, 0x3f7fffff), + (0x387fe000, 0x387fdfff, 0x33800000, 0x33000000), + (0x33000001, 0xb5c00000, 0x80000000, 0x00000000), + (0xbf803000, 0xbf801000, 0x477fefff, 0x477ff000), + (0xc77ff000, 0x7f800000, 0xff800000, 0x7fc00001), + (0x40490fdb, 0x35555555, 0xbeaaaaab, 0xffc00123), + (0x3c000000, 0xbc800000, 0x3d000000, 0xbd800000), + (0x42000000, 0xc2200000, 0x42400000, 0xc2600000), + (0x3e200000, 0x3ea00000, 0x3ef00000, 0x3f100000), + (0xbe200000, 0xbea00000, 0xbef00000, 0xbf100000), + (0x39001000, 0x39003000, 0xb9003000, 0x39001001), + (0x44002000, 0x44006000, 0xc4006000, 0x44002001), + (0x34000000, 0x34800000, 0x35000000, 0x35800000), + (0xb4000000, 0xb4800000, 0xb5000000, 0xb5800000), + (0x3fc00000, 0xc0000000, 0x40200000, 0xc0400000), + (0x477fe000, 0xc77fe000, 0x38800000, 0xb8800000), +) + +# DXGI_FORMAT enum values referenced in src/startup_stubs/d16_image_format.h. +DXGI_FORMAT_VALUES = { + 'DXGI_FORMAT_R32G32B32A32_FLOAT': 2, + 'DXGI_FORMAT_R32G32B32_FLOAT': 6, + 'DXGI_FORMAT_R16G16B16A16_UNORM': 11, + 'DXGI_FORMAT_R32G32_FLOAT': 16, + 'DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS': 21, + 'DXGI_FORMAT_R8G8B8A8_UNORM': 28, + 'DXGI_FORMAT_R16G16_UNORM': 35, + 'DXGI_FORMAT_R32_FLOAT': 41, + 'DXGI_FORMAT_R8G8_UNORM': 49, + 'DXGI_FORMAT_R16_UNORM': 56, + 'DXGI_FORMAT_R8_UNORM': 61, + 'DXGI_FORMAT_A8_UNORM': 65, + 'DXGI_FORMAT_B8G8R8A8_UNORM': 87, + 'DXGI_FORMAT_B8G8R8X8_UNORM': 88, +} + + +def encode_mimg(op, *, dmask=0xf, dim=DIM_2D, vaddr=0, vdata=4, srsrc=16, ssamp=0, nsa=0, extra_addrs=(), + dlc=0, unorm=0, glc=0, r128=0, tfe=0, lwe=0, slc=0, a16=0, d16=0, w0_reserved=0, w1_reserved=0): + w0 = (0xf0000000 | ((op & 0x7f) << 18) | ((op >> 7) & 1) | ((nsa & 0x3) << 1) + | ((dim & 0x7) << 3) | ((dlc & 1) << 7) | ((dmask & 0xf) << 8) + | ((unorm & 1) << 12) | ((glc & 1) << 13) | ((r128 & 1) << 15) + | ((tfe & 1) << 16) | ((lwe & 1) << 17) | ((slc & 1) << 25) | w0_reserved) + w1 = ((vaddr & 0xff) | ((vdata & 0xff) << 8) | (((srsrc // 4) & 0x1f) << 16) + | (((ssamp // 4) & 0x1f) << 21) | ((a16 & 1) << 30) | ((d16 & 1) << 31) | w1_reserved) + ext = bytes(extra_addrs) + bytes(max(0, 4 * nsa - len(extra_addrs))) + return struct.pack(', 0xffff, v.""" + return struct.pack(' v_cvt_f32_f16), 2-channel non-contiguous a16+d16 (dmask:0x5) +# and 3-channel NSA d16 (dmask:0x7 -> SDWA WORD_0 low-half consumer on v7). +PS_SOURCE_A = PRE + '\n'.join(MIMG_LLVM_MC[k][0] for k in ('d16_x', 'd16_xz_a16', 'd16_xyz_nsa')) + '\n' + POST_A +PS_WORDS_A = PRE_WORDS + b''.join(MIMG_LLVM_MC[k][1] for k in ('d16_x', 'd16_xz_a16', 'd16_xyz_nsa')) + POST_WORDS_A + +# Fixture B exercises full 4-channel d16 (dmask:0xf), single y channel (dmask:0x2 -> v_and_b32 0xffff) and dmask:0xc. +PS_SOURCE_B = PRE + '\n'.join(MIMG_LLVM_MC[k][0] for k in ('d16_xyzw', 'd16_y', 'd16_zw')) + '\n' + POST_B +PS_WORDS_B = PRE_WORDS + b''.join(MIMG_LLVM_MC[k][1] for k in ('d16_xyzw', 'd16_y', 'd16_zw')) + POST_WORDS_B + + +PACK16_RNE_HLSL = """\ +uint pack16_rne(float value) { + uint bits = asuint(value), sign = (bits >> 16) & 0x8000u, abs_bits = bits & 0x7fffffffu; + if (abs_bits > 0x7f800000u) return sign | 0x7e00u; + if (abs_bits >= 0x477ff000u) return sign | 0x7c00u; + if (abs_bits >= 0x38800000u) { + uint shifted = abs_bits - 0x38000000u; + return sign | ((shifted + 0x00000fffu + ((shifted >> 13) & 1u)) >> 13); + } + if (abs_bits < 0x33000000u) return sign; + uint sig = 0x00800000u | (abs_bits & 0x007fffffu), shift = 126u - (abs_bits >> 23); + uint half_m = sig >> shift, rem = sig & ((1u << shift) - 1u), mid = 1u << (shift - 1u); + if (rem > mid || (rem == mid && (half_m & 1u) != 0u)) half_m += 1u; + return sign | half_m; +}""" + +PACK16_UNORM16_HLSL = """\ +uint pack16_unorm16(float value) { + uint u = uint(saturate(value) * 65535.0 + 0.5); + if (u <= 3u) return u << 8; + if (u >= 65535u) return 0x3c00u; + uint msb = firstbithigh(u); + uint num = u << (26u - msb); + uint q = num / 65535u; + if (num - q * 65535u > 32767u) q += 1u; + return ((msb - 1u) << 10) + (q - 1024u); +}""" + +PACK16_D16_HLSL = """\ +uint pack16_d16(float value, uint unorm16) { + return unorm16 != 0u ? pack16_unorm16(value) : pack16_rne(value); +}""" + +PACK16_HELPERS_HLSL = PACK16_RNE_HLSL + '\n' + PACK16_UNORM16_HLSL + '\n' + PACK16_D16_HLSL + +PACK16_RTZ_HLSL = """\ +uint pack16_rne(float value) { + uint bits = asuint(value), sign = (bits >> 16) & 0x8000u, abs_bits = bits & 0x7fffffffu; + if (abs_bits > 0x7f800000u) return sign | 0x7e00u; + if (abs_bits >= 0x47800000u) return sign | 0x7c00u; + if (abs_bits >= 0x477fe000u) return sign | 0x7bffu; + if (abs_bits >= 0x38800000u) return sign | ((abs_bits - 0x38000000u) >> 13); + if (abs_bits < 0x33800000u) return sign; + uint sig = 0x00800000u | (abs_bits & 0x007fffffu), shift = 126u - (abs_bits >> 23); + return sign | (sig >> shift); +}""" + + +def f32_bits_from_unorm16(u16): + return struct.unpack(' scaled.denominator or (2 * r == scaled.denominator and (q & 1)): + q += 1 + return q + e = x.numerator.bit_length() - x.denominator.bit_length() - 1 + while (x * (1 << (-e))) < 1: + e -= 1 + while (x * (1 << (-e))) >= 2: + e += 1 + scaled = x * (1 << (10 - e)) + q, r = divmod(scaled.numerator, scaled.denominator) + if 2 * r > scaled.denominator or (2 * r == scaled.denominator and (q & 1)): + q += 1 + if q == 2048: + q, e = 1024, e + 1 + return ((e + 15) << 10) | (q - 1024) + + +def pack16_rne_ref(bits): + """Independent IEEE-754 binary32-to-binary16 round-to-nearest-even reference (preserving NaN sign).""" + bits &= 0xffffffff + sign = (bits >> 16) & 0x8000 + abs_bits = bits & 0x7fffffff + if abs_bits > 0x7f800000: + return sign | 0x7e00 + if abs_bits >= 0x477ff000: + return sign | 0x7c00 + val = struct.unpack('> 16) & 0x8000 + abs_bits = bits & 0x7fffffff + if abs_bits > 0x7f800000: + return sign | 0x7e00 + if abs_bits == 0x7f800000: + return sign | 0x7c00 + if abs_bits >= 0x47800000: + return sign | 0x7c00 + if abs_bits >= 0x477fe000: + return sign | 0x7bff + if abs_bits >= 0x38800000: + return sign | ((abs_bits - 0x38000000) >> 13) + if abs_bits < 0x33800000: + return sign + sig = 0x00800000 | (abs_bits & 0x007fffff) + shift = 126 - (abs_bits >> 23) + return sign | (sig >> shift) + + +def texel_f32_words(tex_mode, x, y): + if not (0 <= x < WIDTH and 0 <= y < HEIGHT): + return (0, 0, 0, 0) + idx = y * WIDTH + x + if tex_mode == 'r16_unorm': + return (f32_bits_from_unorm16(DEPTH_TEXELS[idx]), 0, 0, 0x3f800000) + return FLOAT_TEXELS[idx] + + +def texel_halves(tex_mode, x, y, mutant=None): + if not (0 <= x < WIDTH and 0 <= y < HEIGHT): + return (0, 0, 0, 0) + idx = y * WIDTH + x + if tex_mode == 'r16_unorm': + rgba = texel_f32_words(tex_mode, x, y) + if mutant == 'rtz': + return tuple(pack16_rtz_ref(c) for c in rgba) + if mutant == 'double_round': + return tuple(pack16_rne_ref(c) for c in rgba) + return (exact_unorm16_f16_ref(DEPTH_TEXELS[idx]), 0, 0, 0x3c00) + narrow = pack16_rtz_ref if mutant == 'rtz' else pack16_rne_ref + return tuple(narrow(c) for c in FLOAT_TEXELS[idx]) + + +def pack_pair(lo, hi): + return (lo & 0xffff) | ((hi & 0xffff) << 16) + + +def expected_words(fixture, tex_mode, mutant=None): + out = [] + for y in range(HEIGHT): + for x in range(WIDTH): + rgba = texel_f32_words(tex_mode, x, y) + hx, hy, hz, hw = texel_halves(tex_mode, x, y, mutant) + if fixture == 'A': + w0 = rgba[0] if mutant == 'unpacked_x' else f32_bits_from_f16_bits(hx) + ax, ay = (x | (y << 16), 63) if mutant == 'drop_a16' else (x, y) + hax, _, haz, _ = texel_halves(tex_mode, ax, ay, mutant) + if mutant == 'swap_halves': + w1 = pack_pair(haz, hax) + elif mutant == 'drop_shift': + w1 = (hax & 0xffff) | (haz & 0xffff) + else: + w1 = pack_pair(hax, haz) + nx, ny = (x, 63) if mutant == 'drop_nsa' else (x, y) + hnx, hny, hnz, _ = texel_halves(tex_mode, nx, ny, mutant) + w2 = pack_pair(hnx, hny) + w3 = (0xdead0000 | hnz) if mutant == 'unmasked_odd_hi' else hnz + out.extend((w0, w1, w2, w3)) + else: + out.extend((pack_pair(hx, hy), pack_pair(hz, hw), hy, pack_pair(hz, hw))) + return out + + +def expect_refused(fn, substring, label): + try: + fn() + except G.Unsupported as exc: + assert substring in str(exc), f'{label}: expected {substring!r} in {str(exc)!r}' + else: + raise AssertionError(f'{label}: unexpectedly accepted') + + +def transpile_emitted_helpers(hlsl_source): + """Compile the live pack16_rne and pack16_unorm16 HLSL bodies emitted by gfx2hlsl.py into Python.""" + namespace = { + 'uint': lambda x: int(x) & 0xffffffff, + 'asuint': lambda bits: bits & 0xffffffff, + 'saturate': lambda bits: min(max(struct.unpack('> 13) & 1u)', '', 1)) + assert broken_tie(0x3f803000) != pack16_rne_ref(0x3f803000) + _, broken_u16 = transpile_emitted_helpers(emitted_ps.replace('> 32767u', '>= 0u', 1)) + assert broken_u16(f32_bits_from_unorm16(0xffaf)) != 0x3bfd + + rtz_depth_diffs = sum( + exact_unorm16_f16_ref(u) != pack16_rtz_ref(f32_bits_from_unorm16(u)) + for u in DEPTH_TEXELS + ) + assert rtz_depth_diffs >= 6, f'expected >=6 RNE-vs-RTZ depth discriminators, got {rtz_depth_diffs}' + print(f'emitted HLSL helpers: {tested} boundary floats, 256 UNORM8 and all 65,536 R16_UNORM codes exact') + + +def check_decoder_and_masks(): + for blob, expected_text in ((PRE_WORDS, PRE), (POST_WORDS_A, POST_A), (POST_WORDS_B, POST_B)): + off = 0 + decoded = [] + while off < len(blob): + n, _, asm, _ = D.decode_instruction(blob, off) + decoded.append(asm) + off += n + assert decoded == expected_text.strip().splitlines(), decoded + + for key in DECODE_KEYS: + text, raw = MIMG_LLVM_MC[key] + length, _, asm, _ = D.decode_instruction(raw, 0) + assert length == len(raw) and asm == text, (key, length, asm, text) + + # Check all 15 non-zero dmasks for destination register width, pairwise component order and odd-dmask gating. + for dmask in range(1, 16): + comps = [c for bit, c in enumerate('xyzw') if dmask & (1 << bit)] + expected_regs = (len(comps) + 1) // 2 + raw = encode_mimg(IMG_LOAD, dmask=dmask, vaddr=8, vdata=4, d16=1) + _, _, asm, _ = D.decode_instruction(raw, 0) + expected_dst = 'v4' if expected_regs == 1 else 'v[4:5]' + assert asm.startswith(f'image_load {expected_dst}, '), (dmask, asm) + if len(comps) % 2 == 1: + odd_reg = 4 + (len(comps) - 1) // 2 + expect_refused( + lambda r=raw: G.Pipeline(VS_WORDS, PRE_WORDS + r + POST_WORDS, root_blob(), + ps_hw_inputs=PACKED_INPUT, rtv_formats=UINT_RTV), + f'whole-word read of v{odd_reg} after odd d16 image_load', + f'odd dmask 0x{dmask:x} direct export', + ) + ps_blob = PRE_WORDS + raw + encode_v_and_low16(odd_reg) + POST_WORDS + else: + ps_blob = PRE_WORDS + raw + POST_WORDS + pipe = G.Pipeline(VS_WORDS, ps_blob, root_blob(), ps_hw_inputs=PACKED_INPUT, rtv_formats=UINT_RTV) + ps = pipe.hlsl_ps() + manifest = pipe.manifest() + assert PACK16_HELPERS_HLSL in ps + assert 'udsrc 4 d16unorm16 0' in manifest.splitlines(), manifest + assert 'd16srv 0 exact' in manifest.splitlines(), manifest + assert 'SamplerState' not in ps and 'smp ' not in manifest + for i in range(0, len(comps), 2): + reg = 4 + i // 2 + if i + 1 == len(comps): + want = f'v{reg} = pack16_d16(t.{comps[i]}, ud4);' + else: + want = f'v{reg} = pack16_d16(t.{comps[i]}, ud4) | (pack16_d16(t.{comps[i + 1]}, ud4) << 16);' + assert want in ps, (dmask, want, ps) + + # Verify 3D and 2D-array level-zero D16 loads, plus vertex-stage emission. + for key, hlsl_type, srv_kind in (('d16_3d', 'Texture3D', 'tex3d'), + ('d16_2da', 'Texture2DArray', 'tex2da')): + ps_3 = PRE_WORDS + MIMG_LLVM_MC[key][1] + POST_WORDS + pipe = G.Pipeline(VS_WORDS, ps_3, root_blob(), ps_hw_inputs=PACKED_INPUT, rtv_formats=UINT_RTV) + hlsl = pipe.hlsl_ps() + manifest = pipe.manifest().splitlines() + assert hlsl_type in hlsl and 'r0.Load(int4(v0, v1, v2, 0))' in hlsl, hlsl + assert f'srv 0 {srv_kind} table 0 0' in manifest and 'd16srv 0 exact' in manifest + + # Vertex stage using image_load ... d16 emits helpers and d16srv, while a pipeline without d16 omits both. + vs_d16 = ( + bytes.fromhex('04040cf4000000fa' '8002027e' '7fc08cbf') + + encode_mimg(IMG_LOAD, dmask=0x3, vaddr=0, vdata=4, d16=1) + + bytes.fromhex('703f8cbf' 'cf0800f804040404' '000081bf') + ) + ps_plain = bytes.fromhex('8002007e' '0f1800f800000000' '000081bf') + vs_pipe = G.Pipeline(vs_d16, ps_plain, root_blob()) + assert PACK16_HELPERS_HLSL in vs_pipe.hlsl_vs() + assert 'v4 = pack16_d16(t.x, ud4) | (pack16_d16(t.y, ud4) << 16);' in vs_pipe.hlsl_vs() + assert 'd16srv 0 exact' in vs_pipe.manifest().splitlines() + plain_pipe = G.Pipeline(VS_WORDS, ps_plain, root_blob()) + assert 'pack16_' not in plain_pipe.hlsl_vs() and 'pack16_' not in plain_pipe.hlsl_ps() + assert 'd16srv' not in plain_pipe.manifest() and 'd16unorm16' not in plain_pipe.manifest() + print('decoder & masks: all 15 non-zero dmasks, 2D/a16/NSA/3D/2D_ARRAY, d16srv manifest and VS/PS paths verified') + + +def check_srv_format_controls(): + header = (HERE.parent / 'src' / 'startup_stubs' / 'd16_image_format.h').read_text(encoding='utf-8') + float_block, unorm16_block = header.split('return D16SrvMode::float_exact;', 1) + float_names = re.findall(r'case\s+(DXGI_FORMAT_\w+)\s*:', float_block) + unorm16_names = re.findall(r'case\s+(DXGI_FORMAT_\w+)\s*:', unorm16_block.split('return D16SrvMode::unorm16;', 1)[0]) + assert len(float_names) == 11 and len(unorm16_names) == 3, (float_names, unorm16_names) + assert {DXGI_FORMAT_VALUES[n] for n in float_names} == G.D16_FLOAT_EXACT_SRV_FORMATS + assert {DXGI_FORMAT_VALUES[n] for n in unorm16_names} == G.D16_UNORM16_SRV_FORMATS + + ps_even = PRE_WORDS + MIMG_LLVM_MC['d16_xyzw'][1] + POST_WORDS + for fmt in sorted(G.D16_EXACT_SRV_FORMATS): + pipe = G.Pipeline(VS_WORDS, ps_even, root_blob(), ps_hw_inputs=PACKED_INPUT, + rtv_formats=UINT_RTV, srv_formats=(fmt,)) + assert 'd16srv 0 exact' in pipe.manifest().splitlines() + + # Integer (UINT/SINT), typeless, depth-stencil-only, SNORM16, R24_UNORM, SRGB, BCn and console formats are refused. + refused_srv_formats = ( + (0, 'UNKNOWN'), + (3, 'R32G32B32A32_UINT'), + (4, 'R32G32B32A32_SINT'), + (13, 'R16G16B16A16_SNORM'), + (20, 'D32_FLOAT_S8X24_UINT'), + (22, 'X32_TYPELESS_G8X24_UINT'), + (24, 'R10G10B10A2_UNORM'), + (27, 'R8G8B8A8_TYPELESS'), + (29, 'R8G8B8A8_UNORM_SRGB'), + (30, 'R8G8B8A8_UINT'), + (31, 'R8G8B8A8_SNORM'), + (32, 'R8G8B8A8_SINT'), + (37, 'R16G16_SNORM'), + (39, 'R32_TYPELESS'), + (40, 'D32_FLOAT'), + (42, 'R32_UINT'), + (43, 'R32_SINT'), + (45, 'D24_UNORM_S8_UINT'), + (46, 'R24_UNORM_X8_TYPELESS'), + (47, 'X24_TYPELESS_G8_UINT'), + (53, 'R16_TYPELESS'), + (55, 'D16_UNORM'), + (57, 'R16_UINT'), + (58, 'R16_SNORM'), + (59, 'R16_SINT'), + (60, 'R8_TYPELESS'), + (62, 'R8_UINT'), + (64, 'R8_SINT'), + (71, 'BC1_UNORM'), + (85, 'B5G6R5_UNORM'), + (98, 'BC7_UNORM'), + (119, 'console R16_UNORM_X8_TYPELESS'), + ) + for fmt, label in refused_srv_formats: + expect_refused( + lambda f=fmt: G.Pipeline(VS_WORDS, ps_even, root_blob(), ps_hw_inputs=PACKED_INPUT, + rtv_formats=UINT_RTV, srv_formats={0: f}), + f'image_load d16 unsupported SRV format {fmt}', + f'srv_formats {label}', + ) + print(f'srv formats: 14 exact formats match d16_image_format.h; {len(refused_srv_formats)} non-exact formats refused') + + +def check_odd_dmask_consumers(): + def dummy_pipe(): + pipe = G.Pipeline.__new__(G.Pipeline) + pipe.resources = {} + pipe.rtv_formats = () + pipe.srv_formats = {} + pipe.uds = [] + return pipe + + def stage_with(lines, *, has_branches=False): + stage = G.Stage.__new__(G.Stage) + stage.pipe = dummy_pipe() + stage.kind = 'ps' + stage.lines = [] + stage.sym = {16 + i: ('desc', ('table', 0), 0, i) for i in range(8)} + stage.sym[24] = ('const', 0x00ff) + stage.sym[25] = ('const', 0x1ffff) + stage.used_s, stage.used_v = set(), set() + stage.exec_known = True + stage.exports = {} + stage.write_masks = {} + stage.attrs = {} + stage.masks = set() + stage.fetched = False + stage.uniform_v = set() + stage.varying_s = set() + stage.scc_uniform = True + stage.low16_only_v = set() + stage.pinned_low16_v = set() + stage.whole_read_v = set() + stage.has_branches = has_branches + stage.blocks = [] + for asm in lines: + stage.one(asm.split(' ', 1)[0], asm) + return stage + + odd_1 = 'image_load v4, v[0:1], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D d16' + odd_3 = 'image_load v[6:7], v[0:1], s[16:23] dmask:0x7 dim:SQ_RSRC_IMG_2D d16' + + accepted_sequences = ( + (odd_1, 'v_cvt_f32_f16_e32 v4, v4', 'v_add_f32_e32 v4, 1.0, v4'), + (odd_1, 'v_cvt_f32_ubyte0_e32 v4, v4', 'v_mul_f32_e32 v4, 2.0, v4'), + (odd_1, 'v_cvt_f32_ubyte1_e32 v4, v4', 'v_mul_f32_e32 v4, 2.0, v4'), + (odd_1, 'v_and_b32_e32 v4, 0xffff, v4', 'v_add_nc_u32_e32 v4, 1, v4'), + (odd_1, 'v_and_b32_e32 v4, v4, s24', 'v_add_nc_u32_e32 v4, 1, v4'), + (odd_1, 'v_and_b32_sdwa v4, v4, v4 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0', + 'v_add_nc_u32_e32 v4, 1, v4'), + (odd_1, 'v_cvt_f32_u32_sdwa v4, sext(v4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_1', + 'v_add_f32_e32 v4, 1.0, v4'), + (odd_1, 'v_cmp_eq_u32_sdwa vcc_lo, v4, v4 src0_sel:WORD_0 src1_sel:BYTE_0'), + (odd_1, 'v_cmp_class_f16_e32 vcc_lo, -|v4|, 0x3ff'), + (odd_1, 'v_fma_mixlo_f16 v8, v4, 1.0, 0 op_sel_hi:[1,0,0]', 'v_add_nc_u32_e32 v8, 1, v8'), + (odd_1, 'v_fma_mixhi_f16 v4, 1.0, 1.0, 0', 'v_add_nc_u32_e32 v4, 1, v4'), + (odd_3, 'v_add_nc_u32_e32 v6, 1, v6', 'v_cvt_f32_f16_e32 v7, v7', 'v_add_f32_e32 v7, 1.0, v7'), + ) + for seq in accepted_sequences: + stage_with(seq) + + refused_sequences = ( + ('v4 add', (odd_1, 'v_add_nc_u32_e32 v5, 1, v4'), 'whole-word read of v4'), + ('v4 shift16', (odd_1, 'v_lshrrev_b32_e32 v5, 16, v4'), 'whole-word read of v4'), + ('v4 mov', (odd_1, 'v_mov_b32_e32 v5, v4'), 'whole-word read of v4'), + ('v4 swap', (odd_1, 'v_swap_b32_e32 v4, v5'), 'whole-word read of v4'), + ('v4 float add', (odd_1, 'v_add_f32_e32 v5, 1.0, v4'), 'whole-word read of v4'), + ('v4 ubyte2', (odd_1, 'v_cvt_f32_ubyte2_e32 v5, v4'), 'whole-word read of v4'), + ('v4 ubyte3', (odd_1, 'v_cvt_f32_ubyte3_e32 v5, v4'), 'whole-word read of v4'), + ('v4 vgpr mask lhs', (odd_1, 'v_and_b32_e32 v5, v2, v4'), 'whole-word read of v4'), + ('v4 vgpr mask rhs', (odd_1, 'v_and_b32_e32 v5, v4, v2'), 'whole-word read of v4'), + ('v4 wide mask imm lhs', (odd_1, 'v_and_b32_e32 v5, 0x1ffff, v4'), 'whole-word read of v4'), + ('v4 wide mask imm rhs', (odd_1, 'v_and_b32_e64 v5, v4, -1'), 'whole-word read of v4'), + ('v4 wide mask hex rhs', (odd_1, 'v_and_b32_e64 v5, v4, 0x1ffff'), 'whole-word read of v4'), + ('v4 wide mask sgpr lhs', (odd_1, 'v_and_b32_e32 v5, s25, v4'), 'whole-word read of v4'), + ('v4 wide mask sgpr rhs', (odd_1, 'v_and_b32_e64 v5, v4, s25'), 'whole-word read of v4'), + ('v4 sdwa word1', + (odd_1, 'v_and_b32_sdwa v5, v4, v4 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:WORD_0'), + 'whole-word read of v4'), + ('v4 sdwa byte2', + (odd_1, 'v_and_b32_sdwa v5, v4, v4 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_2 src1_sel:BYTE_0'), + 'whole-word read of v4'), + ('v4 sdwa preserve low', + (odd_1, 'v_and_b32_sdwa v4, v4, v4 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0 src1_sel:WORD_0', + 'v_add_nc_u32_e32 v5, 1, v4'), + 'whole-word read of v4'), + ('v4 mixlo preserve high', + (odd_1, 'v_fma_mixlo_f16 v4, 1.0, 1.0, 0', 'v_add_nc_u32_e32 v5, 1, v4'), + 'whole-word read of v4'), + ('v4 compr export', + (odd_1, 'exp mrt0 v4, v4, off, off done compr'), + 'whole-word read of v4'), + ('v4 predicated overwrite', + (odd_1, 'v_cmpx_eq_u32_e32 0, v0', 'v_mov_b32_e32 v4, 0', 'v_add_nc_u32_e32 v5, 1, v4'), + 'whole-word read of v4'), + ('v7 dmask 0x7 tail', + (odd_3, 'v_add_nc_u32_e32 v5, 1, v7'), + 'whole-word read of v7'), + ) + for label, seq, msg in refused_sequences: + expect_refused(lambda s=seq: stage_with(s), msg, label) + + def translate_ins(ins): + stage = G.Stage.__new__(G.Stage) + stage.pipe = dummy_pipe() + stage.kind = 'ps' + stage.ins = ins + stage.lines = [] + stage.sym = {16 + i: ('desc', ('table', 0), 0, i) for i in range(8)} + stage.used_s, stage.used_v = set(), set() + stage.exec_known = True + stage.exports = {} + stage.write_masks = {} + stage.attrs = {} + stage.masks = set() + stage.fetched = False + stage.translate() + + forward_ins = [ + (0, 8, 'image_load', odd_1), + (8, 4, 's_cbranch_scc1', 's_cbranch_scc1 label_0010'), + (12, 4, 'v_mov_b32_e32', 'v_mov_b32_e32 v4, 0'), + (16, 4, 'v_add_nc_u32_e32', 'v_add_nc_u32_e32 v5, 1, v4'), + (20, 4, 's_endpgm', 's_endpgm'), + ] + expect_refused(lambda: translate_ins(forward_ins), 'whole-word read of v4', 'forward branch skip overwrite') + + loop_ins = [ + (0, 4, 'v_add_nc_u32_e32', 'v_add_nc_u32_e32 v5, 1, v4'), + (4, 8, 'image_load', odd_1), + (12, 4, 's_cbranch_scc1', 's_cbranch_scc1 label_0000'), + (16, 4, 's_endpgm', 's_endpgm'), + ] + expect_refused(lambda: translate_ins(loop_ins), 'whole-word read of v4', 'backward loop odd d16 leak') + + print(f'odd-dmask consumers: {len(accepted_sequences)} low-16-bit paths accepted; {len(refused_sequences) + 2} whole-word/control-flow leaks refused') + + +def check_refusals(): + def build_ps(mimg_bytes): + return G.Pipeline(VS_WORDS, PRE_WORDS + mimg_bytes + POST_WORDS, root_blob(), ps_hw_inputs=PACKED_INPUT) + + expect_refused(lambda: build_ps(MIMG_LLVM_MC['mip_d16_refused'][1]), 'image_load_mip', 'image_load_mip d16') + expect_refused(lambda: build_ps(MIMG_LLVM_MC['1d_d16_refused'][1]), '1D', '1D image_load d16') + expect_refused(lambda: build_ps(MIMG_LLVM_MC['cube_d16_refused'][1]), 'SQ_RSRC_IMG_CUBE', 'cube image_load d16') + expect_refused(lambda: build_ps(encode_mimg(IMG_LOAD, dim=DIM_3D, a16=1, d16=1)), 'image_load', '3D a16+d16') + expect_refused(lambda: build_ps(encode_mimg(IMG_LOAD, dim=DIM_2D_ARRAY, a16=1, d16=1)), 'image_load', '2D_ARRAY a16+d16') + expect_refused(lambda: build_ps(encode_mimg(IMG_LOAD, dmask=0, d16=1)), 'dmask:0x0', 'dmask 0 d16') + expect_refused(lambda: build_ps(encode_mimg(IMG_LOAD, tfe=1, d16=1)), 'tfe', 'tfe d16') + expect_refused(lambda: build_ps(encode_mimg(IMG_LOAD, lwe=1, d16=1)), 'lwe', 'lwe d16') + expect_refused(lambda: build_ps(encode_mimg(IMG_LOAD, r128=1, d16=1)), 'r128', 'r128 d16') + expect_refused(lambda: build_ps(encode_mimg(IMG_LOAD, w0_reserved=0x40, d16=1)), 'reserved', 'w0 reserved d16') + expect_refused(lambda: build_ps(encode_mimg(IMG_LOAD, a16=1, d16=1, nsa=1, extra_addrs=(1,))), 'invalid_nsa', 'a16+d16 fake NSA') + + sample_pre = PRE_WORDS + bytes.fromhex('800398be800399be80039abe80039bbe') + for name, op in (('image_sample', IMG_SAMPLE), ('image_sample_lz', IMG_SAMPLE_LZ)): + expect_refused( + lambda o=op: G.Pipeline(VS_WORDS, sample_pre + encode_mimg(o, ssamp=24, d16=1) + POST_WORDS, + root_blob(), ps_hw_inputs=PACKED_INPUT), + f'{name} modifier d16', + f'{name} d16', + ) + + pipe = G.Pipeline(VS_WORDS, PS_WORDS_A, root_blob(), ps_hw_inputs=PACKED_INPUT, rtv_formats=UINT_RTV) + expect_refused( + lambda: pipe.ps.image(['v[4:7]', 'v[8:9]', 's[16:23]'], ['dim:SQ_RSRC_IMG_2D', 'dmask:0xf', 'd16'], 'load'), + 'image_load d16 destination v[4:7] for dmask 0xf', + '4-VGPR dst on dmask 0xf d16', + ) + expect_refused( + lambda: pipe.ps.image(['v[4:5]', 'v[8:9]', 's[16:23]'], ['dim:SQ_RSRC_IMG_2D', 'dmask:0x3', 'd16'], 'load'), + 'image_load d16 destination v[4:5] for dmask 0x3', + '2-VGPR dst on dmask 0x3 d16', + ) + expect_refused( + lambda: pipe.ps.image(['v4', 'v8', 's[16:23]'], ['dim:SQ_RSRC_IMG_2D', 'dmask:0x1', 'd16'], 'load'), + 'image_load address or modifiers', + '1-VGPR addr without a16', + ) + print('refusals: image_load_mip, sample/sample_lz, 1D/cube, 3D/array a16, tfe/lwe/r128/reserved and bad tuple widths refused') + + +def controls(): + check_rounding_formula() + check_decoder_and_masks() + check_srv_format_controls() + check_odd_dmask_consumers() + check_refusals() + + +def check_binary(llvm_mc): + assert assemble(llvm_mc, PS_SOURCE_A) == PS_WORDS_A, 'PS_SOURCE_A encoding mismatch' + assert assemble(llvm_mc, PS_SOURCE_B) == PS_WORDS_B, 'PS_SOURCE_B encoding mismatch' + for key, (inst, expected) in sorted(MIMG_LLVM_MC.items()): + built = assemble(llvm_mc, inst + '\n') + if built != expected: + raise AssertionError(f'{key}: assembled {built.hex()}, recorded {expected.hex()}') + print(f'llvm-mc: {len(MIMG_LLVM_MC)} MIMG encodings and both pixel fixtures match recorded words') + + +def check_decode(library): + from pixel_aot import disassemble + blob = b''.join(MIMG_LLVM_MC[k][1] for k in DECODE_KEYS) + llvm_lines = disassemble(blob, library) + ours = [D.decode_instruction(MIMG_LLVM_MC[k][1], 0)[2] for k in DECODE_KEYS] + assert llvm_lines == ours, f'LLVM vs disasm_rdna2 mismatch: {list(zip(llvm_lines, ours))}' + print(f'libLLVM: {len(DECODE_KEYS)} MIMG instructions match disasm_rdna2.py verbatim') + + +def mutate_hlsl_a(source, mutant): + if mutant == 'rtz': + assert source.count(PACK16_RNE_HLSL) == 1 and source.count(PACK16_D16_HLSL) == 1, source + mutated = (source.replace(PACK16_RNE_HLSL, PACK16_RTZ_HLSL, 1) + .replace('return unorm16 != 0u ? pack16_unorm16(value) : pack16_rne(value);', + 'return pack16_rne(value);', 1)) + elif mutant == 'double_round': + target = 'return unorm16 != 0u ? pack16_unorm16(value) : pack16_rne(value);' + assert source.count(target) == 1, source + mutated = source.replace(target, 'return pack16_rne(value);', 1) + elif mutant == 'unpacked_x': + target_load = 'v4 = pack16_d16(t.x, ud4);' + target_cvt = 'v4 = U(f16tof32(v4));' + assert source.count(target_load) == 1 and source.count(target_cvt) == 1, source + mutated = source.replace(target_load, 'v4 = U(t.x);', 1).replace(target_cvt, 'v4 = v4;', 1) + elif mutant == 'swap_halves': + target = 'v5 = pack16_d16(t.x, ud4) | (pack16_d16(t.z, ud4) << 16);' + assert source.count(target) == 1, source + mutated = source.replace(target, 'v5 = pack16_d16(t.z, ud4) | (pack16_d16(t.x, ud4) << 16);', 1) + elif mutant == 'drop_shift': + target = 'v5 = pack16_d16(t.x, ud4) | (pack16_d16(t.z, ud4) << 16);' + assert source.count(target) == 1, source + mutated = source.replace(target, 'v5 = pack16_d16(t.x, ud4) | pack16_d16(t.z, ud4);', 1) + elif mutant == 'drop_a16': + target = 't = r0.Load(int3(v0 & 0xffffu, v0 >> 16, 0));' + assert source.count(target) == 1, source + mutated = source.replace(target, 't = r0.Load(int3(v0, v1, 0));', 1) + elif mutant == 'drop_nsa': + target = 't = r0.Load(int3(v2, v9, 0));' + assert source.count(target) == 1, source + mutated = source.replace(target, 't = r0.Load(int3(v2, v3, 0));', 1) + elif mutant == 'poison_odd_hi': + t4 = 'v4 = pack16_d16(t.x, ud4);' + t7 = 'v7 = pack16_d16(t.z, ud4);' + assert source.count(t4) == 1 and source.count(t7) == 1, source + mutated = (source.replace(t4, 'v4 = 0xdead0000u | pack16_d16(t.x, ud4);', 1) + .replace(t7, 'v7 = 0xdead0000u | pack16_d16(t.z, ud4);', 1)) + elif mutant == 'unmasked_odd_hi': + t7 = 'v7 = pack16_d16(t.z, ud4);' + sdwa7 = 'v7 = ((v7 >> 0u) & 0xffffu) & ((v7 >> 0u) & 0xffffu);' + assert source.count(t7) == 1 and source.count(sdwa7) == 1, source + mutated = (source.replace(t7, 'v7 = 0xdead0000u | pack16_d16(t.z, ud4);', 1) + .replace(sdwa7, 'v7 = v7;', 1)) + else: + raise ValueError(mutant) + assert mutated != source, mutant + return mutated + + +def run_d16_draw(renderer, adapter, tex_mode, vs, ps, words, directory, tag): + expected_path = directory / f'{tag}.bin' + expected_path.write_bytes(struct.pack('<64I', *words)) + run = subprocess.run( + [renderer, adapter, '--startup-image-load-d16', tex_mode, str(vs), str(ps), str(expected_path)], + capture_output=True, + text=True, + ) + if run.returncode == 77: + print(run.stdout + run.stderr, end='', flush=True) + sys.exit(77) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, (run.stdout, run.stderr) + return run + + +def check_draw(dxc, renderer, adapter, fxc=None): + hlsl_a = G.Pipeline(VS_WORDS, PS_WORDS_A, root_blob(), ps_hw_inputs=PACKED_INPUT, rtv_formats=UINT_RTV).hlsl_ps() + hlsl_b = G.Pipeline(VS_WORDS, PS_WORDS_B, root_blob(), ps_hw_inputs=PACKED_INPUT, rtv_formats=UINT_RTV).hlsl_ps() + mutants = ('rtz', 'double_round', 'unpacked_x', 'swap_halves', 'drop_shift', 'drop_a16', 'drop_nsa', 'unmasked_odd_hi') + + compilers = [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + out_dir = HERE.parent / 'out' + out_dir.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(prefix='image-load-d16-', dir=out_dir) as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, f'vs_{kind}', vs_profile, directory) + ps_a = compile_hlsl(compiler, kind, hlsl_a, f'ps_a_{kind}', ps_profile, directory) + ps_b = compile_hlsl(compiler, kind, hlsl_b, f'ps_b_{kind}', ps_profile, directory) + ps_poison = compile_hlsl(compiler, kind, mutate_hlsl_a(hlsl_a, 'poison_odd_hi'), + f'ps_poison_{kind}', ps_profile, directory) + + for tex_mode in ('r16_unorm', 'rgba32f'): + ref_a = expected_words('A', tex_mode) + ref_b = expected_words('B', tex_mode) + run_a = run_d16_draw(renderer, adapter, tex_mode, vs, ps_a, ref_a, directory, f'ref_a_{tex_mode}_{kind}') + assert run_a.returncode == 0, f'{kind} A {tex_mode} failed:\n{run_a.stdout}{run_a.stderr}' + run_b = run_d16_draw(renderer, adapter, tex_mode, vs, ps_b, ref_b, directory, f'ref_b_{tex_mode}_{kind}') + assert run_b.returncode == 0, f'{kind} B {tex_mode} failed:\n{run_b.stdout}{run_b.stderr}' + run_p = run_d16_draw(renderer, adapter, tex_mode, vs, ps_poison, ref_a, + directory, f'poison_{tex_mode}_{kind}') + assert run_p.returncode == 0, f'{kind} poison_odd_hi {tex_mode} leaked:\n{run_p.stdout}{run_p.stderr}' + print(f'{kind} {tex_mode}: fixtures A/B and odd-dmask upper-half poison check matched all words', flush=True) + + # Every mutation must fail against the reference and match its mutated model across every + # applicable texture mode (drop_shift uses rgba32f because t.z is 0.0 on R16_UNORM; double_round + # uses r16_unorm to exercise 0xffaf -> 0x3bfe vs 0x3bfd and 0xffef -> 0x3c00 vs 0x3bff). + for mut in mutants: + ps_mut = compile_hlsl(compiler, kind, mutate_hlsl_a(hlsl_a, mut), f'mut_{mut}_{kind}', ps_profile, directory) + if mut == 'drop_shift': + modes = ('rgba32f',) + elif mut == 'double_round': + modes = ('r16_unorm',) + else: + modes = ('r16_unorm', 'rgba32f') + for tex_mode in modes: + ref_words = expected_words('A', tex_mode) + fail_run = run_d16_draw(renderer, adapter, tex_mode, vs, ps_mut, ref_words, + directory, f'fail_{mut}_{tex_mode}_{kind}') + assert fail_run.returncode == 1, ( + f'{kind} mutant {mut} ({tex_mode}) unexpectedly passed:\n{fail_run.stdout}{fail_run.stderr}' + ) + mut_words = expected_words('A', tex_mode, mutant=mut) + match_run = run_d16_draw(renderer, adapter, tex_mode, vs, ps_mut, mut_words, + directory, f'model_{mut}_{tex_mode}_{kind}') + assert match_run.returncode == 0, ( + f'{kind} mutant {mut} ({tex_mode}) did not match model:\n{match_run.stdout}{match_run.stderr}' + ) + print(f'{kind} negative control ({mut}): rejected against reference and matched mutated model', flush=True) + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'binary' and len(args) == 1: + check_binary(args[0]) + elif mode == 'decode' and len(args) == 1: + check_decode(args[0]) + elif mode == 'draw' and len(args) in (3, 4): + controls() + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_image_load_mip_check.py b/tests/startup_image_load_mip_check.py index 0f72ef271..0fb4bd69d 100644 --- a/tests/startup_image_load_mip_check.py +++ b/tests/startup_image_load_mip_check.py @@ -68,7 +68,17 @@ def check_plain_load_layouts(llvm_mc): # Patch the length field and append a fake NSA word to check that the decoder preserves the refusal. invalid_nsa = '0a0f00f00004044001000000' - for flag, encoded in (('d16', '080f00f000040480'), ('tfe', '080f01f000040400'), + d16_ps = shader(bytes.fromhex('080f00f000040480')).hlsl_ps() + assert 'v4 = pack16_d16(t.x, ud4) | (pack16_d16(t.y, ud4) << 16);' in d16_ps, d16_ps + assert 'v5 = pack16_d16(t.z, ud4) | (pack16_d16(t.w, ud4) << 16);' in d16_ps, d16_ps + try: + shader(bytes.fromhex('080f04f000040480')) + except G.Unsupported as error: + assert 'image_load_mip' in str(error) and 'd16' in str(error), error + else: + raise AssertionError('d16 image_load_mip accepted') + + for flag, encoded in (('tfe', '080f01f000040400'), ('r128', '088f00f000040400'), ('lwe', '080f02f000040400'), ('reserved', '084f00f000040400'), ('dmask:0x0', '080000f000040400'), ('a16', '100f00f000040440'), ('invalid_nsa', invalid_nsa)): diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index b59ea9795..ccd7a4e96 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -105,7 +105,8 @@ int main(int argc, char** argv) void* device = nullptr; void* pso = nullptr; const bool hardware = draw && std::strcmp(argv[4], "hardware") == 0; - if (const int rc = prepare_stream_pipeline(argv[1], argv[2], argv[3], hardware, bc7.blocks != nullptr, + const bool textured = bc7.blocks != nullptr || GetEnvironmentVariableW(L"X2W_TEST_D16_SRV", nullptr, 0) != 0; + if (const int rc = prepare_stream_pipeline(argv[1], argv[2], argv[3], hardware, textured, adapter, device, pso)) return rc; if (GetEnvironmentVariableW(L"X2W_TEST_TRUNCATED_ONLY", nullptr, 0)) return 0; if (argc == 4) return 0; diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index 5598e0c02..597fa8182 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -287,6 +287,9 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* } else if (GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_BUFFER_SRV", nullptr, 0)) { extern int draw_address_buffer_srvs(ID3D12Device*, void*, void*); if (const int result = draw_address_buffer_srvs(desktop.Get(), guest, list)) return result; + } else if (GetEnvironmentVariableW(L"X2W_TEST_D16_SRV", nullptr, 0)) { + extern int draw_d16_srvs(ID3D12Device*, void*, void*); + if (const int result = draw_d16_srvs(desktop.Get(), guest, list)) return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_VERTEX_FETCH", nullptr, 0)) { // TEXCOORD float3 in slot 0 and POSITION float3 in slot 1, 12 bytes each; vertices 0-2 are unused. Vertices // 3-8 are drawn from start vertex 3: positions cover pixels [1, 3) x [1, 3) of the 8x4 target, texture diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 6d22c6f80..c09573f93 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -440,7 +440,13 @@ def smem_mods(mods): class Stage: """Translates one stage. Shares the resource and entry-constant registries of its pipeline.""" - needs_sm6 = False # the lowering uses a shader model 6.0 intrinsic, so the stage cannot compile as 5.1 + # Immutable fallbacks for unit probes that bypass __init__; __init__ and translate() assign fresh + # per-instance sets, so nothing is shared across Stage instances. + needs_sm6 = False # the lowering uses a shader model 6.0 intrinsic, so the stage cannot compile as 5.1 + exec_known = False # unit probes without __init__ customize this explicitly when needed + low16_only_v = () # VGPRs whose upper 16 bits are undefined after odd-dmask d16 image_load + pinned_low16_v = () # low16_only_v live across basic-block boundaries + whole_read_v = () # VGPRs read outside a proven low-16-bit consumer def __init__(self, pipe, kind, code, refusals=None, decoded=None): self.pipe, self.kind = pipe, kind @@ -509,7 +515,13 @@ def S(self, n): self.used_s.add(n) return 's%d' % n - def u(self, tok): + def note_whole_read(self, reg): + if reg in self.low16_only_v: + raise Unsupported('whole-word read of v%d after odd d16 image_load' % reg) + if isinstance(self.whole_read_v, set): + self.whole_read_v.add(reg) + + def u(self, tok, *, low16_only=False): """uint expression for a 32-bit operand.""" if tok in ('vcc_lo', 'vcc'): return 'vcc' @@ -523,7 +535,10 @@ def u(self, tok): r = reg_range(tok) if r: if r[0] == 'v': - self.used_v.add(r[1]) + for reg in range(r[1], r[2] + 1): + self.used_v.add(reg) + if not low16_only: + self.note_whole_read(reg) return 'v%d' % r[1] return self.S(r[1]) if tok in FLOATS: @@ -578,12 +593,36 @@ def is_const(self, n): s = self.sym.get(n) return s[1] if s and s[0] == 'const' else None + def const_u32(self, tok): + r = reg_range(tok) + if r: + if r[0] == 's' and r[1] == r[2]: + c = self.is_const(r[1]) + return None if c is None else (c & 0xffffffff) + return None + if tok in FLOATS: + return fbits(FLOATS[tok]) + try: + return int(tok, 0) & 0xffffffff + except ValueError: + return None + def emit(self, text): self.lines.append(text) - def set_v(self, n, expr): + def clear_low16(self, n): + if isinstance(self.low16_only_v, set) and self.exec_known and n not in self.pinned_low16_v: + self.low16_only_v.discard(n) + + def set_v(self, n, expr, *, low16_only=False): if hasattr(self, 'uniform_v'): self.uniform_v.discard(n) + if low16_only: + if not isinstance(self.low16_only_v, set): + self.low16_only_v = set() + self.low16_only_v.add(n) + else: + self.clear_low16(n) self.used_v.add(n) self.emit('v%d = %s;' % (n, expr) if self.exec_known else 'if (exec & 1) v%d = %s;' % (n, expr)) @@ -699,11 +738,15 @@ def translate(self): self.uniform_v = set() self.varying_s = set() self.scc_uniform = True + self.low16_only_v = set() # VGPRs whose upper 16 bits are undefined after odd-dmask d16 image_load + self.pinned_low16_v = set() # low16_only_v live across basic-block boundaries + self.whole_read_v = set() # VGPRs read outside a proven low-16-bit consumer self.has_branches = bool(targets) start = 0 refusals = getattr(self, 'refusals', None) # unit probes build a Stage without __init__ for off, n, name, asm in self.ins: if off in targets and off != start: + self.pinned_low16_v.update(self.low16_only_v) self.blocks.append((start, self.lines, None)) self.lines, start = [], off self.pc = off @@ -720,10 +763,18 @@ def translate(self): refusals.append((handler_error(name, error, refusals), self.kind)) continue if term: + self.pinned_low16_v.update(self.low16_only_v) self.blocks.append((start, self.lines, term)) self.lines, start = [], off + n if self.lines: self.blocks.append((start, self.lines, None)) + self.pinned_low16_v.update(self.low16_only_v) + leak = self.pinned_low16_v & self.whole_read_v + if leak: + reason = 'whole-word read of v%d after odd d16 image_load' % min(leak) + if refusals is None: + raise Unsupported(reason) + refusals.append((reason, self.kind)) def tracks_uniformity(self): return all(hasattr(self, name) for name in ('uniform_v', 'varying_s', 'scc_uniform')) @@ -879,15 +930,22 @@ def lower(self, base, asm, ops, mods): # accepted here, because ignoring them would silently change the operand. if any(m not in ('clamp', 'mul:2', 'mul:4', 'div:2') for m in mods): raise Unsupported('%s with %s' % (base, mods)) + low16 = base in ('v_cvt_f32_f16', 'v_cvt_f32_ubyte0', 'v_cvt_f32_ubyte1') return self.set_vf(reg_range(ops[0])[1], - text_f.format(*[self.u(o) for o in ops[1:1 + arity]]), mods) + text_f.format(*[self.u(o, low16_only=low16) for o in ops[1:1 + arity]]), mods) if base in VEC_U: arity, text = VEC_U[base] if mods: raise Unsupported('%s with %s' % (base, mods)) if len(ops) != arity + 1: raise Unsupported('%s with %d operands, expected %d' % (base, len(ops), arity + 1)) - return self.set_v(reg_range(ops[0])[1], text.format(*[self.u(o) for o in ops[1:1 + arity]])) + if base == 'v_and_b32': + c0, c1 = self.const_u32(ops[1]), self.const_u32(ops[2]) + args = [self.u(ops[1], low16_only=c1 is not None and (c1 & 0xffff0000) == 0), + self.u(ops[2], low16_only=c0 is not None and (c0 & 0xffff0000) == 0)] + else: + args = [self.u(o) for o in ops[1:1 + arity]] + return self.set_v(reg_range(ops[0])[1], text.format(*args)) if base in SCA: return self.scalar(base, ops) if base in ('buffer_load_format_x', 'buffer_load_format_xy', @@ -1036,7 +1094,9 @@ def sdwa(self, base, ops, mods): selection = fields.get('src%d_sel' % index) if not selection: raise Unsupported('%s SDWA without src%d_sel' % (base, index)) - sources.append(sdwa_source(self.u(token), selection, sext)) + low16 = selection in ('BYTE_0', 'BYTE_1', 'WORD_0') or ( + selection == 'DWORD' and not sext and base in ('v_cvt_f32_f16', 'v_cvt_f32_ubyte0', 'v_cvt_f32_ubyte1')) + sources.append(sdwa_source(self.u(token, low16_only=low16), selection, sext)) result = text.format(*sources) if float_result: # Output modifiers scale and then clamp the float value; dst_sel writes its bit pattern. @@ -1049,8 +1109,10 @@ def sdwa(self, base, ops, mods): if SDWA_SEL[select][1] < 32: result = '(%s)' % result destination = reg_range(ops[0])[1] - self.set_v(destination, sdwa_dest(result, select, fields.get('dst_unused', 'UNUSED_PAD'), - 'v%d' % destination)) + unused = fields.get('dst_unused', 'UNUSED_PAD') + keep_low16 = (unused == 'UNUSED_PRESERVE' and select not in ('DWORD', 'WORD_1') and + destination in self.low16_only_v) + self.set_v(destination, sdwa_dest(result, select, unused, 'v%d' % destination), low16_only=keep_low16) # scalar ALU with descriptor-word bookkeeping def scalar(self, base, ops): @@ -1663,19 +1725,33 @@ def image(self, ops, mods, how): if len(cs) != (4 if three else 3): raise Unsupported('image_sample_l with %d address registers' % len(cs)) lod, cs = cs[-1], cs[:-1] - tex = self.pipe.resource(self.descriptor(ops[2]), kinds[dim]) + desc_key = self.descriptor(ops[2]) + tex = self.pipe.resource(desc_key, kinds[dim]) if how in ('load', 'load_mip'): # image_load_mip addresses x, y, [slice or z] and then the mip, so a 2D array is four registers # and Texture2DArray.Load takes int4(x, y, slice, mip) like a volume's int4(x, y, z, mip). axes = 3 if three else 2 packed_2d = how == 'load' and dim == 'SQ_RSRC_IMG_2D' and 'a16' in mods + packed_d16 = how == 'load' and 'd16' in mods allowed = ('unorm', 'glc', 'slc', 'dlc') if packed_2d: allowed += ('a16',) + if packed_d16: + allowed += ('d16',) unsupported = any(not m.startswith(('dim:', 'dmask:')) and m not in allowed for m in mods) - wrong_address = (packed_2d and len(cs) != 1) or (how == 'load_mip' and len(cs) != axes + 1) + expected_addr = 1 if packed_2d else (axes + 1 if how == 'load_mip' else axes) + wrong_address = len(cs) != expected_addr if unsupported or wrong_address or not dmask: raise Unsupported('image_%s address or modifiers: %s' % (how, ' '.join(mods))) + if packed_d16: + expected_dst = (bin(dmask).count('1') + 1) // 2 + if not dst or dst[0] != 'v' or dst[2] - dst[1] + 1 != expected_dst or dst[2] > 255: + raise Unsupported('image_load d16 destination %s for dmask %#x' % (ops[0], dmask)) + res = self.pipe.resources[desc_key] + if res['index'] in self.pipe.srv_formats: + fmt = self.pipe.srv_formats[res['index']] + if fmt not in D16_EXACT_SRV_FORMATS: + raise Unsupported('image_load d16 unsupported SRV format %d' % fmt) if packed_2d: packed = self.u(cs[0]) address = ['%s & 0xffffu' % packed, '%s >> 16' % packed] @@ -1716,11 +1792,22 @@ def image(self, ops, mods, how): else: call = '%s.Sample(%s, %s)' % (tex, smp, uv) self.emit('t = %s;' % call) - n = dst[1] - for bit, comp in enumerate('xyzw'): - if dmask & (1 << bit): - self.set_v(n, 'U(t.%s)' % comp) - n += 1 + if how == 'load' and 'd16' in mods: + res = self.pipe.resources[desc_key] + res['d16_exact'] = True + mode_arg = 'ud%d' % self.pipe.ud(('d16unorm16', res['index'])) + self.pipe.uses_pack16_rne = True + halves = ['pack16_d16(t.%s, %s)' % (comp, mode_arg) for bit, comp in enumerate('xyzw') if dmask & (1 << bit)] + for i in range(0, len(halves), 2): + odd_tail = i + 1 == len(halves) + expr = halves[i] if odd_tail else '%s | (%s << 16)' % (halves[i], halves[i + 1]) + self.set_v(dst[1] + i // 2, expr, low16_only=odd_tail) + else: + n = dst[1] + for bit, comp in enumerate('xyzw'): + if dmask & (1 << bit): + self.set_v(n, 'U(t.%s)' % comp) + n += 1 def image_compare(self, ops, mods, how): """image_sample_c and image_sample_c_lz: a 2D or 2D-array depth comparison returning one float. @@ -1872,6 +1959,8 @@ def op_v_swap_b32(self, ops, mods): if any(not r or r[0] != 'v' or r[1] != r[2] or r[1] > 255 for r in regs): raise Unsupported('v_swap_b32 operands %s, %s: expected two single VGPRs' % (ops[0], ops[1])) dst, src = regs[0][1], regs[1][1] + for reg in (dst, src): + self.note_whole_read(reg) body = '{ uint t = v%d; v%d = v%d; v%d = t; }' % (dst, dst, src, src) # Uniformity travels with the value; under an unknown exec mask neither register keeps the proof. uniform = (dst in self.uniform_v and self.exec_known, src in self.uniform_v and self.exec_known) @@ -1931,7 +2020,7 @@ def mix(self, ops, mods, high): def operand(tok, is_half): if not is_half or tok in ('-0', '0'): return self.f(tok) - return 'f16tof32(%s)' % self.u(tok) + return 'f16tof32(%s)' % self.u(tok, low16_only=True) expr = '%s * %s + %s' % tuple(operand(t, s) for t, s in zip(ops[1:4], sel)) if 'clamp' in mods: expr = 'saturate(%s)' % expr @@ -1940,7 +2029,8 @@ def operand(tok, is_half): if high: self.set_v(d, '(v%d & 0xffffu) | (f32tof16(%s) << 16)' % (d, expr)) else: - self.set_v(d, '(v%d & 0xffff0000u) | f32tof16(%s)' % (d, expr)) + keep_low16 = d in self.low16_only_v + self.set_v(d, '(v%d & 0xffff0000u) | f32tof16(%s)' % (d, expr), low16_only=keep_low16) def op_v_fma_mixlo_f16(self, ops, mods): self.mix(ops, mods, False) @@ -1981,6 +2071,8 @@ def shift64(self, ops, mods, helper): if hasattr(self, 'uniform_v'): self.uniform_v.discard(dst[1]) self.uniform_v.discard(dst[2]) + self.clear_low16(dst[1]) + self.clear_low16(dst[2]) self.used_v.update((dst[1], dst[2])) self.emit(body if self.exec_known else 'if (exec & 1) ' + body) @@ -2019,7 +2111,7 @@ def compare_sdwa_sources(self, base, typ, ops, mods, *, float_src0=False): continue if sext: token = token[len('sext('):-1] - word = sdwa_source(self.u(token), selection, sext) + word = sdwa_source(self.u(token, low16_only=selection in ('BYTE_0', 'BYTE_1', 'WORD_0')), selection, sext) sources.append('int(%s)' % word if typ == 'i32' else word) return sources @@ -2077,7 +2169,7 @@ def compare(self, base, ops, mods=()): if token in FLOATS or re.fullmatch(r'-[1-9]\d*', token): # A float-printed operand would otherwise be lowered as its binary32 bit pattern. raise Unsupported('%s source %s: f16 class compares need the raw half' % (base, value)) - bits = self.u(token) + bits = self.u(token, low16_only=True) if absolute: bits = '(%s & 0x7fffu)' % bits if negative: @@ -2458,11 +2550,20 @@ def read(fmt, data, offset): UINT_RTVS = frozenset((3, 7, 12, 17, 25, 30, 36, 42, 50, 57, 62)) SINT_RTVS = frozenset((4, 8, 14, 18, 32, 38, 43, 52, 59, 64)) FLOAT32_RTVS = frozenset((2, 6, 16, 41)) +# DXGI_FORMAT values independently verified exact for D16 image_load, matching d16_srv_mode() +# in src/startup_stubs/d16_image_format.h (#2023): 32-bit float and 8-bit UNORM views (exact via +# pack16_rne) plus 16-bit UNORM views (exact via pack16_unorm16). +D16_FLOAT_EXACT_SRV_FORMATS = frozenset((2, 6, 16, 21, 28, 41, 49, 61, 65, 87, 88)) +D16_UNORM16_SRV_FORMATS = frozenset((11, 35, 56)) +D16_EXACT_SRV_FORMATS = D16_FLOAT_EXACT_SRV_FORMATS | D16_UNORM16_SRV_FORMATS class Pipeline: + uses_pack16_rne = False + srv_formats = () + def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=(), ps_hw_inputs=None, vs_fetch=None, - refusals=None, decoded=None, ps_attr_map=None): + refusals=None, decoded=None, ps_attr_map=None, srv_formats=()): self.root = parse_root(root_blob) self.ps_attr_map = ps_attr_map # stream_interface(): pixel attribute -> (vertex parameter, component mask); None pairs by number self.vs_fetch = vs_fetch # stream_fetch(): the loads the vertex stage's entry call stands for @@ -2477,8 +2578,10 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( widths = (2, 2, 2, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1) self.packed_position_vgpr = sum(w for bit, w in enumerate(widths) if addr & (1 << bit)) self.rtv_formats = rtv_formats + self.srv_formats = dict(srv_formats) if isinstance(srv_formats, dict) else dict(enumerate(srv_formats)) self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap self.uses_sampler_heap = False + self.uses_pack16_rne = False self.resources = {} # key -> dict(index, kind) self.samplers = {} # key -> index self.uds = [] # entry-constant sources @@ -2593,6 +2696,39 @@ def common(self): out.append('SamplerState qh[%d] : register(s0, space%d);' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE)) out.append('uint x2w_sampler_entry(uint offset) { return (offset & 15u) != 0 || offset >= %du ? %du : offset >> 4; }' % (16 * SAMPLER_HEAP_FALLBACK, SAMPLER_HEAP_FALLBACK)) + if self.uses_pack16_rne: + # IEEE binary32 to binary16 round-to-nearest-even (quieting NaN while preserving its sign, + # matching RDNA 2 hardware on binary32 inputs), plus exact UNORM16 ratio-to-half conversion + # (avoiding binary32 double-rounding at 0xffaf -> 0x3bfd and 0xffef -> 0x3bff). + out.extend(( + 'uint pack16_rne(float value) {', + ' uint bits = asuint(value), sign = (bits >> 16) & 0x8000u, abs_bits = bits & 0x7fffffffu;', + ' if (abs_bits > 0x7f800000u) return sign | 0x7e00u;', + ' if (abs_bits >= 0x477ff000u) return sign | 0x7c00u;', + ' if (abs_bits >= 0x38800000u) {', + ' uint shifted = abs_bits - 0x38000000u;', + ' return sign | ((shifted + 0x00000fffu + ((shifted >> 13) & 1u)) >> 13);', + ' }', + ' if (abs_bits < 0x33000000u) return sign;', + ' uint sig = 0x00800000u | (abs_bits & 0x007fffffu), shift = 126u - (abs_bits >> 23);', + ' uint half_m = sig >> shift, rem = sig & ((1u << shift) - 1u), mid = 1u << (shift - 1u);', + ' if (rem > mid || (rem == mid && (half_m & 1u) != 0u)) half_m += 1u;', + ' return sign | half_m;', + '}', + 'uint pack16_unorm16(float value) {', + ' uint u = uint(saturate(value) * 65535.0 + 0.5);', + ' if (u <= 3u) return u << 8;', + ' if (u >= 65535u) return 0x3c00u;', + ' uint msb = firstbithigh(u);', + ' uint num = u << (26u - msb);', + ' uint q = num / 65535u;', + ' if (num - q * 65535u > 32767u) q += 1u;', + ' return ((msb - 1u) << 10) + (q - 1024u);', + '}', + 'uint pack16_d16(float value, uint unorm16) {', + ' return unorm16 != 0u ? pack16_unorm16(value) : pack16_rne(value);', + '}', + )) return out def interface(self, for_pixel): @@ -2675,6 +2811,8 @@ def manifest(self): if where is None: raise Unsupported('resource through %s' % (source,)) lines.append('srv %d %s %s' % (r['index'], r['kind'], where)) + if r.get('d16_exact'): + lines.append('d16srv %d exact' % r['index']) for key, i in self.samplers.items(): comparison = key[0] == 'cmp' lines.append('%s %d %s' % ('smpc' if comparison else 'smp', i, ' '.join('0x%x' % w for w in key[comparison:])))