diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index e77c937a52..9f2d82948d 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -146,6 +146,7 @@ jobs: (["tests/startup_compute_lds_b64_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_compute_lds_b128_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_calculated_target_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_far_early_out_check.py", "binary", "llvm-mc-15", "libLLVM-15.so.1"], {}), (["tests/startup_gfx2hlsl_join_symbols_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_joined_table_pointer_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_swap_check.py", "binary", "llvm-mc-15"], {}), @@ -320,6 +321,7 @@ jobs: tests/startup_gfx2hlsl_heap_record_check.py \ tests/startup_gfx2hlsl_heap_word_check.py \ tests/startup_gfx2hlsl_calculated_target_check.py \ + tests/startup_gfx2hlsl_far_early_out_check.py \ tests/startup_triage_run_check.py \ tests/startup_run_ps1_check.py \ tests/startup_run_sh_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 378ebd05da..8b5b46c435 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -172,7 +172,9 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_spill_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_mask_spill_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_check.py +./out/pe-env/bin/python -B tests/startup_pixel_image_store_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_d16_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_image_store_3d1d_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_heap_record_check.py ./out/pe-env/bin/python -B tests/startup_compute_store_format_xyzw_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_heap_word_check.py @@ -273,6 +275,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_brev_fold_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_const_copy_join_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_pack_b32_f16_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_pk_minmax_check.py ./out/pe-env/bin/python -B tests/run_checks_parallel_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_handler_arity_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_getpc_refusal_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 519b38d8d0..fef07e4850 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3493,6 +3493,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_image_store_check.py") add_test(NAME startup_compute_image_store_d16 COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_image_store_d16_check.py") + add_test(NAME startup_gfx2hlsl_image_store_3d1d COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_image_store_3d1d_check.py") add_test(NAME startup_gfx2hlsl_heap_record COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_heap_record_check.py") add_test(NAME startup_gfx2hlsl_heap_word COMMAND "${INTAKE_PYTHON}" -B @@ -3871,7 +3873,7 @@ if(EXISTS "${INTAKE_PYTHON}") # Startup shader translator: a plain image_sample past a uniform join keeps its implicit LOD (Sample, not level 0). add_test(NAME startup_image_sample_implicit_lod_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_image_sample_implicit_lod_check.py") - # Startup shader translator: image_get_lod on a 2D texture (CalculateLevelOfDetail / Unclamped). + # Startup shader translator: image_get_lod on 2D and 2D-array textures. add_test(NAME startup_gfx2hlsl_image_get_lod_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_image_get_lod_check.py") foreach(adapter IN ITEMS warp hardware) @@ -4933,6 +4935,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_copied_vertex_srv_check.py" "$" "${backend}") set_tests_properties(startup_copied_vertex_srv_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_table_alias_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_table_alias_check.py" + "$" "${backend}") + set_tests_properties(startup_table_alias_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) add_test(NAME startup_direct_index_late_write_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_direct_index_late_write_check.py" "$" "${backend}") @@ -4975,7 +4981,8 @@ if(EXISTS "${INTAKE_PYTHON}") # queue has run them. The ring control fills them from the shared upload ring, which must refuse the uploads # past its 256 MiB cap while the queue is held. gate-ring-reuse: once those submits have completed, the ring # must accept a new upload again. - foreach(gate IN ITEMS gate gate-ring gate-ring-reuse) + # gate-ring-keep(-release): a closed list that is never Reset, without and with X2W_D3D12_RING_RELEASE_AT_SUBMIT. + foreach(gate IN ITEMS gate gate-ring gate-ring-reuse gate-ring-keep gate-ring-keep-release) string(REPLACE "-" "_" gate_name "${gate}") add_test(NAME startup_address_console_${gate_name}_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_console_check.py" diff --git a/CMakePresets.json b/CMakePresets.json index 19a646b004..0008441a2a 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -29,7 +29,7 @@ "d3d12_sdk_check", "era_heap_check", "xmem_shim", "offscreen_check", "cpu_fuzz_lifted", "cpu_fuzz_lifted_o2", "pe_map", "intake_candidate", "archive_gpu_reader", "archive_codec_gpu", "archive_texture_gpu_lifted", "startup_launch_probe", - "startup_indirect_dispatch", "startup_indirect_draw_indexed" + "startup_indirect_dispatch", "startup_indirect_draw_indexed", "startup_present_readback_check" ] }, { "name": "release", "configurePreset": "release" } @@ -42,7 +42,7 @@ "displayName": "Windows pull request smoke tests", "filter": { "include": { - "name": "^(desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key)$" + "name": "^(desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key|startup_present_readback)$" } } }, diff --git a/README.md b/README.md index 9b94df39ff..c0b5dd147d 100644 --- a/README.md +++ b/README.md @@ -226,6 +226,7 @@ Results are grouped by adapter. Open a report for the driver, build and any capa | AMD Radeon RX 9070 XT (driver 32.0.32015.16001) | 64 | Passed, 64 lanes; lane range 32–64 | 408 queries passed | [RX 9070 XT report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063426420) · [32.0.32029.2010 retest, D3D12 warning 989](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063787553) · [32.0.32015.16001 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064744246) · [32.0.32015.7029 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065371244) · [32.0.32029.2010 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065554754) · [32.0.32029.2010 run 3](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066677824) · [32.0.32029.2010 run 4](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066940493) · [32.0.32029.2010 run 5](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7068364653) · [32.0.32015.12012 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7068740351) · [32.0.32029.2010 source build at bc24dfd](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7071126769) · [32.0.32029.2010 run 6, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7085696786) · [32.0.31044.16 source build, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7113579998) · [32.0.32015.7029 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7133166858) · [32.0.32029.2010 source build at 49f53ae6, Windows build 26200.9974, debug layer unavailable](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7190843348) | | NVIDIA GeForce RTX 4060 Ti (driver 32.0.16.1742) | 32 | Skipped, lane range 32–32 | 408 queries passed | [Hardware report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063740292) · [32.0.16.2124 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066549178) | | AMD Radeon RX 7900 GRE (driver 32.0.32015.7029) | 32 | Passed, 64 lanes | 408 queries passed | [Hardware report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063746749) | +| AMD Radeon RX 7900 XT (driver 32.0.32029.2010) | 32 | Skipped, Shader Model 6.6 unavailable (capped at 6.5 on Windows 10 build 19045) | 408 queries passed | [Windows 10 report, debug layer unavailable](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7207902686) | | NVIDIA GeForce RTX 4070 Ti SUPER (driver 32.0.16.1088) | 32 | Skipped, lane range 32–32 | 408 queries passed | [Hardware report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063783462) · [32.0.15.7270 report, Windows 10](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066125394) | | NVIDIA GeForce RTX 5080 (driver 32.0.16.2124) | 32 | Skipped, lane range 32–32 | 408 queries passed | [Hardware report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063834333) · [32.0.16.1088 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065170340) · [32.0.16.1664 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065546749) · [Independent run, same driver](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065671431) · [32.0.16.1692 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7069515442) · [32.0.16.1714 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7073236219) · [32.0.16.2114 report, debug layer enabled, adapter filter RTX 5080](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7120729216) | | NVIDIA GeForce RTX 5080 Laptop GPU (driver 32.0.15.8142) | 32 | Skipped, lane range 32–32 | Passed | [Package report by ChazY11](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7118193451) | diff --git a/docs/experiments.md b/docs/experiments.md index 2800e39a99..2365cd0c25 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -1972,6 +1972,8 @@ Run `ctest --preset dev --no-tests=error -R '^cpu_aot_xchg$' -V`. `cpu_hint_nop_fixture` compares native execution against the lowered body for the same bytes. One generator (`tests/cpu/hint_nop_fixture.py`) assembles the exact byte sequences and lowers the same instructions, so the two arms cannot drift apart. A prologue sets RAX from the input and the arithmetic flags from an `ADD`; each case then executes the encoding under test and stores the flags in AH with `LAHF`, so a changed register or flag shows up as a different return value. The memory forms are handed a pointer to a `PAGE_NOACCESS` page as the base register, and both the native and the lifted call run under the same exception guard, so a lowering that evaluated the operand is reported as a mismatch rather than crashing the fixture. Two controls make that meaningful: a real load from the same page must fault, and a real `mov eax, imm` with the same inputs must return a different value. Run `ctest --preset dev --no-tests=error -R '^cpu_hint_nop_fixture$' -V`. +**Non-temporal stores.** The shared lowering accepts the legacy SSE stores `MOVNTPS` (`0F 2B /r`), `MOVNTPD` (`66 0F 2B /r`) and `MOVNTDQ` (`66 0F E7 /r`) from XMM0 to XMM2, the registers it models for `MOVAPS`, and `MOVNTI` (`0F C3 /r`) from a 32- or 64-bit register. Each lowers to the streaming-store intrinsic of its width (`_mm_stream_si128`, `_mm_stream_si32`, `_mm_stream_si64`), so the non-temporal hint and the weak ordering stay the guest's: only the guest's own `SFENCE`, `MFENCE` or a locked instruction orders them. No flag changes. The XMM forms test the target against 15 first and raise the aligned-operand fault, as `MOVAPS` does, before anything is written; `MOVNTI` has no alignment requirement. The MMX `MOVNTQ`, the SSE4a scalar `MOVNTSS` and `MOVNTSD`, the VEX `VMOVNTPS`, `VMOVNTPD` and `VMOVNTDQ`, the `MOVNTDQA` load and XMM3 and above stay refused. `cpu_nt_store` (`tests/cpu/nt_store_check.py`) pins eight accepted encodings to their intrinsic and alignment test and eight neighbours to a refusal. `cpu_nt_store_fixture` (`tests/cpu/nt_store_fixture.py`) generates the native bytes and the lowered C++ from one list and runs both into separate sentinel-filled buffers: stores at aligned and displaced targets and `MOVNTI` at odd addresses must match native and an independent reference byte for byte; misaligned XMM targets must raise the access violation at address -1 natively and translated with nothing written; and a `PAGE_NOACCESS` target must raise the same write fault at the same address. Three controls must break a rule: `noalign` removes the alignment test and stores with `memcpy` (the streaming intrinsic is itself `MOVNTDQ` and would fault anyway), so it must store where native faults; `nostore` replaces the native store with a NOP and must miss the reference; and a native `MOVUPS` to the misaligned target must not fault, so the fault comes from the alignment rule. Run `ctest --preset dev --no-tests=error -R '^cpu_nt_store(_fixture)?$' -V`; the `release` preset runs the same checks. + A 67h address-size prefix selects 32-bit addressing. The lowering wraps base + index × scale + displacement at 32 bits and zero-extends the result, ignoring the upper halves of the registers as the hardware does. In this mode iced reports a displacement of -8 as `0xfffffff8`, so the wrap is also needed when the upper halves are zero. EIP-relative operands are rejected because the hardware adds the low 32 bits of the runtime RIP, which an RVA binding cannot represent. `cpu_aot_address_size` builds `lea`, load and store forms such as `lea rax, [ecx+edx*8-8]` and `mov [ecx+edx], r8d` from MASM source. It translates them and compares both images with a 32-bit reference over wrapped sums and upper-half noise. The loads and stores use a page committed below 4 GiB, and each store must leave the rest of the page unchanged. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_address_size$' -V`. XLATB replaces AL with the byte at RBX + AL. AL is zero-extended, and bits 8 to 63 of RAX and the flags are unchanged. With a 67h prefix the base is EBX and the sum wraps at 32 bits, so the upper half of RBX is ignored. A REX.W prefix (`48 d7`) does not change the operation. `cpu_aot_xlatb` builds four exports from [MASM source](../tests/cpu/xlatb.asm): the plain, REX.W and 67h forms, and two lookups in a row. Each export runs on a 256-byte permutation table in a page committed below 4 GiB. The check compares RAX and ZF/CF for every AL value, with noise in the upper bits of RAX and, for the 67h form, in the upper half of RBX, against the native DLL and an independent reference. Three controls mutate the generated C++ and must mismatch: `signed` sign-extends AL, `noaddr32` keeps the upper half of RBX in the 67h sum (whose reads fault), and `clear` writes the loaded byte over all of RAX. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_xlatb$' -V`. @@ -4514,6 +4516,36 @@ cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^compute_store_aot_mtbuf_load_(warp|hardware)$' -V ``` +### Pixel-stage sparse image stores + +A pixel-stage 2D `image_store` with a partial DMASK writes only the selected +components. `dmask:0x5` lowers to `w0[uint2(v0, v1)].xz = float2(...)`. The +store does not read the texel, so two invocations can update disjoint channels +of one texel without writing the other invocation's stale channels back. A +float4 read-modify-write is not used. Compute stores, D16 stores and array +stores still require `dmask:0xf`. A full-mask pixel 2D-array store stays a +float4 assignment, `w0[uint3(x, y, layer)] = asfloat(uint4(...))`, with a +`tex2da` manifest line. + +The source-built fixture draws two pixels in one pass. Both address texel +(1, 2). One invocation stores x (`dmask:0x1`, 1.0) and the other stores z +(`dmask:0x4`, 2.0). The image starts at -1 in every channel, so the texel +must read back (1, -1, 2, -1) and every other texel must stay -1. Writing the +second value into y instead of z must mismatch. A manifest line that ends in +`typedload` is refused before the draw when the format has no typed UAV load. +The component store does not ask for that load. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_pixel_image_store' -V +``` + +```bash +python3 -B tests/startup_pixel_image_store_check.py +python3 -B tests/startup_pixel_image_store_check.py binary llvm-mc-15 +``` + +Refs #2618. + ### gfx1013 2D float image stores and mip loads The fixed compute profile accepts a 2D `R32G32B32A32_FLOAT` `image_store` @@ -4761,6 +4793,8 @@ LLVM and LLD 15 build the code object and verify one instruction of each kind in its disassembly. The CPU witnesses and mutations pass independently. Native readback remains pending, including the raw miss and disabled-slot words. The probe leaves translator behavior and form coverage unchanged. +The node model and its witness set are described in +[bvh-node-model.md](experiments/bvh-node-model.md). ### gfx1013 2D explicit-LOD image gathers @@ -5717,7 +5751,8 @@ size, times 64 for the `st64` forms), and accesses word `(address >> 2) + i`. Th - `ds_write2_b32`, `ds_read2_b32`, `ds_write2st64_b32`, `ds_read2st64_b32`, `ds_write2_b64`, `ds_read2_b64`, `ds_write2st64_b64` and `ds_read2st64_b64`, with two different offsets; - the non-returning `ds_add_u32`, `ds_sub_u32`, `ds_and_b32`, `ds_or_b32`, `ds_xor_b32`, `ds_min_u32` and - `ds_max_u32`, as HLSL `Interlocked*` operations (`ds_sub_u32` adds the negated value); + `ds_max_u32`, as HLSL `Interlocked*` operations (`ds_sub_u32` is two `InterlockedAdd` calls on the same + word, `~v` and then `1`, see below); - `s_barrier`. The profile is one guest wave per group. A group of at most 32 threads is one wave at either guest wave @@ -5756,8 +5791,8 @@ writes its own words, and after a barrier reads another lane's: A counter program sets seven words, has every lane add, subtract, AND, OR, XOR, take the minimum and take the maximum of its index or a mixed word, and reads them back. With two groups, each group's sums cover -only its own threads, which shows that each group has its own LDS. Three mutations of the programs must -mismatch at the first word they change: +only its own threads, which shows that each group has its own LDS. Three mutations of the programs, and +one of the HLSL described below, must mismatch at the first word they change: - the next-but-one lane, at word 0; - an `st64` read spelled as a plain `read2`, at word 1; - `ds_min_u32` in place of `ds_max_u32`, at word 11. @@ -5779,6 +5814,27 @@ The mutations mismatched at their expected words on both adapters. Of the gfx101 `tools/form_coverage.py`, the test adds only `s_barrier`, because the gfx1030 private-LDS fixtures already record the DS mnemonics. +`ds_sub_u32` used to be one `InterlockedAdd(lds[i], (0u - v))`. On an NVIDIA GeForce RTX 5080 (driver +32.0.16.2124, Windows 11 build 26300.9974, debug layer unavailable) `CreateComputePipelineState` refused that +program with `E_OUTOFMEMORY`, so `compute_store_aot_lds_shared_hardware` failed. The DXIL is valid, and WARP +and an AMD Radeon iGPU (driver 32.0.11034.2) ran it. A reduction to a 64-thread shader isolates the case. The +PSO fails whenever an `InterlockedAdd` on groupshared memory takes `sub i32 0, x` for a runtime `x`. DXC +folds every tried spelling to that instruction, including `~x + 1u`, `x * 0xffffffffu`, `-(int)x` and +`-Od`. The same negation does not fail with `InterlockedAdd` on a UAV, with `InterlockedExchange`, `Xor` or +`Max` on groupshared memory, or with a plain groupshared store. Neither does `5u - x`, `0u - x * 3u` or a +constant addend. The translator now emits two additions on the word, `~v` and then `1u`. That is +`mem - v` modulo 2^32. The step has no return value and ends with a barrier, so no lane reads the +intermediate word. A fourth mutation of the HLSL drops the second addition and must mismatch at word 1. The +translation controls require the two additions and no `0u - ` in the counter program. + +On this change, with the hardware run on the RTX 5080 and then with `XBOX2WINDOWS_ADAPTER=Radeon`: + +| Adapter | Result | Debug layer | +|---|---|---| +| Microsoft Basic Render Driver (WARP), 10.0.26100.9818 | passed | unavailable | +| NVIDIA GeForce RTX 5080, driver 32.0.16.2124 | passed (failed before: `E_OUTOFMEMORY`) | unavailable | +| AMD Radeon(TM) Graphics, driver 32.0.11034.2 | passed | unavailable | + ```powershell cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^compute_store_aot_lds_shared_(warp|hardware)$' -V @@ -7113,7 +7169,7 @@ The `SUB_CO` fixture in `tests/compute_store_check.py` (`draw-sub-co`, `compute_ `v_mac_f32_e32 vD, S0, vS1` (VOP2 `0x1f`) and `v_mac_f32_e64 vD, S0, S1` (VOP3) compute `D = S0 * S1 + D` as an unfused binary32 multiply-add: the intermediate product `S0 * S1` rounds to binary32 before the addition. `D` is both an input accumulator and the destination. Lowering uses `f32_mac(a, b, c)` with separate `precise float p = asfloat(a) * asfloat(b)` and `precise float r = p + asfloat(c)` so DXC does not contract the operation to FMA. NaN/Inf/denormal literal constants, uninitialized/unknown or pending `S0`/`S1`/`D`, `vD > 255`, source modifiers (`-`, `|.|`), `clamp`, `omod`, and bare `v_mac_f32` are refused. -The `MAC_F32` fixture in `tests/compute_store_check.py` (`draw-mac-f32`, `compute_store_aot_mac_f32_${adapter}`) runs one 64-thread group (`buffer_store_dwordx4`, 256 output words plus 64 `SENTINEL` words), including `4097 * 4097 + (-16785408)` and `(1 + 2^-23) * (1 + 2^-23) - (1 + 2^-22)` where unfused and fused results differ, and compares all 320 words against an independent Python model. Reference controls (fused FMA at word 0, `p - c` at word 2, accumulator zeroed at word 3, sentinel modified at word 256) and recompiled-HLSL mutations (`mad()` fused multiply-add, `p - asfloat(c)`) must all fail. DXIL lets the driver fuse `mad()` (`FMad`) or not, so on hardware the `mad()` mutation is first read back against the fused and the unfused model. Exactly one must match all 320 words; anything else fails the test. Where the unfused model matches (an RX 5700 XT and an RX 9070 XT, [#2730](https://github.com/R0Y00/Xbox2Windows/issues/2730)), the mutation equals the lowering, and the test logs it as inapplicable on that adapter. The full comparison, the reference controls and the other mutations stay mandatory. Run `ctest --preset dev --no-tests=error -R '^compute_store_aot_mac_f32_(warp|hardware)$' -V`. +The `MAC_F32` fixture in `tests/compute_store_check.py` (`draw-mac-f32`, `compute_store_aot_mac_f32_${adapter}`) runs one 64-thread group (`buffer_store_dwordx4`, 256 output words plus 64 `SENTINEL` words), including `4097 * 4097 + (-16785408)` and `(1 + 2^-23) * (1 + 2^-23) - (1 + 2^-22)` where unfused and fused results differ, and compares all 320 words against an independent Python model. Reference controls (fused FMA at word 0, `p - c` at word 2, accumulator zeroed at word 3, sentinel modified at word 256) and recompiled-HLSL mutations (`mad()` fused multiply-add, `p - asfloat(c)`) must all fail. DXIL lets the driver fuse `mad()` (`FMad`) or not, so on hardware the `mad()` mutation is first read back against the fused and the unfused model. Word 0 has only constant operands, and DXC 1.9.2602.17 folds its `mad()` at compile time to the unfused +0, so the fused model fuses only the thread-dependent words and keeps word 0 unfused; the two models differ at words 2, 10, 18, … ([#2883](https://github.com/R0Y00/Xbox2Windows/issues/2883)). Exactly one must match all 320 words; anything else fails the test, and the failure names each model's first mismatch. Where the fused model matches (an RTX 4090), the mutation must be detected. `mac_f32_controls()` runs the probe against a simulated renderer: an unfused readback and the folded fused readback are classified, and a fully fused readback or a renderer exit of 3 fails. Where the unfused model matches (an RX 5700 XT and an RX 9070 XT, [#2730](https://github.com/R0Y00/Xbox2Windows/issues/2730)), the mutation equals the lowering, and the test logs it as inapplicable on that adapter. The full comparison, the reference controls and the other mutations stay mandatory. Run `ctest --preset dev --no-tests=error -R '^compute_store_aot_mac_f32_(warp|hardware)$' -V`. ```powershell ctest --preset dev --no-tests=error -R '^compute_store_aot_salu_i32_(warp|hardware)$' -V @@ -8924,6 +8980,8 @@ The carry-out add and subtracts `v_add_co_u32`, `v_sub_co_u32` and `v_subrev_co_ The carry-in add and subtracts `v_add_co_ci_u32`, `v_sub_co_ci_u32` and `v_subrev_co_ci_u32` lower in both encodings, VOP2 (`_e32`) and VOP3 (`_e64`), as the carry-out operations above with the carry or borrow of each lane read from a lane mask. The add computes `src0 + src1 + carry` and writes 1 when the 33-bit sum does not fit in 32 bits; `v_sub_co_ci_u32` computes `src0 - src1 - borrow` and writes 1 when `src1 + borrow > src0` (unsigned); `v_subrev_co_ci_u32` computes `src1 - src0 - borrow` and writes 1 when `src0 + borrow > src1`. The lowering keeps both steps in 32-bit unsigned arithmetic: the add carries when either step wraps, and a subtract borrows when the subtrahend exceeds the minuend or the borrow-in exceeds the partial difference. The source is again the LLVM 15 AMDGPU backend, read at tag `llvmorg-15.0.7`: it selects `V_ADDC_U32_e64` for `ISD::ADDCARRY` and `V_SUBB_U32_e64` for `ISD::SUBCARRY` (`AMDGPUISelDAGToDAG.cpp`, `SelectAddcSubb`), the multiple-precision add and subtract with carry or borrow in and out; it defines `V_SUBBREV_U32` with `v_subb_u32` as its reversed-operand counterpart (`VOP2Instructions.td`); and LLVM 15 prints the three on gfx10 as `v_add_co_ci_u32`, `v_sub_co_ci_u32` and `v_subrev_co_ci_u32`. The semantics are not checked against the ISA document here and not measured on a console. LLVM 15 prints both encodings with their suffix, so only those spellings are accepted. The `_e32` form reads and writes `vcc` or `vcc_lo` and takes a VGPR as `src1`; the `_e64` form names both masks, each `vcc`, `vcc_lo`, one SGPR or an SGPR pair, and both must have the same width. Each source is a register, an inline constant or a literal. The carry-in must be a per-lane condition the translator tracks, written by a comparison or a carry-out, exactly as for `v_cndmask_b32`, and the carry-out replaces the condition in its mask. The forms without a suffix, ` clamp`, a float modifier, `exec` or a VGPR as either mask, an `_e32` form with another mask or an SGPR `src1`, masks of different widths, a carry-in that no instruction wrote or that holds a constant, a missing or extra operand, an unwritten register, and the DPP and SDWA forms are refused. Three programs, one per operation, export through the `R32G32B32A32_UINT` readback target and are compared bit for bit. Each takes A, B, C and D from the constants, computes the carry-out form of the same operation on (A, B) into `vcc_lo` and on (A, D) into `s60`, then op(C, D, `vcc_lo`) in the `_e32` encoding and op(D, C, `s60`) in the `_e64` encoding with its carry-out in `s61`. Two `v_cndmask_b32_e64` selects turn the carry-outs into 0.5 or 1.0, and 2.0 (0x40000000) is added to both results, a bijection modulo 2^32 that moves the all-ones word of a borrow taken from the borrow-in alone to a normal number. Each operation runs on four rows: both carry-ins set with both carry-outs coming from the carry-in alone (C + D is 0xffffffff, or C = D), both carry-ins clear with a carry or borrow from the operands, and one row each with only `vcc_lo` or only `s60` set. Each carry-in and each carry-out takes both states, and every input and every exported word is a normal binary32 or zero, which the test asserts. Twenty-seven wrong references, each replacing one channel of one row, must report `pixel_mismatch`: a dropped carry-in or borrow-in, a carry-in read as set, a carry-out or borrow-out without the carry-in term on each mask, a dropped carry-out of the operands, the carry-in of one encoding read from the other's mask, subtract for add, add for subtract, a borrow-in added, reversed operands, and the borrow-out of the other operand order. That is 39 draws from 3 compiles and 3 renderer launches. As a check of the fixture, dropping the `{r} < {p}` term from the add's carry-out in `tools/pixel_aot.py` makes the first row mismatch on WARP. They run as their own tests, `pixel_aot_carry_in_hardware` and `pixel_aot_carry_in_warp` (`tests/pixel_aot_check.py draw-carry-in`), with their own coverage record, and the LLVM 15 round trip covers the three programs. They passed on the NVIDIA GeForce RTX 5080 (driver 32.0.16.2124), on the AMD Radeon(TM) Graphics iGPU (vendor 1002, device 13c0, driver 32.0.11034.2, selected with `XBOX2WINDOWS_ADAPTER=Radeon`) and on WARP (Microsoft Basic Render Driver 10.0.26100.9818), Windows 11 (build 26300), with the debug layer unavailable. They show that the translated shader computes the stated operations on desktop GPUs, not that the console does. Run `ctest --preset dev --no-tests=error -R '^pixel_aot_carry_in_' -V`. The 64-bit multiply-adds `v_mad_u64_u32` and `v_mad_i64_i32` lower as `D = S0 * S1 + S2` modulo 2^64 with two 32-bit factors and a 64-bit `S2`, written to a VGPR pair `v[d:d+1]`. The product is built from `a * b` and the `mul_hi_u32` or `mul_hi_i32` helper of the scalar multiply-high, the add runs on two `uint` words with the carry of the low word added to the high word, and no 64-bit HLSL type is used. The unsigned form zero-extends the factors and writes the carry-out of the 64-bit add (the high-word step wraps) to the lane mask, tracked like a comparison result so that `v_cndmask_b32` can read it. The semantics come from LLVM 15 `VOP3Instructions.td`, which defines both (VOP3B opcodes 374 and 375, as in `tools/disasm_rdna2.py`) as `VOP3b_I64_I1_I32_I32_I64`: a 64-bit result and a one-bit carry-out per lane; they are not checked against the ISA document here and not measured on a console. The carry-out of the signed form is not established here, so the translator has no mask for it: the signed form is accepted only with the discarding `null` destination, which LLVM 15 assembles, and any other destination is refused, so a later read of a mask the signed form seems to have written is refused as an unwritten register. The mask of the unsigned form is `vcc`, `vcc_lo`, one SGPR or an SGPR pair; `null` there is refused. `S0` and `S1` take a register, an inline constant or a literal; `S2` takes a VGPR pair, an aligned SGPR pair or an inline constant from -16 to 64, sign-extended to 64 bits. Unaligned VGPR pairs are accepted because LLVM 15 assembles them (hardware legality is assumed, not measured). A literal `S2`, ` clamp`, any operand modifier, an output modifier, an `_e64` suffix, a destination or `S2` that is not a two-register VGPR range, a mask of the wrong width or alignment, an unwritten register and DPP controls are refused. Four programs export through the `R32G32B32A32_UINT` readback target and are compared bit for bit: `u64_pair` (VGPR-pair `S2` with its carry in `vcc_lo`, and an inline -1 `S2` with its carry in `s60`), `u64_mixed` (SGPR-pair `S2`, an inline factor 3 and an unaligned destination), `i64_pair` and `i64_mixed` (the same for the signed form, with an inline -1 and -3). The unsigned rows cover a carry out of the high word with both factors above 2^31, a carry from the low into the high word without a carry out, a sum that wraps to exactly zero and carries, a zero `S2` and a zero factor; the signed rows cover negative times positive, negative times negative with a negative `S2`, and positive times positive with a negative `S2`. Every input and every exported word is a normal binary32 or zero, which the test asserts. Twenty-three wrong references, each replacing one channel of one row, must report `pixel_mismatch`: the signed product for the unsigned form and the unsigned product for the signed form, a dropped `S2`, a dropped carry-out, a carry-out on a low-to-high carry only, a dropped low-word carry, a dropped carry when the sum wraps to zero, a wrong carry of the inline -1 on a non-zero and a zero product, a zero-extended inline -1 and -3, an inline 3 read as 1 and an inline -3 read as 3, and a dropped high word of `S2`. They run as their own tests, `pixel_aot_mad64_hardware` and `pixel_aot_mad64_warp` (`tests/pixel_aot_check.py draw-mad64`), with their own coverage record, and the LLVM 15 round trip covers the four programs. They passed on the NVIDIA GeForce RTX 3080 (driver 32.0.16.2124) and on WARP (Microsoft Basic Render Driver 10.0.26100.9818), Windows 11 (build 26200). They show that the translated shader computes the stated operations on desktop GPUs, not that the console does. Run `ctest --preset dev --no-tests=error -R '^pixel_aot_mad64_' -V`. +For the wave64 skipped-block liveness proof, an unsigned VOP3B carry-out with `vcc_lo` may also write `vcc_hi`; a discarded carry does not invalidate either half. The signed form's admitted `null` destination is unchanged. `startup_gfx2hlsl_mad64_check.py` verifies these effects and the clear-fact transfer at a skipped-block join. + The exact conversions `v_cvt_f64_i32` and `v_cvt_f64_u32` lower as the binary64 value of a 32-bit signed or unsigned integer, written to a VGPR pair `v[d:d+1]` (low word in `v[d]`, high word in `v[d+1]`). Every 32-bit integer is exactly representable in binary64, so there is no rounding and no dependence on a rounding mode. The translator builds both words from `uint` operations and uses no `double` and no `asdouble`: the sign (bit 31 of the signed form, zero otherwise), the magnitude, an exponent of 1023 plus the index of the highest set bit, and the bits below it shifted to the top of the 52-bit fraction. Zero gives +0.0 (both words 0) and `INT_MIN` gives `0xc1e00000_00000000`. The shader therefore needs no double-precision capability, and the draw tests have no capability skip for it (the WARP fault on double comparisons noted for `v_div_fmas_f32` is not reachable). The semantics come from LLVM 15 `VOP1Instructions.td` (`v_cvt_f64_i32` and `v_cvt_f64_u32` are VOP1 with a 64-bit result and a 32-bit integer source); they are not checked against the ISA document here and not measured on a console. LLVM 15 prints the unmodified VOP1 form with the `_e32` suffix and accepts it without; both spellings are lowered, with a VGPR, SGPR, inline-constant or literal source. An `_e64` suffix (with or without modifiers), ` clamp`, an output modifier, DPP, SDWA, a destination that is not a two-register VGPR range (one register, a reversed or three-register range, an SGPR range, a pair that ends above v255), a source that is not one dword or an untracked register, and any use inside a masked region are refused. LLVM 15 itself does not assemble `-v` or `|v|` on the integer source; the translator refuses those spellings as well. The translator tracks the pair as two ordinary numeric words (`alul` and `aluh`): a later integer or binary32 instruction that reads one word, such as `v_add_f32`, still lowers and sees the raw word, and `v_mad_u64_u32` may take the pair as its `S2`. A supported binary64 comparison can consume the pair directly. Binary64 arithmetic and conversions back to binary32 or an integer remain unsupported. Four programs export through the `R32G32B32A32_UINT` readback target and are compared bit for bit with Python's own `struct.pack(': image_sample, image_sample_l through a sampler heap: sampler MIN_LOD, MAX_LOD and LOD bias are not validated (#2221)`). Since then the run-time heap table applies each entry's MIN_LOD and MAX_LOD (`dynamic_sampler()` in `src/startup_stubs/translated_sampler_bindings.h`, checked by `startup_sampler_lod_*`); the entry's LOD bias is not carried, a MIN_LOD above MAX_LOD is passed through unchanged, and the default-sampler shortcut keeps a static sampler with an unbounded LOD range. A sampler that is neither heap nor constant is refused as before. `image_sample_c` keeps its MAX_LOD rule. +Not changed: a sampler read through the sampler heap (table or default-sampler shortcut) keeps the ordinary static or heap sampler and is not validated; `translate_to` and `translate_compute` write one line per module to stderr (`: image_sample, image_sample_l through a sampler heap: sampler MIN_LOD, MAX_LOD and LOD bias are not validated (#2221)`). Since then the run-time heap table applies each entry's MIN_LOD and MAX_LOD (`dynamic_sampler()` in `src/startup_stubs/translated_sampler_bindings.h`, checked by `startup_sampler_lod_*`); the entry's LOD bias is not carried, a MIN_LOD above MAX_LOD is passed through unchanged, and the default-sampler shortcut keeps a static sampler with an unbounded LOD range. Other nonconstant samplers remain refused except for the [proven two-sampler explicit-LOD join](experiments/startup-sampler-join.md). `image_sample_c` keeps its MAX_LOD rule. `tests/startup_image_sample_lod_check.py` draws each form on its own (`startup_image_sample_lod_warp`, `startup_image_sample_lod_hardware`) against the 4x4, two-slice, three-mip array, point sampler with mip filter point, where all six cells differ. Each form's control is the same program through the ordinary `smp` line, which must read a different mip: `image_sample_l` with explicit level 2 and MAX_LOD 1 reads mip 1 (`smp`: mip 2); `image_sample` with MIN_LOD 2 above the implicit level 1 reads mip 2 (`smp`: mip 1); `image_sample_lz` with MIN_LOD 1 reads mip 1 (`smp`: mip 0). The implicit level 1 comes from the technique of the bias check: only the `u` initialiser of the translated HLSL is replaced by `0.75 + 0.5 * (SV_Position.x - 0.5)`, the `Sample` call is untouched. Refusal controls per form: bias, secondary bias and MIN_LOD 3 above MAX_LOD 2; accepted controls per form: mip filter 0 (`smp` line) and a heap sampler (table and default-sampler shortcut, logged once). The three `image_sample_b` discriminators are unchanged. Not covered: a fractional MIN_LOD or MAX_LOD, a linear mip filter, 1D, 3D and packed `a16` draws, the run-time heap sampler's LOD fields (#2221), and compute stages. @@ -15158,6 +15222,15 @@ The two adapters and WARP [measured on the desktop](https://github.com/R0Y00/Xbo differed at exact half-mip boundaries with point mip filtering. The regression uses linear filtering for the fractional lower clamp. Native console readback remains open. +The same startup lowering admits 2D arrays with three guest address registers. +DXIL `CalculateLOD` takes just the two spatial coordinates for a `Texture2DArray`; +the slice is not part of the level calculation. The portable controls verified +both dimensions, including a non-sequential address with a different slice register, +and retained the existing derivative, sampler and mask refusals. +The array-view fixture compares raw translated and direct HLSL readbacks for +two encoded slice values and two gradients against the independent LOD reference. +The array GPU lane was not run on Apple Silicon. + ```powershell ctest --preset dev --no-tests=error -R '^startup_image_get_lod_view_' -V ``` @@ -15668,6 +15741,26 @@ python3 -B tests/startup_gfx2hlsl_calculated_target_check.py python3 -B tests/startup_gfx2hlsl_calculated_target_check.py binary llvm-mc-15 ``` +### Statically resolved far early-outs through the two-exit profile + +The gfx1013 pixel two-exit extractor accepts a single proven forward calculated transfer onto an +instruction-aligned terminating continuation containing only `s_nop`/`v_nop` and a plain `s_endpgm`. +The contiguous `s_getpc_b64`/`s_add_u32`/`s_addc_u32`/`s_setpc_b64` chain uses a fresh aligned scalar +pair and a constant displacement with matching sign extension. The repository and LLVM instruction +inventories must agree, and no branch may enter the chain interior. Observable continuation effects +remain refused. The standalone `pixel_aot.lower()` retains its single-export, single-exit scope. + +The source-built fixture compares short direct, short calculated and far calculated transfers using +both selector outcomes and an independent arithmetic reference. The far displacement exceeds the +131068-byte positive SOPP range. The bounded FSSM extraction check requires LLVM 15; its absence is +reported separately from translation. Refusal controls cover malformed chains, escaping scratch +words or SCC, effectful continuations and unaligned or out-of-range destinations. + +```bash +python3 -B tests/startup_gfx2hlsl_far_early_out_check.py +python3 -B tests/startup_gfx2hlsl_far_early_out_check.py binary llvm-mc-15 +``` + ## Compute stage in the startup translator `gfx2hlsl.ComputePipeline` translates one gfx1013 compute program with the root and resource model of diff --git a/docs/experiments/bvh-node-model.md b/docs/experiments/bvh-node-model.md new file mode 100644 index 0000000000..3f8b184752 --- /dev/null +++ b/docs/experiments/bvh-node-model.md @@ -0,0 +1,102 @@ +# Console BVH node model and witness set + +Refs [#1759](https://github.com/R0Y00/Xbox2Windows/issues/1759), +[#2413](https://github.com/R0Y00/Xbox2Windows/issues/2413) and +[#2603](https://github.com/R0Y00/Xbox2Windows/pull/2603). This note covers the +pure-Python node model in `tests/gfx1030_bvh_box/bvh_model.py` and the +model-only witness set in `tests/gfx1030_bvh_box/check.py --model-only`. The +HIP kernel, the gfx1030 code object and the shader translator are unchanged. + +## Node formats + +A node pointer has its kind in the low three bits. The rest addresses a +64-byte node as `(pointer >> 3) << 6`. The 32-bit form adds that offset to a +40-bit base held in descriptor DWORD 0 and the low byte of DWORD 1, in +256-byte units. The 64-bit form uses the absolute pointer. + +| Kind | Node | Bytes | Layout | +|---|---|---|---| +| 0-3 | triangle 0-3 | 64 | five vertices, three f32 each, bytes 0-59; ID DWORD at byte 60 | +| 4 | box, f16 bounds | 64 | four child pointers, then four boxes of six f16 from byte 16 | +| 5 | box, f32 bounds | 128 | four child pointers, then four boxes of six f32 from byte 16; bytes 112-127 unused | +| 6, 7 | instance, procedural | - | not read by this instruction | + +`TRIANGLE_VERTICES` is `((0, 1, 2), (1, 3, 2), (2, 3, 4), (2, 4, 0))`. +Triangle `k` uses those three node vertices. The ID byte for triangle `k` +selects the vertices weighted by I and J in bits 1:0 and 3:2; the remaining +vertex is `3 - I - J`. Bits 7:4 of the ID byte are ignored. A malformed ID +that names the fourth map nibble reads node vertex 0, as the arithmetic +lands. + +Descriptor DWORD 1 bit 31 enables nearest-first box sorting. DWORD 3 bit 24 +selects triangle return mode 1. DWORD 3 bits 31:28 hold the resource type, +`0x8`. + +## Results + +A box node returns four child pointers. A hit is included at its entry +distance; a miss or an absent child is `0xffffffff`. Sorting uses a strict +comparison, so equal entries keep their child order; misses sort last when +sorting is enabled. + +Triangle return mode 1 is `{t_num, t_denom, I_num, J_num}`, all as f32. On a +miss it is `{+inf, 1.0, 0.0, 0.0}`. The instruction does not test the ray +extent for triangles. Return mode 0 is not modeled in this slice. + +## Assumptions + +- Arithmetic is binary32 at each step, rounding to nearest even. Python + floats only carry the values; the result DWORDs are the f32 bit patterns. +- The inverse direction is an instruction input. The box test clamps it to + `+-FLT_MAX` before multiplying, so an origin exactly on a face does not + create `0 * infinity`. +- `fmin`/`fmax` return the non-NaN operand when one is NaN. A NaN minimum x + marks an absent box. Other NaN box components are outside the defined + input. +- A box is hit when `leave >= max(0, enter)` and `enter < extent`. An entry + exactly at the extent is not a hit. A box containing the origin can be hit + at a negative entry. +- The triangle test is the watertight Woop, Benthin and Wald formulation used + by RADV. A ray exactly through an edge or vertex hits both triangles that + share it. A NaN vertex, a zero determinant or a triangle behind the ray + misses. +- A zero direction gives an infinite inverse; the triangle shear then + produces NaN and the triangle misses. + +These choices follow Mesa RADV's MIT-licensed software emulation and the +RDNA 2 ISA descriptor tables. They are a CPU model, not a native measurement: +hardware rounding, which of two equally near boxes is returned first, and the +exact edge case remain assumptions. No code is copied from the GPL-3.0 +VIctory reference. + +## Witness set + +The model-only run has 315 cases: 231 node cases and 84 pointer-decoding +cases. The node cases are 66 f32 box, 46 f16 box and 119 triangle cases. The +expected four-DWORD results are literals in `check.py`; the runner does not +recompute them with the model. The existing five-ray FP32 box assertions in +`model_check()` still run before the witness set. + +Coverage includes sorted and unsorted hits, misses, ties, extent clipping, +disabled and zero child pointers, inverted and infinite bounds, negative +zero, NaN bounds and vertices, zero directions, f16 rounding, subnormals and +65504, all six triangle vertex permutations for each kind, ID high bits, +malformed IDs, shared edges and vertices, t = 0, triangles behind the ray, +and degenerate triangles. Pointer cases cover every kind, nonzero and +high bases, 48-bit wrap and the absolute 64-bit form. + +## Reproduce + +```sh +python3 -B tests/gfx1030_bvh_box/check.py --model-only +``` + +The command needs no GPU, HIP library or code object. The native five-ray +case still needs LLVM/LLD 15 and a gfx1030 HIP device: + +```sh +sh tests/gfx1030_bvh_box/build.sh +python3 -B tests/gfx1030_bvh_box/check.py --device 0 +``` + +No game files, dumps or third-party source are part of this fixture. diff --git a/docs/experiments/exe-structurization.md b/docs/experiments/exe-structurization.md new file mode 100644 index 0000000000..d1b76d37b9 --- /dev/null +++ b/docs/experiments/exe-structurization.md @@ -0,0 +1,223 @@ +# EXEC removal and structurization for the shader frontend + +The startup translator refuses a large fraction of the title's shaders on control-flow and lane-mask +shapes. The same shapes recur across compute, graphics and mesh programs: + +| Refusal family | Example measured on 26 November 2026 | Count | +|---|---|---:| +| `s_cbranch_execz` / `s_cbranch_scc0` inside a skipped block | `s_branch inside an s_cbranch_execz block` | 331 (RTX 3090 run) | +| Slot 57 mesh skipped-block effects | `slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes` | 241 | +| `v_readfirstlane_b32` without a proven uniform source | `v_readfirstlane_b32 requires a proven uniform source` | 526 | +| `src_scc` with unverified SCC | `src_scc with unverified SCC` | 762 (rev28 census) | +| Wave reductions in branched programs | `wave reduction in a program with branches` | present in the census | + +The 26 November census held 3,007 `.fail` records (2,564 compute, 275 graphics, 162 mesh). Adding +one accepted shape at a time moves a request to the next refusal more often than it produces a +complete translation. The mesh notes record exactly that: a change accepts 91 of 407 requests at one +pre-check, and all 91 stop at the next refusal, with no new complete translation. + +This note proposes a structural fix: lower the program **as one lane runs it**, without EXEC, then +emit HLSL from the structured control flow. It is a design for the C++ frontend; the current Python +translator remains the reference for instructions that already translate. + +## Why the local pattern approach does not converge + +EXEC, VCC, SCC and the saved-exec registers are one dependency graph. A rule that proves a scalar +dead at one join, or a mask equal to a lane's own bit, depends on the paths that reach the join and +on every writer of the mask. A pattern that accepts one shape without a general representation of +that graph leaves the next shape refused. The refused shapes also interact: + +- a branch on a mask test is also a join of the mask; +- a scalar load inside an EXEC-zero block is uniform only because the guest runs the block once per + wave, while the per-lane model may run it per lane; +- a `v_readfirstlane_b32` waterfall has one descriptor per lane and needs the per-lane source that + produced it; +- a wave reduction is a loop over lanes that changes EXEC on purpose. + +## Proposed pipeline + +``` +decode -> CFG/SSA -> normalise special registers -> per-lane mask booleans + -> structurize without EXEC -> path-sensitive guard proof + -> resource/address tracing -> HLSL -> DXIL +``` + +### 1. Decode and CFG/SSA + +Keep the existing gfx10 decoder. Build basic blocks and SSA values for VGPRs, SGPRs, SCC, VCC and +EXEC. The CFG must be reducible for DXIL; refuse irreducible graphs with a named reason rather than +guessing. Record, for each instruction, the block and the word offset for diagnostics. + +### 2. Normalise special registers + +Turn writes to EXEC, VCC, VCCZ and the saved-exec registers into explicit values. A write from +`v_cmp*`, `s_and_b64`, `s_or_b64`, `s_cselect_b64`, `s_mov_b64` or `s_*_saveexec` becomes a mask +value, not an opaque register. A write the pass cannot follow becomes an `Opaque` mask atom and is +kept as a per-lane boolean, with a refusal only where a later use needs a stronger fact. + +### 3. Per-lane mask booleans + +Represent a lane mask as a Boolean function over these atoms: + +- `Lane(value)`: the lane's bit of a VALU-written compare or carry result, before EXEC masking; +- `Uniform(value)`: an SCC value that is the same in every lane; +- `Phi(value)`: a mask joined at a block entry; +- `Quad(value)`: an `s_wqm` result (some lane of the quad is in the source mask); +- `Opaque(value)`: a mask the pass cannot see into; +- `Constant(mask)`: all lanes, no lanes, or a constant mask. + +A reduced ordered binary decision diagram (BDD) gives canonical equality and cheap `and`/`or`/ +`not`/`ite`. The alternative is a bitset per atom set; the BDD wins when the same mask is rebuilt +along many paths, and loses on pathological atom counts. Whichever representation is chosen, the +interface must expose: `lane_bit(mask, lane)`, `is_all`, `is_none`, `is_equal(a,b)`, and substitution +of a lane's bit for a uniform branch. + +### 4. Remove EXEC + +Translate the program as one lane. For each vector instruction, compute the guard +`lane_bit(EXEC_at_instruction, lane)`. If the guard is `true` for every lane that reaches the +instruction, emit it unguarded. Otherwise emit a per-lane `if` around it. This is valid because the +guest drops the instruction's side effects outside EXEC, and PC hardware only requires the same +result in the lanes that matter; helper-lane work is dead except where derivatives or quad +operations read it. + +A branch on a wave-wide mask test (`s_cbranch_execz`, `s_cbranch_vccz`, an SCC computed from a mask) +becomes a branch on `lane_bit(mask, lane)` for the lane being modelled. A path-sensitive pass then +proves where the guard is constant and removes the `if`. + +### 5. Structurize + +Recover `if`/`else`, `break`, `continue` and loops from the reducible CFG. Keep the block shape so +diagnostics and the existing instruction offsets survive. A loop's EXEC changes must be modelled per +iteration; the pass must not hoist a mask out of a loop unless the loop is proven not to change it. + +### 6. Path-sensitive guard proof + +For each instruction, collect the mask facts that hold on every path to it. Prove a guard `true` when +all reaching paths imply it; prove `false` when none reaches it. Only emit a per-lane `if` when the +proof cannot decide. This is the step that turns the general model into the small HLSL the current +translator emits for its accepted shapes. + +### 7. Resource and address tracing + +Trace each descriptor and scalar address to a root parameter (table, heap, root descriptor, root +constant) or to a raw title address. A descriptor that a waterfall reads in the first lane is traced +to the per-lane load or choice that produced it. A raw address is a 40-bit title address, not a +desktop pointer; it needs the page directory and a bound resource, or a named refusal. + +## Mapping to the C++ frontend + +The Python translator's accepted instruction set is the semantic reference, not the architecture. +Keep its tests and its refusal strings. Move the following into the C++ frontend as separate passes +with their own fixtures: + +| Current Python area | C++ pass | Keep | Replace | +|---|---|---|---| +| `Stage.execz_refusals`, per-shape mask proofs | CFG/SSA + mask BDD | refusal reasons and tested shapes | ad-hoc shape matching | +| `spill_*`, `uniform_branches` | normalise special registers + guard proof | spill-slot semantics | per-instruction exception tables | +| `uniform_image_load_regs` / `v_readfirstlane` proof | resource/address tracing | per-lane descriptor facts | local scan heuristics | +| wave-reduction recogniser | cross-lane operation pass | opcode set and wave32/wave64 rules | pattern matching on the chain | +| mesh skeleton | mesh pass on the same CFG | group-index/count exchange rules | duplicated EXEC rules | + +The frontend should keep a `--explain` path that names the first unresolved fact for each refused +program, so a census remains comparable with the Python `.fail` reasons. + +## Phases + +### Phase 1: uniform skipped blocks + +Accept an `s_cbranch_execz` block entered by a wave-uniform condition whose scalar writes are dead at +the join. Emit the block once per wave, predicate vector writes by the lane's EXEC bit, and keep an +empty wave from issuing loads. This is the shape already measured in the slot 57 notes; it is a +useful first test of the model but not the end state. + +Acceptance: a source-built gfx1013 compute or mesh program with a uniform skip and a dead scalar +write translates; a control with a live scalar at the join is refused by name; the current +translator's accepted programs still produce the same pixels. + +### Phase 2: mask joins and SCC branches + +Add the BDD or bitset representation. Cover `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_not_b64`, +`s_cselect_b64`, `s_cmov_b32`, `s_cbranch_scc0/1`, and `v_cndmask_b32` mask selection. The first +target is the 762 `src_scc` census entries and the 95 `s_cbranch_scc0` inside skipped blocks. + +Acceptance: a differential set of programs where the current translator accepts one form and the new +pass accepts the neighbours; a control that uses a varying SCC as a uniform branch must be refused, +not miscompiled. + +### Phase 3: `v_readfirstlane` and waterfalls + +Trace the per-lane source of a first-lane read through `v_cndmask_b32`, an if/else whose arms set +the same descriptor, or a load from a per-lane descriptor. Cover the 526 first-lane refusals and the +remaining mesh group-index reads. + +Acceptance: a source-built descriptor waterfall whose lanes select different buffers; a control with +an unproven lane source is refused; a draw reads the expected texels. + +### Phase 4: wave reductions + +Model the reduction as a lane loop or as the corresponding wave intrinsic when the shape is proven. +Keep the existing wave32/wave64 opcode set (`v_or_b32`, `v_min_u32`, `v_max_u32`, the saveexec form) +and extend only with a tested shape. The current straight-line-only restriction is the thing to +remove; the identity fill and the partial-mask rules must stay explicit. + +Acceptance: a reduction inside a branch and a loop; a wave64 control; a partial-mask control that +must refuse. + +### Phase 5: helper lanes, quads and mesh + +Helper lanes count as live for derivatives and quad operations. Model `s_wqm`, quad reads and the +mesh group-index/count exchange on the same CFG. This is where the slot 57 mesh path and the pixel +helper-lane path converge; do not fork a second EXEC model for mesh. + +Acceptance: the existing quad/helper-lane fixtures, the mesh wave-block fixtures, and a new mesh +program with a count exchange and a real export. + +## Test and oracle strategy + +- **Differential against the current translator:** for every shape the Python translator accepts, + the new pass must produce the same pixels or the same raw words. This is the strongest regression + oracle and costs no new golden data. +- **Source-built gfx1013 programs:** one program per phase, assembled with the existing fixtures, + with expected values written out independently of the pass. +- **Negative controls:** a live scalar at a join, a varying SCC used as a uniform branch, an + unproven first-lane source, a partial-mask reduction, and an irreducible CFG. Each must be refused + by name, not translated approximately. +- **GPU coverage:** WARP for every shape; hardware on the available Radeon/NVIDIA adapters for the + first program of each phase. Report capability skips separately. + +## Risks and non-goals + +- **BDD blow-up:** cap the atom count and fall back to a bitset or a named refusal. A cap that + silently changes semantics is not acceptable. +- **Irreducible CFG:** refuse; DXIL requires reducible control flow. +- **Helper lanes:** a per-lane model can drop work that derivatives read. Keep helper lanes live in + pixel stages and prove the quad operations. +- **Wave width:** wave64 semantics on a wave32 host need exact lane-mask handling; the existing + wave64 tests remain the reference. +- **Resource tracing is not part of the control-flow pass.** Keep it separate so a mask bug does not + hide a binding bug. +- **Non-goal:** translating every instruction at once. The pass order must land behind tests, one + phase at a time. + +## Recommended first patch + +Start with Phase 1 in the C++ frontend or, if the frontend is not ready, add the same uniform-skip +rule to the Python translator behind a narrow fixture. The patch should: + +1. accept one wave-uniform `s_cbranch_execz` block with scalar writes dead at the join; +2. predicate vector writes by the lane's EXEC bit; +3. refuse a live scalar at the join and an empty-wave load by name; +4. prove it on the existing slot 57 wave-block fixture and one compute program. + +That is small enough for one reviewable PR and gives the C++ frontend its first end-to-end control- +flow test without pretending the general pass is finished. + +## References + +- `tools/startup/gfx2hlsl.py`: `Stage.execz_refusals`, `spill_*`, `op_v_readfirstlane_b32`, the + wave-reduction recogniser, and the slot 57 skeleton. +- `docs/experiments/startup-mesh57-wave-block.md` and `startup-mesh57-dead-block-scalar.md`. +- Issues #2125, #2413, #2023, #1723 and #1143. +- The public design description of DexNom/VIctory's `structure.rs` (GPL-3.0; read-only, no code + copied): per-lane booleans, EXEC removal, structured control flow, helper lanes. diff --git a/docs/experiments/mesh57-dxil-plan.md b/docs/experiments/mesh57-dxil-plan.md new file mode 100644 index 0000000000..3d09fdcd73 --- /dev/null +++ b/docs/experiments/mesh57-dxil-plan.md @@ -0,0 +1,167 @@ +# Slot 57 mesh: plan for a complete DXIL translation + +Slot 57 is the fixed mesh pipeline path: the title creates a mesh pipeline whose programs are +console gfx1013, then issues `DispatchMesh` (directly or through an indirect signature). The +tracking issue #2413 recorded 298 distinct requests and **0 complete translations**. The partial +slices merged so far remove pre-checks; they do not produce a complete program, and the next +refusal is always waiting. + +This note separates the work that must happen before a first complete translation from the runtime +work that consumes it. It is a plan, not a claim that a scene renders. + +## Dependency map + +``` +device slot 57 request + -> gfx2hlsl inspect_mesh57_request (pre-checks, skeleton, pixel stage) + -> translate_mesh57 (mesh body, exports, container) + -> .ms.cso / .ps57.cso + -> runtime CreateMeshPipelineState + root signature + -> DispatchMesh (direct or indirect signature) + -> GPU mesh pipeline + pixel stage +``` + +The translator and the runtime have separate gates. A program can translate and still not run if +the runtime refuses `DispatchMesh` (`#1759`) or the pipeline root; a runtime path can be ready and +draw nothing without a translation. Keep them as separate PRs. + +## Measured refusal shapes + +From the local capture census in the #2413 notes and the 26 November runs: + +| Shape | Requests | Where it stops | +|---|---:|---| +| `s_cbranch_execz` pre-exchange block with scalar loads | 407 | `s_cbranch_execz skips code with effects outside active lanes` | +| Same, after the wave-block and dead-scalar slices | 91 | `v_readfirstlane_b32 outside the group-index read is not covered` | +| Branch inside the skipped block, `src_scc`, or `v_cmpx_lt_u32 v, v` | 316 | one of those named refusals | +| Pixel stage mixes the null export with another export | 97 | `slot 57 pixel stage mixes the null export with another export` | +| Group-index/count exchange shape | 15 | exchange refusal | +| Loops | 11 | loop refusal | +| `v_fma_mix_f32` reading the upper half of `v_interp_p2_f16` | 39 | pixel-stage refusal | +| `s_load` with a register offset through the resource heap | 47 | resource-heap refusal | + +The numbers are counts from one capture, not a promise that fixing a shape completes a program. The +91-request slice is the clearest evidence: two accepted blocks still produced zero complete +translations because the next refusal was waiting. + +## The smallest end-to-end target + +Do not start from the 298 real requests. Start from a source-built slot 57 program with the smallest +shape the runtime can create and dispatch: + +- one mesh workgroup, one output lane per thread (wave64 or wave32 depending on the fixture); +- three vertices and one triangle, written through the mesh export path; +- a group-index read through `v_readfirstlane_b32` of a formatted buffer load; +- one `SetMeshOutputCounts` and no LDS exchange beyond the group index; +- a constant-colour pixel stage, then a textured pixel stage. + +This program proves the chain: request -> `MeshPixelStage` -> DXIL mesh container -> desktop +`CreateMeshPipelineState` -> `DispatchMesh` -> readback. Only then take the first real request whose +shape is closest to this program. + +## Pass plan + +### 1. Mesh skeleton and wave model + +The existing `mesh_skeleton` already handles the group-index/count exchange, the wave64 lane masks +and the fixed user-SGPR layout. Keep it. The mesh stage must model one thread per output lane and +must not reuse the pixel helper-lane rules blindly. + +Requirements: user SGPRs start at s16; the root layout is s16 tables, a root descriptor pair, root +constants, then heap bases; a program with one fewer table shifts by one. `s_bitcmp0_b32 s20, 28` +tests a packed root-constant field, not a hardware system value. Resource-heap records are indexed +as `(rootconst & 0x3ff) << 5` and loaded with `s_load_dwordx4` from the 32-bit heap base. + +### 2. `v_readfirstlane_b32` of the group index + +The 91 requests that pass the wave block stop on a first-lane read of a formatted buffer load in the +pre-exchange code. The pass must trace that read to the per-lane descriptor and the lane that +produced it. This is the same fact the compute waterfall path needs; do not add a mesh-only rule. + +Acceptance: the source-built group-index program translates and reads the expected index; a control +whose first-lane source is not proven is refused by name. + +### 3. Branches and SCC inside skipped blocks + +The 316 remaining pre-check requests have a branch inside the block, `src_scc`, or the +`v_cmpx_lt_u32 v, v` compare form. Do not add one pattern per shape. Use the EXEC/SSA structurization +from `docs/experiments/exe-structurization.md`: represent the block as one lane, branch on the lane's +own mask bit, and prove the scalar values that survive the join. A mesh-specific exception table is +the wrong direction. + +### 4. Group memory and output counts + +The mesh stage writes group memory (LDS) and then exports vertices and primitives. The pass must: + +- keep the group-index and count exchanges wave-uniform; +- keep `SetMeshOutputCounts` once per workgroup, not once per lane; +- respect the declared maximum vertices/primitives and the output-size limit; +- map `v_mbcnt`, `ds_*` and the export registers to the DXIL mesh output arrays; +- keep helper lanes out of the mesh output count path. + +Acceptance: a source-built triangle with three vertices and one primitive; a control with a wrong +count, a wrong index, and a missing export each produces a named failure or a pixel mismatch. + +### 5. Pixel stage linkage + +The slot 57 pixel stage is a separate console program. Link its inputs to the mesh outputs by +semantic, not by register order. The 97 requests that stop on `slot 57 pixel stage mixes the null +export with another export` are the early-exit form: the null export after the main `s_endpgm` is a +kill, not a second colour target. Accept only that block; leave other mixed-export forms refused. + +### 6. Runtime creation and dispatch + +The translator can publish `.ms.cso` and `.ps57.cso` before the runtime consumes them. The +runtime needs: + +- `CreateMeshPipelineState` with the translated root signature and the MS/PS bytecode; +- the mesh container fields (max vertices, max primitives, topology, output size); +- `DispatchMesh` direct and indirect, with the console command signature; +- the pipeline root and the group counts on the same command list. + +Keep the runtime slice behind a source-built `startup_mesh57_*` fixture; a translation without a +runtime fixture is not an end-to-end result. + +## Phased schedule + +| Phase | Scope | Observable acceptance | Owner | +|---|---|---|---| +| A | source-built minimal mesh + group-index read | translate, create PSO, dispatch, read back 3 vertices/1 triangle on WARP and hardware | translator + runtime | +| B | `v_readfirstlane` group index on a real request shape | the 91-request class moves past the refusal; one request translates completely if the rest is present | translator | +| C | EXEC/SSA branches inside skipped blocks | the 316-request class moves; no mesh-only exception table | frontend | +| D | group memory, counts, export limits | source-built triangle with LDS and count controls | translator | +| E | pixel-stage linkage and null-export kill | 97-request class pixel programs translate and draw the expected pixels | translator + GPU | +| F | one real slot 57 request end-to-end | a real request creates a desktop mesh PSO and `DispatchMesh` draws the expected geometry in a capture | runtime + GPU | + +Phase A is the only one that can claim a complete translation. B-E are enabling slices; each should +say how many requests moved and whether any complete translation resulted. + +## Risks + +- **Wave64 on wave32:** the title's mesh programs use 64-lane waves and 64-bit EXEC operations. A + wave32 host needs exact lane-mask handling; a silent 32-lane assumption changes the group index + and the export count. +- **Workgroup size and LDS:** the console mesh group is not the desktop mesh group. The pass must + preserve the group-index/count exchange and the LDS size the program declares. +- **Output limits:** DXIL mesh outputs have a size limit; a program that fits the console may need a + refusal or a split. Do not let the validator fail at runtime without a named translation refusal. +- **Slot 57 vs slot 86:** slot 57 is the fixed mesh pipeline; slot 86 is the stream pipeline path. + Do not merge their request formats or their root rules. +- **Helper lanes:** a pixel stage that uses derivatives needs helper lanes; a mesh-only per-lane + model that drops them will produce wrong edges. + +## First patch recommendation + +Add the `v_readfirstlane_b32` group-index read to the mesh skeleton, with the source-built minimal +mesh from Phase A. The 91 requests already pass the wave block and stop there; the patch tests the +same fact on a program that can be drawn end-to-end. If the minimal program cannot yet create a +desktop mesh PSO, land the translator test and the runtime fixture separately and do not claim a +complete translation. + +## References + +- Issue #2413 and its comments, especially the T6/T7 wave and dead-scalar slices. +- `docs/experiments/startup-mesh57-wave-block.md`, `startup-mesh57-dead-block-scalar.md`. +- `tools/startup/gfx2hlsl.py`: `inspect_mesh57_request`, `translate_mesh57`, `MeshPixelStage`. +- The public design description of DexNom/VIctory's mesh emitter and diff tests (GPL-3.0; read-only, + no code copied). diff --git a/docs/experiments/native-startup-request-cache.md b/docs/experiments/native-startup-request-cache.md index 976bc76baa..de9cc77722 100644 --- a/docs/experiments/native-startup-request-cache.md +++ b/docs/experiments/native-startup-request-cache.md @@ -1,19 +1,19 @@ # Startup request consumption and runtime cache publication in `compile_dxil` (#2933) [The fixture](../../tests/native_startup_request_cache_check.py) verifies that `compile_dxil --requests` consumes -revision-28 startup graphics (`x2w-startup-shader-28`, including ASCII `req_.psin` pixel-input descriptions) -and compute (`x2w-startup-shader-28cs`, `req_.c67`) requests, publishes runtime-named stage binaries and +revision-29 startup graphics (`x2w-startup-shader-29`, including ASCII `req_.psin` pixel-input descriptions) +and compute (`x2w-startup-shader-29cs`, `req_.c67`) requests, publishes runtime-named stage binaries and manifests (`.vs.cso` / `.ps.cso` or `.cs.cso`, followed by `.txt`), and loads directly through the startup runtime cache loaders on WARP and hardware without manual renaming or conversion. ## Alignment between `compile_dxil --requests` and the startup cache 1. **Request keys and `.psin` stream descriptions (`src/shader_compute_request.cpp`):** - - Graphics requests validate `x2w-startup-shader-28` over `.a`, `.b`, `.root`, and optional `.ia`. When + - Graphics requests validate `x2w-startup-shader-29` over `.a`, `.b`, `.root`, and optional `.ia`. When `req_.psin` is present, the reader parses `psin1 ena=0x addr=0x`, checks that the embedded key matches `` and `(ena & ~addr) == 0`, and folds `b"psin1" + struct.pack(" buf root `) manifest consumer + +Refs [#2618](https://github.com/R0Y00/Xbox2Windows/issues/2618), +[#2274](https://github.com/R0Y00/Xbox2Windows/issues/2274). +Follows the compute `global_load_dword` lowering in +[#2715](https://github.com/R0Y00/Xbox2Windows/pull/2715) (ticket `C500-01/031`). + +When a translated compute shader loads through a 64-bit root SRV pointer via +`global_load_dword`, `tools/startup/gfx2hlsl.py` emits `srv buf root ` +in the compute manifest (`.txt`) and lowers the read to +`ByteAddressBuffer r : register(t)` in the translated descriptor table. + +The production startup compute manifest consumer in +`src/startup_stubs/d3d12_compute_dispatch.inl` and command-list tracking in +`src/startup_stubs/d3d12_xs_device.cpp` now consume `srv buf root `: + +- Command-list slot 43 (`SetComputeRootShaderResourceView`) records the guest + address and a bound bit per compute root parameter on the open recording while + a compute root signature is bound. Binding a different compute root signature + in slot 33 (`SetComputeRootSignature`), closing the list (slot 9), or + resetting the list (slot 139) clears the recorded compute root SRV bindings; + re-binding the same compute root signature preserves them. +- `load_compute_translation` parses `srv %u buf root %d%n` (requiring an exact + whole-line match, `param >= 0`, and sequential `i == tr.srvs.size()`), and + rejects descriptor-word entry values (`stride`, `descword3`) that reference a + root SRV slot. +- At translated compute `Dispatch` (slot 14), `compute_root_srv_buffer` resolves + each `buf root ` input by verifying that `` in the bound compute + root signature has `D3D12_ROOT_PARAMETER_TYPE_SRV`, was set by slot 43 since + the compute root signature was bound or reset, has a non-null 4-byte-aligned + guest address at a 16-byte-aligned offset (`D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT`) + inside either a recording upload allocation (slot 148) or a live aliased + placed buffer in `COMMON` state (slot 133) with at least one whole dword + remaining, and does not alias an output UAV buffer. The resolved range is + bound as a raw `DXGI_FORMAT_R32_TYPELESS` `ByteAddressBuffer` view from that + offset to the end of its backing allocation or placed buffer (up to 16 MiB). + +## Verification + +`tests/startup_compute_root_srv_dispatch_check.py` (registered in +`tests/cmake/startup_compute_root_srv.cmake`) drives source-built gfx1013 +compute `global_load_dword` programs (1-root-SRV and 2-root-SRV variants) +through slot 67, slot 33, slot 43, slot 37/39, slot 35, and slot 14 in +`startup_stream_consumer` with `X2W_D3D12_DEBUG=1` on both `warp` and `hardware` +(`AMD Radeon RX 9070 XT`): + +- **Single and two-root-SRV dispatches:** 3x2x2 groups of 2x3x4 threads (288 + active lanes, 320 total output words) load at offset `0` and `+128` bytes from + one or two distinct placed input buffers (`srv 0 buf root 2` and + `srv 1 buf root 3`), including re-binding the same compute root signature, + non-zero byte offsets into placed buffers (`+16` bytes on root SRV 0, `+32` + bytes on root SRV 1) and recording upload memory (`+16` bytes via slot 148), + and out-of-bounds loads (`v4 + 128u` past the bounded 1,280-byte backing) + returning `0` rather than reading adjacent `0xdeadbeef` / `0xfeedface` + neighbor words in the same 64 KiB page. +- **Refusal controls:** malformed manifest lines (`root -1`, trailing tokens, + non-sequential SRV index, `udsrc ... stride` on a root SRV), unset root SRV + slot (first or second), root SRV cleared by `Reset` or by binding a different + compute root signature, wrong root parameter kind (`D3D12_ROOT_PARAMETER_TYPE_CBV` + at ``), null guest address, unaligned guest address (`addr + 2`), + non-16-byte-aligned interior resource offset (`addr + 4`), unmapped guest + address between placed buffers, non-aliased copied placed buffer, and + input-aliases-output-UAV hazard all refuse cleanly with their expected log + reasons and leave all 320 output sentinel words (`0xc5c5c5c5`) untouched. +- **Negative controls:** skipping `Dispatch`, swapping `srv 0 buf root 2` and + `srv 1 buf root 3` in the manifest, or dropping the `+ 128u` offset in the + translated HLSL changes all 288 active output words as predicted. + +Reproduce on Windows: + +```powershell +cmake --build --preset release --target d3d12_xs_shim startup_stream_consumer +ctest --preset release -j1 --no-tests=error -R '^startup_compute_root_srv_dispatch_(warp|hardware)$' -V +``` + +What remains a hypothesis: retail title compute dispatches that combine root SRV +pointers with unplaced host memory outside slot-133 placed buffers and slot-148 +recording upload allocations are not yet modelled here and remain refused until +a title call site establishes their backing contract. diff --git a/docs/experiments/startup-compute-volume-line-uav.md b/docs/experiments/startup-compute-volume-line-uav.md new file mode 100644 index 0000000000..0a3d4560e0 --- /dev/null +++ b/docs/experiments/startup-compute-volume-line-uav.md @@ -0,0 +1,14 @@ +# Startup compute stores to 3D and 1D UAVs + +The startup translator lowers full-channel compute `image_store` to +`RWTexture3D` with an integer XYZ address or `RWTexture1D` +with a scalar integer address. A 3D address can be a VGPR tuple or an NSA list. +Both forms use the fixed table descriptor and emit a `tex3d` or `tex1d` UAV +entry. Requests refused before this change are retried by `--pending`, so +the compute cache revision is unchanged. + +Dispatch uses the title's view at its selected mip. For 3D the shader's Z +coordinate is relative to `FirstWSlice`, and a W size of all ones selects +the remaining slices. The Dispatch fixture compares all mip-one texels +against a CPU reference and checks that a 2D view or an out-of-range W +selection leaves the texels unchanged. diff --git a/docs/experiments/startup-gfx2hlsl-bvh-box32.md b/docs/experiments/startup-gfx2hlsl-bvh-box32.md new file mode 100644 index 0000000000..8e9521be92 --- /dev/null +++ b/docs/experiments/startup-gfx2hlsl-bvh-box32.md @@ -0,0 +1,63 @@ +# First `image_bvh_intersect_ray` slice: FP32 box nodes + +`tools/startup/gfx2hlsl.py` now lowers the 32-bit `image_bvh_intersect_ray` (RDNA 2 MIMG opcode 230) for +one node form: the 128-byte FP32 box node, kind 5. The result is four child pointers, with `0xffffffff` for a +disabled child or a missed box. The helper performs the four slab tests, clips against `ray_extent`, and sorts +hits by entry distance only when bit 31 of the BVH T# is set. With sorting disabled it compacts hits in child +order, which is the order a traversal consumes the four results. + +The node layout is the one in Mesa 25.1.0 `src/amd/vulkan/bvh/bvh.h` (MIT): `children[4]` at bytes 0..15, +`coords[4][2][3]` at 16..111, and four reserved words at 112..127. The slab test follows Mesa +`radv_nir_rt_common.c` (MIT): inverse direction clamped to finite extremes, `tmin`/`tmax` from the three axes, +an inactive box whose `min.x` is NaN, `tmax >= max(0, tmin)`, `tmin < ray_extent`, and the five compare-exchange +stages that sort the four children. A child word of `0xffffffff` is a miss even when its stored box would hit. +The BVH T# fields are RDNA 2 ISA Table 49: base 39:0 (256-byte aligned), reserved 54:40, box growing 62:55, +box sorting 63, size 105:64, triangle return mode 120, big page 123 and type 8 at 127:124. + +## Accepted slice + +- compute stage only; +- `image_bvh_intersect_ray v[4], v[11], s[4]` with the packed address form (the disassembler prints `v[16:31]` + for the eleven consumed dwords); +- a constant inline T# built by four SGPR constants, type 8, base nonzero and 256-byte aligned, box growing zero, + size at least one 64-byte unit and below 4 GiB, and the node inside that size; +- a constant node pointer whose low three bits are 5, 128-byte aligned and inside the same 4 GiB address window; +- either value of the sort bit. + +The manifest names the node allocation with `srv bvh base 0x size 0x`. The host must bind a raw +`ByteAddressBuffer` at the base covering `(size + 1) * 64` bytes. That host binding is not part of this change. + +## Refused by name + +Triangle nodes (kind 0), 16-bit box nodes (kind 4), every other node kind, `image_bvh64_intersect_ray`, A16, +non-sequential addresses, a pixel or vertex stage, a node pointer that is not a straight-line constant, a T# +loaded at run time, a type other than 8, nonzero box growing, a misaligned base, an absolute base, a size that +does not cover the node, size bits above 4 GiB, and every reserved T# field. The checks assert that a refusal +emits no helper call and no destination VGPR assignment. + +## Evidence + +```text +python -B tests/startup_gfx2hlsl_bvh_check.py +``` + +The check compares the CPU box reference with the fixture in `tests/gfx1030_bvh_box/check.py` for six rays, +compares the emitted helper with the same reference, checks the sort-bit negative control (word 0 changes from +`0x1d` to `0x25`), checks the three-hit sort-disabled case whose equal keys must stay in child order +(`0x25, 0x2d, 0x35, 0xffffffff`), translates a synthetic constant-T# program and checks the four child results +and the manifest, and checks every refusal above. It also compiles the translated compute shader with DXC when +one is available; without DXC it prints `dxc compile: skip` and does not count that as a pass. + +```text +python -B tests/startup_gfx2hlsl_bvh_check.py dispatch warp +``` + +The dispatch mode compiles the same helper with a `RWByteAddressBuffer` in place of the bound +`ByteAddressBuffer`, writes the three synthetic nodes and six rays, and compares all twenty-four result words on +a Microsoft Basic Render Driver (`1414:008c`, driver `10.0.26100.10068`). It also dispatches a mutant that +leaves missed child words in place; the all-miss case 2 word 0 at words 136..139 must stop being +`0xffffffff`. That control caught the first version of this helper, which sorted the keys correctly but +returned the original child pointer for a miss. + +This is a translator slice. It does not execute the native gfx1030 probe, does not bind the node buffer on a +D3D12 device, and does not establish any title behavior. diff --git a/docs/experiments/startup-gfx2hlsl-cselect-descnum.md b/docs/experiments/startup-gfx2hlsl-cselect-descnum.md new file mode 100644 index 0000000000..1e33a3f2fc --- /dev/null +++ b/docs/experiments/startup-gfx2hlsl-cselect-descnum.md @@ -0,0 +1,87 @@ +# Scalar select on descriptor-derived data in gfx2hlsl compute stages (#2618, the C500 rows) + +In 250 compute rows of the C500-01 and C500-02 batches, the recorded refusal is `numeric use of sX holding descnum` +at `s_cselect_b32 sX, 0, sX`. Before this change, `Stage.scalar_select` in `tools/startup/gfx2hlsl.py` read both +sources as run-time values. A number computed from a buffer descriptor (`descnum`) has none, so the select refused. + +## Contract + +A select between descriptor data and zero can disable a buffer by zeroing its size. On the console such a buffer +returns zeros. A lowering that keeps only the descriptor arm would read real data instead. So in a compute stage, +`s_cselect_b32 sD, a, b` into an SGPR, where one source holds `descnum` and each other source is a constant, emits +no HLSL. sD holds `('descnum', 'cselect', offset, arm a, arm b)`: both arms and the offset of the select, whose +SCC picks one. + +Nothing reads that symbol as a value: + +- A numeric read still refuses with `numeric use of sD holding descnum`. This covers VALU and SALU sources, compares, + m0, store data and lane writes. +- `s_mov_b32` and `s_mov_b64` copy the symbol. Any other scalar ALU instruction with it in any register of a source + (the high word of a 64-bit pair too) refuses with ` on a select of descriptor data` + (`Stage.refuse_select_source`). It would otherwise become a plain `descnum` or an in-place edit of a descriptor + word, which loses the arm. This also covers the structured-to-raw conversion when its stride comes from such a + select. +- An access whose descriptor operand has the symbol in any word refuses with + `descriptor operand s[N:M]: sK holds a select of descriptor data` (`Stage.select_word`, called by + `Stage.descriptor`). On main b505c32b a buffer load ignores edits to words 1–3 of its descriptor (#2901), so + without this check a copied select would reach the load with the zero arm dropped. +- In compute, an access whose descriptor operand holds a word joined at a branch target after its first word + refuses with `descriptor operand s[N:M]: sK holds a word joined at a branch target` (`Stage.joined_word`). A join + of different symbols leaves only that mark, so a select that reaches a descriptor word on one path, or through a + loop back edge, would otherwise be dropped. This also refuses compute joins that bring two different non-select + words there. Main translates those, ignoring the difference, as in #2901. +- The select still refuses with `scc from descriptor data in s_cselect_b32` when its SCC came from an ALU + instruction on descriptor data, because that SCC is not emitted. + +Unchanged: `s_cselect_b64`, an m0, exec or vcc destination, a raw descriptor word or a pointer as a source, a +run-time register next to the `descnum` source, and every non-compute stage. + +A row only gets past the select if sX is dead afterwards or is only copied. Where sX is read later, the refusal moves +to that read. The packets record only the first refusal, so how often each case occurs is not known yet. + +## Checks + +`tests/startup_gfx2hlsl_cselect_descnum_check.py` splices synthetic instructions into case A of +`tests/startup_gfx2hlsl_compute_check.py`. The decoder must print the expected text for each one. + +- Accepted: the select with its result dead, in both source orders, with a literal source and on an extracted + stride. The HLSL may differ from case A only by the compare's `scc` line, and sD must hold both arms and the offset. +- Refused, each checked by its reason: every later use listed above, a copy into word 1, 2 or 3 of the load + descriptor (also through a second copy), a copy into the store descriptor, and SCC from descriptor data. +- Branches: the select writes no HLSL variable, so a join must not turn sD back into a run-time register. A read + after a forward join where one path skips the select, and a read at a loop head reached by a back edge after the + select, both refuse with `numeric use of s21 holding joined at a branch target`. The same forward join with a + run-time write in place of the select translates. +- Descriptor words through a join, from the #2903 review: a load after a join where one path selects into word 2 + of its descriptor, and the same select at the bottom of a loop whose head is the load, refuse as joined words. + The same join with the loaded word on both paths, and the same loop without the select, translate. A select in + the high word of `s_or_b64 s[14:15], s[20:21], 0` refuses. +- Only buffer load and store operands are exercised for the descriptor-operand refusal. Image, sampler and + `s_buffer_load` operands go through the same `Stage.descriptor` check but have no control here. +- Still refused as before: the unchanged forms above, in the compute stage and in the vertex and pixel probe stages. +- Negative controls, each a mutated translator that must fail a named check: + - `zero-arm-dropped`: the select keeps only its `descnum` source. The structured-to-raw conversion with the + selected stride then translates. + - `load-check-removed`: `select_word` finds nothing. A load through a copied select then translates. + - `alu-check-removed`: `refuse_select_source` accepts everything. An ALU copy into word 2 then reaches the load. + - `join-check-removed`: `joined_word` finds nothing. The load after the join, and the load at the loop head, then + translate. + - `high-word-unchecked`: `refuse_select_source` sees only the low word of each source. The `s_or_b64` case then + translates. + +```powershell +python -B tests/startup_gfx2hlsl_cselect_descnum_check.py +ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_cselect_descnum_(controls|warp)$" -V +``` + +The `warp` and `hardware` tests translate case A with the dead select, compile it with DXC `cs_6_0`, dispatch it +and compare all 320 words with case A's reference. + +Measured on Windows 11 build 26300 with Python 3.14 at the commit that adds this note (base b505c32b): the controls +pass (41 first-pass checks, and each of the five controls fails its named check). On b505c32b the same file fails +20 of its 34 first-pass checks. The four accepted cases are refused at the select, and 16 later-use, branch and +review checks get that refusal instead of their own reason. The mutation phase cannot run there, because the helpers +don't exist yet. + +Still a hypothesis: which later use of sX matters in the C500 rows. The packets don't show the instructions that +produce sX, write SCC or read sX afterwards. diff --git a/docs/experiments/startup-gfx2hlsl-pk-minmax.md b/docs/experiments/startup-gfx2hlsl-pk-minmax.md new file mode 100644 index 0000000000..351ce797c9 --- /dev/null +++ b/docs/experiments/startup-gfx2hlsl-pk-minmax.md @@ -0,0 +1,27 @@ +# Startup packed binary16 min/max + +The startup translator lowers `v_pk_min_f16` and `v_pk_max_f16` on gfx1013. +Each source is a single VGPR, numeric SGPR, 32-bit hex literal, or inline +integer zero. The inputs are packed words. `op_sel` selects each source's +half for the result's low half and `op_sel_hi` selects each source's half for +the result's high half. The defaults select the low and high halves +respectively. Other modifiers and source forms are refused. Packed add, mul +and fma still require VGPRs. + +The helper strips the binary16 sign and compares the remaining encoding +against infinity to identify NaNs. One NaN yields the other operand's +encoding. Two NaNs yield the chosen canonical quiet NaN `0x7e00`. The +two-NaN payload choice has no hardware confirmation. Numeric comparison uses +ordered integer keys and returns the original bits. In either operand order, +min chooses negative zero and max chooses positive zero when the signs +differ. Equal zeros retain their sign. + +The Python controls check emitted HLSL and operand refusals. The WARP and +hardware draw modes use a source-built gfx1013 fixture and compare both halves +with an independent CPU reference, including signed zeros, NaNs, infinity, +subnormals and literal and SGPR selector flips. + +```sh +python -B tests/startup_gfx2hlsl_pk_minmax_check.py +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_pk_minmax' +``` diff --git a/docs/experiments/startup-sampler-join.md b/docs/experiments/startup-sampler-join.md new file mode 100644 index 0000000000..eb6efeb2b4 --- /dev/null +++ b/docs/experiments/startup-sampler-join.md @@ -0,0 +1,21 @@ +# Two inline samplers at a uniform forward join + +For 2D explicit-level `image_sample_l` and `image_sample_lz`, a single forward SCC diamond may select two inline four-word sampler definitions. Both arms must finish by writing all four words as literals, with proven uniform control flow and unchanged EXEC. Only normalized point wrap/clamp XY addressing and point mip filtering are admitted, with validated LOD limits. Two `smpl` static bindings preserve the descriptors; the selected runtime word chooses between complete `SampleLevel` calls. Any intervening overlap write invalidates the join proof. Implicit derivatives, partial definitions and more complex control flow retain their existing refusals. + +The source-built fixture evaluates both root-constant selector outcomes for both sample forms with an independent point-texel oracle. A third variant holds word 0 unchanged and varies only MAX_LOD in word 1; the explicit level selects mip 1 or mip 0. Swapping sampler bindings changes the result in every variant. A decoded negative diamond keeps every field valid but sets bit 24 of word 1, above the whole-word-1 mask, so the guard refuses it as unsupported joined sampler words. Seven refusal controls and ten binary assembly variants are included. + +Both portable checks passed on Apple Silicon; the expanded ten-variant fixture was assembled with LLVM 15.0.7. + +```bash +python3 -B tests/startup_image_sample_l_join_check.py +python3 -B tests/startup_image_sample_l_join_check.py binary llvm-mc +``` + +The registered Windows draw consumes the actual translated shader, both manifest lines and the runtime selector. + +```powershell +cmake --build --preset dev --target offscreen_check +ctest --preset dev --no-tests=error -R '^startup_image_sample_l_join_' -V +``` + +DXC/WARP/hardware draw execution requires Windows and remains unmeasured locally. diff --git a/docs/experiments/startup-table-srv-alias.md b/docs/experiments/startup-table-srv-alias.md new file mode 100644 index 0000000000..7b8e51cfca --- /dev/null +++ b/docs/experiments/startup-table-srv-alias.md @@ -0,0 +1,104 @@ +# Table buffer views over aliased placed buffers (opt-in) + +A translated draw copies every buffer it reads from the title's descriptor table into the upload ring +(`frame_copy`, see [Copies of title memory within a frame](../startup-runtime.md#copies-of-title-memory-within-a-frame)). +Within a frame the copy is reused only after a full comparison with the bytes it was made from, and the copy is +cut at 16 MiB. Vertex streams and live indices in a slot 133 placed buffer that aliases title memory bind that +alias instead (#2724, #2834). `X2W_D3D12_TABLE_ALIAS=1` does the same for table buffer views. + +## What the switch changes + +- In the `draw_translated` view loop, a table buffer view (`source 0`) that is not a formatted load, with a + nonzero range of at most 512 MiB, looks its whole range up with `placed_buffer_range`. When that finds one live + placement of kind `aliased_buffer` and the view starts 16-byte aligned in it, the draw keeps the alias alive + with the recording, requires the shader-resource states and creates a raw view over the full range. +- The raw view covers whole DWORDs, so the lookup uses the range rounded up to 4 bytes. A view whose rounded + range would run past the placement keeps the copy. +- When the same alias is also the draw's live index buffer, it is put in the index-buffer and both + shader-resource states at once, so neither binding leaves the other in a wrong state. +- The GPU then reads the title's bytes at execution. A title write between recording and submission is visible + to the draw, as on the console, where the GPU reads the same memory when the work runs. With the copy, each + draw sees the bytes as they were when it was recorded. +- Ranges past 16 MiB are bound in full; the copy reads zeros there. +- Everything else keeps the copy: formatted loads, views outside a placement or across its end, placements + that are copied or shared (`X2W_D3D12_LINEAR_BUFFERS`), released resources, unaligned offsets. +- Unset, nothing changes. + +## Fixture + +```powershell +cmake --build --preset release --target startup_stream_consumer +ctest --preset release --no-tests=error -j 1 -R '^startup_table_alias_(warp|hardware)$' -V +``` + +`X2W_TEST_TABLE_ALIAS_WRITE`: a 256-byte slot 133 buffer placed on `VirtualAlloc` memory, a raw view the title +creates over it (device slot 18) at table entry 0, and a vertex shader that reads one 8-byte record. The title +writes 40, draws the left half, writes 80, draws the right half, and writes 120 after recording, before the +list runs. + +- Unset: left 40, right 80 (each draw's copy). +- Set: both halves 120 (the alias, read at execution). +- Negative control: the same fixture with the buffer in image memory (a static array) is placed "not aliased", + and the set arm then reads 40 | 80 and fails. + +Two more cases run with the switch set. The fixture skips (77) when the adapter has no existing heaps. + +- `shared-index`: the buffer also holds the indices of one indexed draw (indices 0–2 at offset 0, index view + over the same placement). It runs under the debug layer with GPU-based validation + (`X2W_TEST_DEBUG_LAYER=1 X2W_TEST_GPU_VALIDATION=1`) and must report no error and draw 40. +- `odd-size`: a 254-byte buffer under a structured view of 127 two-byte records. The 256-byte raw view would + run past the alias, so the draw takes the copy and shows 40, not the value 120 written after recording. + +## Startup run of the main executable + +Local diagnostic runs, Windows 10 22H2 (19045), RTX 3080 Ti, NVIDIA driver 32.0.16.1047, i7-4790K, release +build of this change on top of #2949 with `X2W_D3D12_RING_RELEASE_AT_SUBMIT=1`, warm shader cache, +`run.ps1 -Render` without `-Translate`, scripted input, 250 s. One build; only `X2W_D3D12_TABLE_ALIAS` differs. +Two pairs, the second in reverse order. Aggregates only; logs stay local. + +| frames per second, 30 s windows | 150–180 s | 180–210 s | 210–240 s | +|---|---|---|---| +| unset, pair 1 / pair 2 | 8.9 / 8.6 | 5.1 / 7.8 | 3.7 / 4.2 | +| set, pair 1 / pair 2 | 11.5 / 9.8 | 8.0 / 11.2 | 6.6 / 6.1 | + +| per run, pair 1 / pair 2 | unset | set | +|---|---|---| +| translated draws | 64,296 / 88,027 | 97,419 / 100,254 | +| list executes | 14,774 / 18,151 | 22,979 / 21,373 | +| null bindings with cause `buffer` | 0 / 0 | 0 / 0 | +| null bindings per 1,000 load-phase draws (all cause `token`) | 53.8 / 46.5 | 54.0 / 50.8 | +| process commit peak | 18.1 / 17.1 GiB | 17.9 / 18.1 GiB | +| device removal | none | none | + +- Before 150 s (intro and menus) both settings run at about 30 fps. +- Where the time went, from local timers that are not part of this change (150–240 s, threads busy): + - unset: about 1.9 threads waited for `draw_lock`; the lock was held about 58 % of the time, mostly by + `draw_translated`, and 86 % of that hold was `frame_copy`; + - 97 % of the `frame_copy` time was one view: 16 MiB (cut from a 90 MiB slot 133 placed buffer that aliases + title memory) compared in full on about 140 draws per second, almost always unchanged; + - set: the lock waits fell to about 0.1–0.3 threads and the copy of that view was gone. +- A user watching the set run saw no visual difference or glitches. + +Retest after the review fixes (index state, rounded range), same settings, two more pairs (the second again in +reverse order), build = this branch after merging `main` `fb955a51`, on top of #2949: + +| frames per second, 30 s windows | 150–180 s | 180–210 s | 210–240 s | mean | +|---|---|---|---|---| +| unset, pair 3 / pair 4 | 6.3 / 7.9 | 9.3 / 4.5 | 3.8 / 4.0 | 6.5 / 5.5 | +| set, pair 3 / pair 4 | 11.9 / 11.7 | 7.9 / 10.8 | 6.5 / 8.0 | 8.8 / 10.2 | + +| per run, pair 3 / pair 4 | unset | set | +|---|---|---| +| translated draws | 73,904 / 89,833 | 120,081 / 122,176 | +| list executes | 16,022 / 21,080 | 28,516 / 25,474 | +| not drawn in the load (missing translations) | 47 % / 50 % | 50 % / 49 % | +| null bindings with cause `buffer` | 0 / 0 | 0 / 0 | +| process commit peak | 17.5 / 17.3 GiB | 17.6 / 17.5 GiB | +| device removal | none | none | + +- `draw_lock` waits 150–240 s: unset 1.0–1.5 threads, set 0.08–0.14; the draw hold 0.4–0.56 vs 0.07–0.09. +- Unset, the 16 MiB view is again 83–86 % of `frame_copy` time; set, no copy above 64 KiB remains. +- The pair 4 set arm reached the load later (27.8 fps at 120–150 s vs 19.2), which favours its later windows. + +Not established: other titles, AMD adapters, and whether any draw in this title depends on a value written +between recording and submission (none was seen). diff --git a/docs/experiments/startup-upload-ring-release-at-submit.md b/docs/experiments/startup-upload-ring-release-at-submit.md new file mode 100644 index 0000000000..b24ea0e27e --- /dev/null +++ b/docs/experiments/startup-upload-ring-release-at-submit.md @@ -0,0 +1,78 @@ +# Upload ring: release a closed list's chunks at its fenced submit (opt-in) + +Refs [#2837](https://github.com/R0Y00/Xbox2Windows/issues/2837), +[#2849](https://github.com/R0Y00/Xbox2Windows/pull/2849). + +Since #2823 a reservation in the shared upload ring keeps its bytes until its chunk is recycled, and #2849 +recycles a chunk only when no command-list recording holds it and every queue that used it has passed its +fence. A closed list keeps its hold until Reset, Release or a failed Close, because D3D12 lets it be submitted +again. `X2W_D3D12_RING_RELEASE_AT_SUBMIT=1` moves that release to the list's fenced submit and sizes the ring +in 16 MiB chunks up to 512 MiB. + +## What the switch changes + +- After a submit whose queue fence was signalled, each submitted list stops holding its chunks + (`release_upload_chunks_at_submit`). The queue fence still keeps those chunks from reuse until the GPU has + passed it. Without a signalled fence nothing changes: the chunk stays busy, as without the switch. +- The list records the generation of each chunk it released. If the same list is submitted again before its + Reset, chunks with an unchanged generation are fenced again by that submit + (`resubmitted_upload_chunks`). If a chunk was recycled in between, the list would read replaced bytes: the + queue leaves it out of `ExecuteCommandLists` (`released_chunks_recycled`, checked with `draw_lock` and + `allocator_lock` held, the same locks the submit bookkeeping holds), counts it and logs the first eight + (`... were reused; refused, it is not executed`). The other lists of that call still run, as a list that is not + closed is left out today. It stays refused until its Reset, which records it afresh. +- The ring grows in 16 MiB chunks up to 512 MiB, so one list that is still recording or waiting to be submitted + pins 16 MiB instead of a chunk of up to 128 MiB. +- Unset, the ring behaves exactly as before: doubling chunks up to 256 MiB, holds until Reset. + +## Fixtures + +```powershell +cmake --build --preset release --target startup_stream_consumer upload_reservation_check d3d12_xs_shim +ctest --preset release --no-tests=error -j 1 -R '^(upload_reservation|startup_address_console_gate_ring_keep(_release)?_(warp|hardware))$' -V +``` + +- `upload_reservation`: `check_release_at_submit` releases two chunks after a fenced submit, keeps them from + reuse until the fence passes, reuses one, then finds the other intact and the reused one recycled on a + resubmit, and fences the intact one again. Mutants: keeping the holds fails "release: holds dropped"; + ignoring generations fails "a resubmit finds chunk 1 intact and chunk 0 reused". +- `startup_address_console_gate_ring_keep_*` (`X2W_TEST_CONSOLE_KEEP`): a second list A uploads 32 by-address + payloads of 16 MiB each from the ring (512 MiB), is submitted, completes and is never Reset. The fixture's own + list then draws payload 32 over the right half of the target, A is submitted again, and the target is read back + after that submit. + - Without the switch, A keeps every chunk: the ring refuses past 256 MiB and the right half reads the null + view. + - `..._keep_release_*` sets the switch: the right half holds payload 32 from a chunk A released. A's second + submit would read a reused chunk, so it is refused and not executed: the right half still holds payload 32, + not A's payload 31. + - Mutants: disabling the release leaves the right half on the null view; executing the stale resubmit (the + check before the execute removed) puts A's draws back over the right half and fails on wrong pixels. +- Fixtures that describe the default ring clear the switch for their own process, so they keep testing the + default mode when it is set in the environment: the #2849 `startup_address_console_gate_ring{,_reuse}_*` + (a refusal at the 256 MiB cap) and `startup_slot133_heap_cap_capped_*` (doubling growth to 48 MiB). + +## Startup run of the main executable + +Local diagnostic runs, Windows 10 22H2 (19045), RTX 3080 Ti, NVIDIA driver 32.0.16.1047, i7-4790K, 16 GB, +release build of this change, warm shader cache, `run.ps1 -Render` without `-Translate`, scripted input, 250 s. +One build; only the switch differs. Aggregates only; logs stay local. + +| | switch unset | switch set | +|---|---|---| +| null bindings with cause `buffer` | 33,632 | 0 | +| `upload ring reservation refused` logged | yes | no | +| resubmits after a reuse (now refused) | n/a | 0 | +| process commit peak | 16.7 GiB | 18.1 GiB | +| visible | single full black frames in the post-load animation | none seen | + +- Without the switch, a census at each refusal showed every chunk held by closed lists not yet Reset, while + every queue had passed the chunk's fence. Most refused requests were 64 KiB: the window + `upload_from_title` copies for a graphics root SRV without an existing upload mapping. +- The title never submitted a closed list again without a Reset: 0 of more than 500,000 submits over five runs. + A title that does resubmit after a reuse gets the refusal described above: that list does not run. +- The larger ring cost about 1 GiB of process commit at peak in this run. +- Repeated after the stale-resubmit refusal, on a later `main`, same settings: buffer null bindings 50,665 → + 0, reservation refusals logged → none, stale resubmits refused 0 → 0, commit peak 17.9 → 18.0 GiB, black + frames → none seen. + +Not established: other titles' resubmit behaviour, and whether 512 MiB is enough on other workloads. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index a97fd2607d..c8e239f248 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -208,7 +208,10 @@ The translation is refused when: - either header has another size; - the code reads an attribute the table does not list. -Graphics and compute use cache revisions `x2w-startup-shader-28` and `x2w-startup-shader-28cs`. +Graphics and compute use cache revisions `x2w-startup-shader-29` and `x2w-startup-shader-29cs`. +Revision 29 invalidates compute translations whose skipped-block proof kept a stale clear `vcc_hi` fact +across an unsigned `v_mad_u64_u32` carry-out, which may write `vcc_hi` in wave64 like the compares and +the other carry-outs. Revision 28 lowers `v_fma_mix*` through a `precise` `mad`, so a zero product keeps its sign. Revision 25 preserves the sign of zero in binary16 multiply, including the packed and SDWA forms. Revision 24 invalidates translations that revision 23 wrongly accepted: `vcc_hi_scalar_mask_read` now also @@ -326,6 +329,18 @@ to a real present. The contract under the switch: Neither line is the composited window picture. +The diagnostic readback publishes pixels only after its queue fence reaches +the submitted value without reporting device removal. A timeout, a failed +event registration or an incomplete fence after the event registers a drain: +a threadpool wait on the submitted fence value that releases the held surface +and queue references once the fence completes and publishes no pixels, so a +final sample no longer keeps them for the module lifetime. The drain releases +only the submission it was registered for (a later sample owns its own) and +never releases pending, failed-signal or device-removed work; a failed signal +or removed device disables further diagnostic readback for the module +lifetime. `startup_present_readback` exercises the completion policy and the +ownership retirement without a GPU. + The first presents and every 300th log each plane: ```text @@ -517,6 +532,17 @@ one address between two draws of a frame, such as a dynamic constant buffer, gav data. The comparison uses the kept bytes because the ring is write-combined memory that is slow to read. `startup_frame_copy_{warp,hardware}` rewrites a constant buffer between two draws and checks both halves. +A table buffer view (an SRV read from the title's descriptor table) is copied the same way, at most 16 MiB of it. +For a large view the comparison costs a full read of the kept bytes on every draw, under `draw_lock`. With +`X2W_D3D12_TABLE_ALIAS=1` (opt-in, render mode), a table buffer whose whole range lies in a slot 133 placed buffer +that aliases title memory binds that alias instead, as vertex streams and live indices already do: no copy, no +comparison, and no 16 MiB cut. The GPU then reads the bytes as they are when the list runs, not as they were when +the draw was recorded, so a title write between recording and submission becomes visible to the draw (on the +console, the GPU also reads the shared memory at execution). Formatted loads, views over other memory and +unaligned offsets keep the copy. `startup_table_alias_{warp,hardware}` writes a record, draws, rewrites it, draws +again and rewrites it after recording: unset, the halves show the first two values; set, both show the third. See +[the experiment note](experiments/startup-table-srv-alias.md). + ## Root signature changes and dropped root constants Command-list slot 34 (`SetGraphicsRootSignature`) clears the translated draw's cached descriptor tables, root @@ -873,7 +899,11 @@ the debugger and stops it, with its worker processes, when the debugger returns without `-Render` is ignored with a warning). The watcher repeats the `--pending` scan every 2 seconds (`--watch ` sets another interval), so a pipeline the title creates during the run is translated within seconds, and the runtime picks it up on a later draw instead of on the -next run. The cache persists: a later run reads every published `.txt` and translates only new +next run. The runtime looks for an absent manifest again 1 second after the first miss and doubles +the wait with each further miss up to 32 seconds. A translation published during the run is therefore +used on a draw or Dispatch at most 32 seconds later, and a key that never gets a translation costs one +cache lookup every 32 seconds instead of one per second (each lookup holds `draw_lock`, which every draw +and Dispatch takes). The cache persists: a later run reads every published `.txt` and translates only new requests. The watcher's first pass retries every earlier failure once, so a translator update reaches requests that failed in an earlier run; after that, a request whose `.fail` is newer than its ready marker is not retried during the run (the runtime writes each request once and never rewrites @@ -1497,6 +1527,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_NATIVE_SHADERS=` (`run.ps1 -NativeShaders `) | experimental, in render mode: translates device slot 67 compute requests in the stand-in with the C++ compiler; `` holds `dxcompiler.dll` and `dxil.dll`. See [Translating compute programs in the stand-in](#translating-compute-programs-in-the-stand-in) | | `X2W_D3D12_LINEAR_BUFFERS=1` or `=copy` | opt-in backing for linear buffers placed at a title address (device slot 133, initial state `COMMON`): shared where the adapter, extent and memory allow it (private allocations larger than 256 MiB are skipped only with `X2W_D3D12_CAP_EXISTING_HEAP=1`), otherwise copied from title memory at each submission, otherwise the default backing is kept and the refusal recorded; `copy` never shares. Unset or `0`, slot 133 keeps its default backing. See [Linear buffer backing (device slot 133, opt-in)](#linear-buffer-backing-device-slot-133-opt-in) | | `X2W_D3D12_CAP_EXISTING_HEAP=1` | opt-in 256 MiB (`unplaced_existing_heap_allowed`) allocation-size cap on `OpenExistingHeapFromAddress` in device slot 133 (`startup_slot133_heap_cap_*`). Unset (default), private allocations larger than 256 MiB keep the formerly aliased path: a capped copied placement is refused by `CopyBufferRegion` (list slot 15) as `title_backed_source`, losing a late guest write made after recording and before submit. Set, allocations larger than 256 MiB skip `OpenExistingHeapFromAddress` so multi-GiB startup blocks are not pinned in `WorkingSetSize` and `NonLocal` GPU memory | +| `X2W_D3D12_RING_RELEASE_AT_SUBMIT=1` | opt-in, render mode: a closed command list releases its upload ring chunks once its submit is fenced instead of holding them until Reset, and the ring grows in 16 MiB chunks up to 512 MiB (default: doubling chunks up to 256 MiB, holds until Reset). The larger ring can add up to about 1 GiB of process commit at peak (startup runs in the experiment note). A later submit of the same list before its Reset fences its unchanged chunks again; if one was reused in between, that list is refused before the execute and logged (`startup_address_console_gate_ring_keep_*`, `upload_reservation`). See [the experiment note](experiments/startup-upload-ring-release-at-submit.md) | | `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the hypothesised occlusion query methods (see [Occlusion queries](#occlusion-queries)). Unset, the three slots stay no-ops | | `X2W_D3D12_BUDGET=1` | adds [video memory budget and allocation counts](#d3d12-resource-budget) to the D3D12 heartbeat | | `X2W_D3D12_RELEASE_RETIRED=1` | opt-in, effective with `X2W_D3D12_RENDER=1` only (the list handlers that record holds exist only there): frees the desktop object of a released committed 2D texture of one narrow class once no recorded list, submission or release-time fence refers to it ([details](#d3d12-resource-budget)). Unset, nothing changes | @@ -1505,6 +1536,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_D3D12_VIEW_DEFAULTS=all` or `=off` | `all` is experimental: UAV, RTV and DSV descriptions with `ViewDimension` 0 also get the resource's default view, which drops their requested format and component mapping. `off` skips the measured SRV case too. Unset, only SRVs of typed non-depth textures get the default view ([details](#unknown-and-mismatched-view-dimensions)) | | `X2W_D3D12_VIEW_CENSUS=1` | diagnostic only: counts new distinct view records by device slot (a heartbeat line), and logs the record vector capacity and hash bucket count before either grows ([details](#d3d12-view-census)). Unset, nothing is counted or logged | | `X2W_DRAW_NULL_IDENTITY=1` | null descriptors read as identity values instead of zero | +| `X2W_D3D12_TABLE_ALIAS=1` | opt-in, render mode: a translated draw's table buffer view whose whole range lies in a slot 133 placed buffer that aliases title memory binds that alias instead of a per-draw frame copy, so the GPU reads the bytes at execution and the view is not cut at 16 MiB (`startup_table_alias_*`). Unset, every table buffer view is copied as before. See [Copies of title memory within a frame](#copies-of-title-memory-within-a-frame) | | `X2W_DEPTH_STATE=1` | translated draws of slot 57 pipelines take their depth-stencil state and stencil reference from state block A instead of the desktop default (depth and stencil off); a refused block keeps the default. Off by default, then nothing changes: see [Shortcuts that are known to be wrong](#shortcuts-that-are-known-to-be-wrong) | | `X2W_PRESENT_SIGNATURE_EVERY=` | in render mode, samples a coarse signature of the presented picture every `n` presents from the start, without a script request (`0` off). Unset, sampling starts, every 4 presents, only once a script with a `wait` asks for it: see [Waiting for the presented picture](#waiting-for-the-presented-picture) | | `X2W_D3D12_DUMP_SURFACE=` | writes the last presented surface | @@ -1943,7 +1975,9 @@ reduces them to 32 x 18 cells of mean luma. Command lists do not hold the resour sampler holds its own reference to the presented surface until the copy's fence has passed; a title may release the surface right after the present. If `Signal` fails after the copy was submitted, sampling stops and the surface, command list and readback buffer stay referenced for the rest of the -process. It publishes them in a named block, +process. A removed device (the fence reporting `UINT64_MAX`) is never treated as a completion: +the readback is not mapped, no sample is published, sampling stops, and the surface stays referenced +for the rest of the process. It publishes them in a named block, `Local\x2w_present_signature_`, so other tools can read it too (`src/startup_stubs/present_signature.h` describes the layout). The 8-bit and 10:10:10:2 colour formats are read; for others it logs @@ -2202,6 +2236,10 @@ These are measured on one executable; treat them as hypotheses for others. integer form against an integer reference, and the draws on WARP and hardware check 16 x 16 pixels that a `v_cmpx_le_i32_sdwa` on a sign-extended byte keeps or discards, with translations that drop the select or `sext()` as failing controls. [#1906](https://github.com/R0Y00/Xbox2Windows/issues/1906) +- **Packed binary16 min/max.** `v_pk_min_f16` and `v_pk_max_f16` select each result half from + packed VGPR, numeric SGPR, hex literal or inline zero sources. The bitwise comparison preserves + signed zeros and returns the numeric operand when its partner is NaN. See + [the packed min/max experiment](experiments/startup-gfx2hlsl-pk-minmax.md) for the fixture and checks. - **DPP quad pair broadcasts.** The four pair permutations of a pixel stage (`quad_perm:[1,1,3,3]`, `[0,0,2,2]`, `[2,3,2,3]`, `[0,1,0,1]`, with `row_mask:0xf bank_mask:0xf`, and `bound_ctrl` since no source lane is disabled) lower on any VOP1 or VOP2 whose first source is a VGPR. The four lanes of the quad are read with the shader model 6.0 `QuadReadLaneAt` and the lane `quad_perm` names is selected by the parity of `SV_Position`; a stage that uses it compiles with DXC `ps_6_0` (`X2W_DXC`), and the result goes through a scratch register so a second source naming the @@ -2258,6 +2296,13 @@ These are measured on one executable; treat them as hypotheses for others. and any other read of it is refused ([the note](experiments/startup-gfx2hlsl-pixel-first-lane.md)). Run `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_pixel_first_lane"`. [#2618](https://github.com/R0Y00/Xbox2Windows/issues/2618) +- **Select on descriptor data.** In a compute stage, `s_cselect_b32 sD, a, b` with one source a number computed + from a descriptor (`descnum`) and the others constants, such as `sX, 0, sX`, emits no HLSL. sD keeps both arms as + a symbol with no run-time value. A numeric read, scalar ALU other than a move, or a descriptor operand holding it + (also as a word joined at a branch target) is refused, so an arm that zeroes a buffer's size is never dropped + ([the note](experiments/startup-gfx2hlsl-cselect-descnum.md)). Run + `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_cselect_descnum"`. + [#2618](https://github.com/R0Y00/Xbox2Windows/issues/2618) - **Soft asserts.** Retail code keeps `int3` instructions followed by a continuation. Without a debugger the title's handler steps over them; under the startup debugger use `-ContinueAsserts N`. One of them fires about ten times a second in the texture-streaming path @@ -2362,25 +2407,39 @@ These are measured on one executable; treat them as hypotheses for others. - **Pixel-stage image stores.** In a pixel stage, `image_store` with `dim:SQ_RSRC_IMG_2D` and `dmask:0xf` becomes a typed store to a `RWTexture2D` at its own `u` register, under the lane's exec bit, and the manifest becomes version 2 with a - `uav tex2d table ` line. The cache-policy bits are accepted. A partial - channel mask (a typed store writes all four channels), other dimensions, `d16`, `a16`, `tfe`, - `lwe`, `r128`, `image_store_mip`, a store outside a pixel or compute stage, and a program that loads - and stores the same image are refused by name. A - hand-assembled program stores four distinct values at texel (1, 2). The desktop draw reads all 16 - texels of a 4x4 image back; deleting the store or exchanging x and y must fail. Run + `uav tex2d table
` line. The same full mask on `dim:SQ_RSRC_IMG_2D_ARRAY` + uses three address registers, a `RWTexture2DArray` and a `tex2da` line. The cache-policy + bits are accepted. A partial pixel-stage 2D DMASK writes only the selected components + (`w0[uint2(x, y)].xz = ...`) and does not read the texel, so two invocations can update disjoint + channels of one texel. Compute stores, D16 stores and array stores still require `dmask:0xf`. An + empty or out-of-range mask, a dimension other than 2D or 2D-array, `d16`, `a16`, `tfe`, `lwe`, + `r128`, `image_store_mip`, a store outside a pixel or compute stage, and a program that loads and + stores the same image are refused by name. A hand-assembled program stores four distinct values at + texel (1, 2). Another draws two pixels in one pass; both address that texel, one with `dmask:0x1` + and one with `dmask:0x4`, and both updates must survive. Writing the second value into y instead of + z must fail. The desktop draw reads all 16 texels of a 4x4 image back; deleting the store or + exchanging x and y must fail. Run `ctest --preset release --no-tests=error -R '^startup_pixel_image_store_' -V`. -- **Binding pixel-stage image stores.** A translated draw binds each `uav N tex2d table P O` line +- **Compute stores to 3D and 1D images.** A compute `image_store` with `dmask:0xf` on a 3D or 1D image + becomes a store to `RWTexture3D` or `RWTexture1D`, and Dispatch binds the title's + 3D or 1D view after checking its mip and, for 3D, its W range. See + [Startup compute stores to 3D and 1D UAVs](experiments/startup-compute-volume-line-uav.md). +- **Binding pixel-stage image stores.** A translated draw binds each `uav N tex2d|tex2da table P O` line as a UAV range `u0..` placed after the SRVs in the translated root signature's view table. The view is made from the unordered-access view the title created at that table entry (`resolve_pixel_uavs` in `d3d12_draw.inl`), on - mip 0 of a 2D texture, and the texture is in `UNORDERED_ACCESS` for the draw. Refusals are logged + mip 0 of a 2D texture, or of a 2D array when the line says `tex2da`, and the texture is in `UNORDERED_ACCESS` for the draw. Refusals are logged with their reason and nothing is bound in place of the view. When the manifest is loaded, the translation is not used for another image kind, a buffer line (`uav N raw table P O`, the vertex-stage store of #2059), a view qualifier (`float`, `uint`, `sint`, as in the compute line), another source, extra fields such as - `channels`, an index out of order or more than eight views. At draw time, + `channels`, an index out of order or more than eight views. A trailing `typedload` is the one extra + word that is read: the binding must also support a typed UAV load. The translator does not emit it + for a component store, which does not read the texel. At draw time, the draw is not translated for no table at the parameter, an entry outside the bound table, an - entry without a view, a view that is not a UAV, a resource without `ALLOW_UNORDERED_ACCESS`, an - array, 3D, 1D or multisampled resource, a view of another dimension, mip or plane, an integer, - sRGB or non-colour format, a format without typed UAV store, and a texture that is also an SRV, + entry without a view, a view that is not a UAV, a resource without `ALLOW_UNORDERED_ACCESS`, a + `tex2d` line on an array resource, a `tex2da` line whose view is not a 2D array, a 3D, 1D or + multisampled resource, a view of another dimension, mip or plane, an integer, + sRGB or non-colour format, a format without typed UAV store, a `typedload` binding whose format has + no typed UAV load, and a texture that is also an SRV, a render target or the depth texture of the draw; these checks run before any view of the draw is written or any texture changes state. Indirect draws refuse a translation with a `uav` line. Compute UAVs and barriers between draws that write and read the same texture are not covered. `tests/startup_pixel_uav_check.py` @@ -3393,6 +3452,18 @@ signal or a removed device keeps the chunk busy. When no chunk qualifies, the reservation is refused; live storage is never reset. Recycling bumps the chunk's generation, and a cached frame copy from an older generation is not reused. +With the opt-in `X2W_D3D12_RING_RELEASE_AT_SUBMIT=1`, a closed list stops +holding its chunks as soon as its submit is fenced: the queue fence alone then +keeps the chunks from reuse until the GPU has passed it. The ring grows in +16 MiB chunks up to 512 MiB in this mode. If the same list is submitted again +before its Reset, the submit fences its chunks again when their generation is +unchanged. If a chunk was recycled in between, the list would read replaced +bytes: it is left out of `ExecuteCommandLists` before the execute, counted and +logged (`closed list ... submitted again after its released chunks ... were +reused; refused, it is not executed`) until its Reset. The mode therefore suits +titles that Reset a list before submitting it again. `startup_address_console_gate_ring_keep_*` keeps one list +closed and never Reset while a second list needs ring space, without and with +the switch. See [the experiment note](experiments/startup-upload-ring-release-at-submit.md). `upload_reservation` exercises the shared cursor and returned-pointer contract without D3D12; on non-Windows hosts run `c++ -std=c++17 -Isrc tests/upload_reservation_check.cpp -o out/upload_reservation_check && out/upload_reservation_check`. diff --git a/src/shader_compute_request.cpp b/src/shader_compute_request.cpp index 1ec6636796..543c3b14c2 100644 --- a/src/shader_compute_request.cpp +++ b/src/shader_compute_request.cpp @@ -190,7 +190,7 @@ x2w::GraphicsRequest x2w::read_graphics_request(const fs::path &marker) { request.input_layout = part(marker, ".ia", 1 << 20); if (fs::exists(fs::path(marker).replace_extension(".psin"))) parse_pixel_inputs(marker, expected, request.pixel_entry, request.pixel_input_description); - constexpr char revision[] = "x2w-startup-shader-28"; + constexpr char revision[] = "x2w-startup-shader-29"; uint64_t key = 1469598103934665603ull; hash_bytes(key, revision, sizeof(revision) - 1); for (const auto *p : {&request.a, &request.b, &request.root, &request.input_layout, &request.pixel_entry}) @@ -217,7 +217,7 @@ x2w::ComputeRequest x2w::read_compute_request(const fs::path &marker) { read(desc, 16) != sa.size() || read(desc, 32) != sb.size()) throw std::runtime_error("inconsistent compute request"); uint64_t key = 1469598103934665603ull; - constexpr char revision[] = "x2w-startup-shader-28cs"; + constexpr char revision[] = "x2w-startup-shader-29cs"; hash_bytes(key, revision, sizeof(revision) - 1); for (const auto *p : {&code, &data, &root, &desc, &sa, &sb}) { uint64_t size = p->size(); diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 6e0be0f75a..3dfc274449 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -1,8 +1,9 @@ // Translated compute programs at Dispatch (list slot 14). A device slot 67 pipeline is a placeholder that keeps // the key of its published request; gfx2hlsl.py --pending answers the request with .txt (`stage cs`) and -// .cs.cso. Bound from the compute tables recorded by slot 35: raw buffers (`srv buf table ` -// inputs, `uav table ` outputs) named by hardware buffer descriptors, and 2D textures -// (`srv tex2d table ` inputs, `uav tex2d/tex2da float table channels 4` outputs) named +// .cs.cso. Bound from the compute tables recorded by slot 35 and compute root SRVs recorded by slot 43: raw +// buffers (`srv buf table ` and `srv buf root ` inputs, `uav table ` +// outputs) named by hardware buffer descriptors or 64-bit root SRV addresses, and textures +// (`srv tex2d table ` inputs, `uav tex1d/tex2d/tex2da/tex3d float table channels 4` outputs) named // by the token of a view the title created (device slots 18 and 19). `smp` lines become static samplers. Entry // values come from the compute root constants of slots 37 and 39, or from the descriptor a buffer input or output is // bound from: its stride and word 3 (`stride`, `descword3`), and word 3, the upper half of word 1 and the record @@ -11,6 +12,15 @@ // binds nothing (the upload of an input texture the title filled in memory may already be recorded: it only // syncs content). +const char* volume_uav_range_error(const D3D12_RESOURCE_DESC& resource, const D3D12_TEX3D_UAV& view) +{ + if (view.MipSlice >= resource.MipLevels) return "an output 3D texture mip is outside the resource"; + const UINT depth = (std::max)(1u, UINT{resource.DepthOrArraySize} >> (std::min)(view.MipSlice, 15u)); + if (view.FirstWSlice >= depth || !view.WSize || (view.WSize != ~0u && view.WSize > depth - view.FirstWSlice)) + return "an output 3D texture W range is outside the mip"; + return nullptr; +} + struct ComputeTranslation { // Root parameter and byte offset (views), or parameter and word (entry values). A heap view names the root // constant (parameter and word) that indexes its 32-byte record in the list's view heap, or, with word_param @@ -23,11 +33,12 @@ struct ComputeTranslation { int word_param = -1, word_byte = 0; std::uint32_t at = 0, times = 0; Source source = root_constant; - bool array = false; + D3D12_UAV_DIMENSION uav_dimension = D3D12_UAV_DIMENSION_UNKNOWN; + bool root = false; }; u64 key = 0; int state = 0; // 0 not loaded, 1 ready, 2 unavailable - ULONGLONG retry_manifest_at = 0; // only an absent manifest can become ready later + x2w_startup::ManifestRetry manifest_retry; // only an absent manifest can become ready later std::vector uds, srvs, uavs; x2w_startup::TranslatedSamplers samplers; // static ones only x2w_startup::ComPtr root; @@ -90,10 +101,10 @@ const char* load_compute_translation(ComputeTranslation& tr) wchar_t path[MAX_PATH]; std::string manifest; if (!cache_path(path, L"", tr.key, L".txt") || !read_text(path, manifest)) { - tr.retry_manifest_at = GetTickCount64() + 1000; + tr.manifest_retry.missed(GetTickCount64()); return nullptr; } - tr.retry_manifest_at = 0; + tr.manifest_retry.found(); unsigned declared_uds = 0, line_number = 0; for (std::size_t at = 0; at < manifest.size(); ++line_number) { std::size_t end = manifest.find('\n', at); @@ -120,6 +131,13 @@ const char* load_compute_translation(ComputeTranslation& tr) if (!std::strcmp(name, names[s])) return static_cast(s + 1); return ComputeTranslation::root_constant; }; + const auto uav_dimension = [&] { + if (!std::strcmp(name, "tex1d")) return D3D12_UAV_DIMENSION_TEXTURE1D; + if (!std::strcmp(name, "tex2d")) return D3D12_UAV_DIMENSION_TEXTURE2D; + if (!std::strcmp(name, "tex2da")) return D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + if (!std::strcmp(name, "tex3d")) return D3D12_UAV_DIMENSION_TEXTURE3D; + return D3D12_UAV_DIMENSION_UNKNOWN; + }; if (line.empty() || (std::sscanf(line.c_str(), "group %u %u %u%n", &x, &y, &z, &used) == 3 && whole())) continue; if (std::sscanf(line.c_str(), "ud %u%n", &declared_uds, &used) == 1 && whole()) continue; if (std::sscanf(line.c_str(), "udsrc %u rootconst %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.uds.size()) @@ -129,6 +147,11 @@ const char* load_compute_translation(ComputeTranslation& tr) tr.uds.push_back({a, 0, false, false, -1, 0, 0, 0, source()}); else if (std::sscanf(line.c_str(), "srv %u buf table %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.srvs.size()) tr.srvs.push_back({a, b}); + else if (std::sscanf(line.c_str(), "srv %u buf root %d%n", &i, &a, &used) == 2 && whole() && a >= 0 && + i == tr.srvs.size()) { + tr.srvs.push_back({a, 0}); + tr.srvs.back().root = true; + } else if (std::sscanf(line.c_str(), "srv %u buf heap rootconst %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.srvs.size()) tr.srvs.push_back({a, b, false, true}); @@ -140,13 +163,10 @@ const char* load_compute_translation(ComputeTranslation& tr) tr.srvs.push_back({c, d, false, true, a, b, x, y}); else if (std::sscanf(line.c_str(), "uav %u table %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.uavs.size()) tr.uavs.push_back({a, b}); - else if (std::sscanf(line.c_str(), "uav %u tex2d float table %d %d channels 4%n", &i, &a, &b, &used) == 3 && whole() && - i == tr.uavs.size()) - tr.uavs.push_back({a, b, true}); - else if (std::sscanf(line.c_str(), "uav %u tex2da float table %d %d channels 4%n", &i, &a, &b, &used) == 3 && whole() && - i == tr.uavs.size()) { + else if (std::sscanf(line.c_str(), "uav %u %15s float table %d %d channels 4%n", &i, name, &a, &b, &used) == 4 && whole() && + i == tr.uavs.size() && uav_dimension() != D3D12_UAV_DIMENSION_UNKNOWN) { tr.uavs.push_back({a, b, true}); - tr.uavs.back().array = true; + tr.uavs.back().uav_dimension = uav_dimension(); } else if (std::sscanf(line.c_str(), "srv %u tex2d table %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.srvs.size()) tr.srvs.push_back({a, b, true}); @@ -159,7 +179,7 @@ const char* load_compute_translation(ComputeTranslation& tr) i == tr.samplers.statics.size()) tr.samplers.read_manifest_line(line.c_str()); else return line.rfind("srv", 0) == 0 ? "a resource that is not a raw table buffer or a 2D texture" - : line.rfind("uav", 0) == 0 ? "an output that is not a raw table buffer or a 2D/2D-array float texture" + : line.rfind("uav", 0) == 0 ? "an output that is not a raw table buffer or a 1D/2D/2D-array/3D float texture" : line.rfind("udsrc", 0) == 0 ? "an entry value that is not a root constant or a buffer descriptor word" : line.rfind("smp", 0) == 0 ? "a sampler that is not a plain static one" : "an unknown manifest line"; } @@ -168,7 +188,7 @@ const char* load_compute_translation(ComputeTranslation& tr) for (const ComputeTranslation::Slot& ud : tr.uds) { const auto& slots = ud.source >= ComputeTranslation::output_word3 ? tr.uavs : tr.srvs; if (ud.source != ComputeTranslation::root_constant && - (ud.a < 0 || static_cast(ud.a) >= slots.size() || slots[ud.a].texture)) + (ud.a < 0 || static_cast(ud.a) >= slots.size() || slots[ud.a].texture || slots[ud.a].root)) return "an entry value names a descriptor that is not a buffer input or output"; } x2w_startup::ComPtr code; @@ -244,6 +264,74 @@ bool translate_compute_natively(ComputeTranslation& tr) #endif } +// Resolve a compute root SRV (`srv buf root `) from the guest address recorded by slot 43 for +// to the end of its backing upload allocation or aliased placed buffer (up to the 16 MiB compute raw buffer limit). +IndirectBufferView compute_root_srv_buffer(Wrapper* self, const Pass& pass, int param, std::uint32_t (&words)[8], + const char** why) +{ + const auto refuse = [why](const char* reason) { + if (why) *why = reason; + return IndirectBufferView{}; + }; + if (why) *why = nullptr; + const auto* root_params = pass.compute_root_wrapper ? root_info(pass.compute_root_wrapper) : nullptr; + if (!root_params || param < 0 || static_cast(param) >= root_params->size() || + static_cast(param) >= pass.compute_root_srvs.size() || + (*root_params)[param].type != D3D12_ROOT_PARAMETER_TYPE_SRV) + return refuse("a compute root input is not a shader resource view parameter"); + if (!(pass.compute_root_srv_set & (u64{1} << param))) + return refuse("a compute root SRV was not set since the compute root"); + const u64 address = pass.compute_root_srvs[param]; + words[0] = static_cast(address); + words[1] = static_cast(address >> 32); + if (!address) return refuse("a compute root SRV has a null address"); + if (address % 4) return refuse("a compute root SRV address is not 4-byte aligned"); + constexpr u64 limit = 16u << 20; + if (const auto allocation = list_upload_tail(self, address); allocation.resource) { + if (allocation.offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) + return refuse("a compute root SRV range is not 16-byte aligned in its resource"); + const u64 bytes = (std::min)(allocation.bytes, limit) & ~u64{3}; + if (bytes < 4) + return refuse("a compute root SRV has fewer than 4 aligned bytes in its upload allocation"); + words[2] = static_cast(bytes); + return {allocation.resource, allocation.offset, bytes, 0, true}; + } + Wrapper* device = self->own().list_device; + const auto first = placed_buffer_range(device, address, 4); + if (first.reject) return refuse("a compute root SRV crosses the end of a placed buffer"); + if (!first.owner) return refuse("a compute root SRV is in title memory outside any placed buffer"); + if (!InterlockedCompareExchange(&first.owner->own().refs, 0, 0)) + return refuse("a compute root SRV's resource is released"); + const auto* info = resource_info(first.owner); + if (!info || info->initial_state != D3D12_RESOURCE_STATE_COMMON) + return refuse("a compute root SRV's resource was not created in the common state"); + const u64 base = reinterpret_cast(first.owner->own().title_memory); + if (!base || address < base || address - base >= info->bytes) + return refuse("a compute root SRV range is outside its desktop buffer"); + const u64 offset = address - base; + if (offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) + return refuse("a compute root SRV range is not 16-byte aligned in its resource"); + const u64 bytes = (std::min)(info->bytes - offset, limit) & ~u64{3}; + if (bytes < 4) + return refuse("a compute root SRV has fewer than 4 aligned bytes in its placed buffer"); + const auto placed = placed_buffer_range(device, address, bytes); + if (placed.reject || placed.owner != first.owner) + return refuse("a compute root SRV crosses the end of a placed buffer"); + auto* native = static_cast(placed.owner->own().real); + if (!placed.alias && (!native || !list_copied_gpu_range(self, native, offset, bytes))) + return refuse("a compute root SRV is in a placed buffer that does not alias title memory"); + x2w_startup::ComPtr native_device; + if (!native || FAILED(native->GetDevice(IID_PPV_ARGS(native_device.GetAddressOf()))) || + native_device.Get() != device_of(device)) + return refuse("a compute root SRV's resource is on another device"); + const auto desc = native->GetDesc(); + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || (desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) || + offset > desc.Width || bytes > desc.Width - offset) + return refuse("a compute root SRV range is outside its desktop buffer"); + words[2] = static_cast(bytes); + return {native, offset, bytes, 0, false}; +} + // Both callers have an open list and a slot 67 request. The indirect caller has checked the signature and argument range. const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& dispatch) { @@ -276,7 +364,7 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& reason = "the compute root set is not the one the pipeline was created with"; else if (!ensure_draw_heap(self->own().list_device)) reason = "no descriptor heap on this device"; else { - if (!tr->state || (tr->retry_manifest_at && GetTickCount64() >= tr->retry_manifest_at)) { + if (!tr->state || tr->manifest_retry.due(GetTickCount64())) { // The in-process translation is tried once per key, before a published one. if (tr->state || !translate_compute_natively(*tr)) { tr->unmodelled = load_compute_translation(*tr); @@ -297,12 +385,22 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& for (std::size_t i = 0; i < count && !reason; ++i) { const bool output = i >= inputs; const ComputeTranslation::Slot slot = output ? tr->uavs[i - inputs] : tr->srvs[i]; - if (dispatch.signature && (slot.heap || slot.texture)) { + if (dispatch.signature && (slot.heap || slot.texture || slot.root)) { reason = "translated indirect Dispatch requires fixed-table raw buffers"; break; } std::uint32_t index = slot.a < 0 || slot.b < 0 ? 0 : pass.compute_constants.word(slot.a, slot.b); std::memset(words, 0, sizeof(words)); + if (!output && slot.root) { + const IndirectBufferView view = compute_root_srv_buffer(self, pass, slot.a, words, &reason); + if (reason && !tr->first_refusal) + log("x2w-draw compute %016llx first refused input %zu (root %d), address 0x%llx", key, i, slot.a, + u64{words[0]} | (u64{words[1]} << 32)); + views[i] = {view.resource, view.offset, view.bytes, !view.upload}; + views[i].stride = view.stride; + std::memcpy(views[i].words, words, sizeof(views[i].words)); + continue; + } if (slot.word_param >= 0) { // The index word is read now from the recording's upload memory, where the title wrote it (no GPU command // writes there), at the dword-aligned 32-bit byte offset the program reads it at. @@ -379,9 +477,28 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& const DXGI_FORMAT format = desc.Format ? desc.Format : resource.Format; words[3] = static_cast(format) | static_cast(desc.ViewDimension) << 16; if (!known || record.slot != 19) reason = "an output texture entry is not the token of an unordered access view"; - else if (!created || !texture || !(resource.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) + else if (slot.uav_dimension == D3D12_UAV_DIMENSION_TEXTURE3D && + texture && (resource.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + const auto& view = desc.Texture3D; + if (!described || desc.ViewDimension != slot.uav_dimension || resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) + reason = "an output texture view or resource is not 3D"; + else { + // Slot 19 can retain a rejected range as an unmaterialized view. + reason = volume_uav_range_error(resource, view); + if (!reason && !created) reason = "an output texture view was not created on the desktop"; + } + } else if (slot.uav_dimension == D3D12_UAV_DIMENSION_TEXTURE1D && + texture && (resource.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + // Checked before `created`, as for 3D: slot 19 records a 1D view with an out-of-range mip as refused. + if (!described || desc.ViewDimension != slot.uav_dimension || resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE1D) + reason = "an output texture view or resource is not 1D"; + else if (desc.Texture1D.MipSlice >= resource.MipLevels) + reason = "an output 1D texture mip is outside the resource"; + else if (!created) + reason = "an output texture view was not created on the desktop"; + } else if (!created || !texture || !(resource.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) reason = "an output texture view was not created on the desktop"; - else if (slot.array) { + else if (slot.uav_dimension == D3D12_UAV_DIMENSION_TEXTURE2DARRAY) { // The layer in HLSL is relative to FirstArraySlice: retain the caller's complete view. const auto& a = desc.Texture2DArray; if (!described || desc.ViewDimension != D3D12_UAV_DIMENSION_TEXTURE2DARRAY) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index e1107e281b..d4ed161c58 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -9,12 +9,17 @@ // buffers named by the hardware descriptors in its tables, textures behind view tokens) into an // upload ring / a private descriptor heap. +#include "startup_stubs/typed_uav_load.h" + // A pixel-stage image store (#1996 item F, #2742): tools/startup/gfx2hlsl.py writes 'uav N tex2d|tex2da table P O' // for the RWTexture2D or RWTexture2DArray at u, whose descriptor is at byte O of the title's // root table P. Only that form is read; a view qualifier or a 'channels' field, as in the compute line, is refused. +// A trailing 'typedload' means the binding must also support a typed UAV load. The translator does not emit it +// for a component store, which does not read the texel. struct PixelUav { unsigned index = 0, parameter = 0, offset = 0; bool array = false; + bool needs_typed_load = false; }; constexpr unsigned pixel_uav_limit = 8; @@ -40,9 +45,10 @@ const char* read_pixel_uav_line(const std::string& line, PixelUav& out) if (w.size() > 3 && (w[3] == "float" || w[3] == "uint" || w[3] == "sint")) return "a view qualifier is not read for pixel stores"; if (w.size() < 4 || w[3] != "table") return "view source is not a table"; if (w.size() < 6) return "missing table parameter or offset"; - if (w.size() > 6) return "unexpected field after the table offset"; + if (w.size() > 7 || (w.size() == 7 && w[6] != "typedload")) return "unexpected field after the table offset"; if (!number(w[4], out.parameter) || out.parameter >= 16) return "table parameter out of range"; if (!number(w[5], out.offset)) return "malformed table offset"; + out.needs_typed_load = w.size() == 7; return nullptr; } @@ -91,7 +97,7 @@ bool srgb_uav_format(DXGI_FORMAT format) // for a manifest 'tex2da' view. Returns nullptr and fills out, or the reason the binding is refused. const char* pixel_uav_view(ID3D12Device* device, const D3D12_RESOURCE_DESC& resource, const D3D12_UNORDERED_ACCESS_VIEW_DESC* title_view, bool array, - D3D12_UNORDERED_ACCESS_VIEW_DESC& out) + D3D12_UNORDERED_ACCESS_VIEW_DESC& out, bool needs_typed_load = false) { if (resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return "resource is not a 2D texture"; if (!array && resource.DepthOrArraySize != 1) return "resource is a texture array"; @@ -121,6 +127,17 @@ const char* pixel_uav_view(ID3D12Device* device, const D3D12_RESOURCE_DESC& reso if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &support, sizeof(support))) || !(support.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE)) return "format has no typed UAV store on this device"; + // Before the view is filled, and therefore before the draw. A component store does not set + // needs_typed_load: it never reads the texel. A binding that does is refused when this device + // cannot load the format. + if (needs_typed_load) { + D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; + const bool additional = SUCCEEDED(device->CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options))) && + options.TypedUAVLoadAdditionalFormats; + if (const char* load = typed_uav_load_refusal(format, support.Support2, additional)) + return load; + } out = {}; out.Format = format; if (array) { @@ -137,7 +154,7 @@ struct Translation { enum UdKind { rect, base_vertex, start_instance, root_constant, stride, mrt_bits, d16_unorm16, desc_word3 }; 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. + x2w_startup::ManifestRetry manifest_retry; // Only an absent manifest can become ready on a later draw. std::vector srvs; std::vector uavs; // manifest 'uav N tex2d table P O' (#1996 F): u0.. after the SRVs std::vector uds; @@ -265,18 +282,18 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) std::string manifest; if (!cache_path(path, L"", tr.key, L".txt")) return; if (!read_text(path, manifest)) { - if (!tr.retry_manifest_at) { + if (!tr.manifest_retry.pending()) { InterlockedIncrement(&translation_missing); static LONG missing; if (rtv_request.empty() && first_calls(missing, 12)) log("x2w-draw no translation for pipeline %016llx", tr.key); } - tr.retry_manifest_at = GetTickCount64() + 1000; + tr.manifest_retry.missed(GetTickCount64()); return; } // The writer publishes this marker last. A malformed published result stays rejected. - const bool previously_missing = tr.retry_manifest_at != 0; - tr.retry_manifest_at = 0; + const bool previously_missing = tr.manifest_retry.pending(); + tr.manifest_retry.found(); bool matched_rtv = false; for (std::size_t at = 0; at < manifest.size();) { std::size_t end = manifest.find('\n', at); @@ -371,7 +388,7 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void* { // Keep pre-fix desktop bytecode and manifests out of this ABI's cache. // tools/startup/gfx2hlsl.py hashes the same bytes, without a trailing NUL. - constexpr char revision[] = "x2w-startup-shader-28"; + constexpr char revision[] = "x2w-startup-shader-29"; const u64 seed = fnv_bytes(revision, sizeof(revision) - 1); u64 key = fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(b, b_bytes, fnv_bytes(a, a_bytes, seed))); // A stream's input layout (stream_input_layout) feeds the vertex fetch, so it is part of the key. @@ -492,7 +509,7 @@ u64 publish_compute_request(const void* desc) std::vector fields(sizeof(words)); words[0] = words[1] = words[3] = words[5] = words[7] = words[9] = words[10] = 0; std::memcpy(fields.data(), words, sizeof(words)); - constexpr char compute_revision[] = "x2w-startup-shader-28cs"; // tools/startup/gfx2hlsl.py compute_key + constexpr char compute_revision[] = "x2w-startup-shader-29cs"; // tools/startup/gfx2hlsl.py compute_key u64 key = fnv_bytes(compute_revision, sizeof(compute_revision) - 1); const std::vector* order[] = {&code, &data, &root_blob, &fields, &state_a, &state_b}; for (const auto* part : order) key = fnv_part(*part, key); @@ -896,7 +913,7 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) { if (!base) return nullptr; if (std::none_of(pass.target_formats, pass.target_formats + pass.target_count, needs_rtv_variant)) { - if (base->retry_manifest_at && GetTickCount64() >= base->retry_manifest_at) + if (base->manifest_retry.due(GetTickCount64())) load_translation(*base); return base; } @@ -913,7 +930,7 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) publish_shader_request(key, L".rtv", request.data(), request.size()); log("x2w-draw no RTV translation for %016llx (%s)", key, request.c_str()); } - } else if (entry->retry_manifest_at && GetTickCount64() >= entry->retry_manifest_at) { + } else if (entry->manifest_retry.due(GetTickCount64())) { load_translation(*entry, request); } return entry; @@ -2167,7 +2184,8 @@ bool resolve_pixel_uavs(const Translation& tr, const Pass& pass, PixelUavBinding title_view.Format = desktop_format(title_view.Format); } const D3D12_RESOURCE_DESC desc = texture->GetDesc(); - const char* reason = pixel_uav_view(device_of(the_device), desc, described ? &title_view : nullptr, uav.array, out[i].view); + const char* reason = pixel_uav_view(device_of(the_device), desc, described ? &title_view : nullptr, + uav.array, out[i].view, uav.needs_typed_load); if (reason) { static LONG refused_view; if (first_calls(refused_view, 16)) @@ -2312,6 +2330,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI const bool indices_ok = indexed && !indirect && pass.ib.BufferLocation && readable_window(index_address, index_total) >= index_total; D3D12_INDEX_BUFFER_VIEW live_indices{}; ID3D12Resource* live_index_resource = nullptr; + bool index_read_as_table = false; // live_index_resource is also bound as a table SRV (X2W_D3D12_TABLE_ALIAS) const auto stream_needs_slicing = [&](const Translation::Srv& srv) { if (srv.source != 1) return false; if (srv.a < 0 || srv.a >= 8) return true; @@ -2559,6 +2578,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI strides[i] = (words[1] >> 16) & 0x3fff; bytes = static_cast(strides[i] ? strides[i] : 1) * words[2]; } + const std::size_t view_bytes = bytes; // before the 16 MiB copy cap if (bytes > (16u << 20)) { bytes = 16u << 20; // Formatted loads past the copy would read zeros on the desktop; refuse the draw instead. @@ -2581,6 +2601,31 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI buffer_facts.bound = bound; count_null_binding(x2w_local::classify_null_binding(buffer_facts)); }; + // X2W_D3D12_TABLE_ALIAS=1: a table buffer whose whole range lies in a placed buffer that aliases title memory + // binds that alias, as vertex streams do, instead of a frame copy. The GPU then reads the bytes at execution, + // not as they were when the draw was recorded, and the range is not cut at 16 MiB. + static const bool table_alias = x2w_local::env_on("X2W_D3D12_TABLE_ALIAS"); + // The raw view covers whole DWORDs, so the alias must hold the rounded range. + const std::size_t raw_bytes = (view_bytes + 3) & ~std::size_t{3}; + if (table_alias && srv.source == 0 && !formatted.entry && address && view_bytes && raw_bytes <= (512u << 20)) { + const auto table_placed = placed_buffer_range(self->own().list_device, address, raw_bytes); + if (!table_placed.reject && table_placed.alias && table_placed.owner && + InterlockedCompareExchange(&table_placed.owner->own().refs, 0, 0)) { + const u64 view_offset = address - reinterpret_cast(table_placed.owner->own().title_memory); + if (view_offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT == 0 && + retain_with_recording(self, x2w_startup::ComPtr(table_placed.alias))) { + // The same alias can also be this draw's live index buffer; it then keeps both read states. + const bool shared_index = table_placed.alias == live_index_resource; + index_read_as_table |= shared_index; + require_state(self, table_placed.alias, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | + (shared_index ? D3D12_RESOURCE_STATE_INDEX_BUFFER : D3D12_RESOURCE_STATE_COMMON)); + buffer_view(dest, table_placed.alias, view_offset, raw_bytes); + count_buffer(true); + continue; + } + } + } if (placed.reject || (placed.owner && !InterlockedCompareExchange(&placed.owner->own().refs, 0, 0))) { buffer_view(dest, nullptr, 0, 0); count_buffer(false); @@ -2728,7 +2773,10 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI ID3D12Resource* index_chunk = nullptr; auto view = live_indices; if (live_index_resource) { - require_state(self, live_index_resource, D3D12_RESOURCE_STATE_INDEX_BUFFER); + require_state(self, live_index_resource, D3D12_RESOURCE_STATE_INDEX_BUFFER | + (index_read_as_table ? D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE + : D3D12_RESOURCE_STATE_COMMON)); } else if (indices_ok && frame_copy(self, index_address, index_total, &offset, &index_chunk) && index_chunk) { view = {index_chunk->GetGPUVirtualAddress() + offset, static_cast(index_total), index_bytes == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT}; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 680d176faf..e48560cef1 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -17,10 +17,12 @@ #include "xmem_page_batch.h" #include "startup_stubs/local_log.h" #include "startup_stubs/logical_view_table.h" +#include "startup_stubs/manifest_retry.h" #include "startup_stubs/list_compute_root.h" #include "startup_stubs/overlay_window.h" #include "startup_stubs/draw_bmp.h" #include "startup_stubs/draw_dump_tracking.h" +#include "startup_stubs/present_readback_state.h" #include "startup_stubs/pixel_history.h" #include "startup_stubs/translated_sampler_bindings.h" #include "startup_stubs/export_write_mask.h" @@ -1463,6 +1465,9 @@ std::unordered_map title_allocators; std::unordered_map list_recordings; // list -> allocator holding its recording std::unordered_map> queue_submits; std::vector upload_chunks; // allocator_lock also protects recording holds and queue fence values +// X2W_D3D12_RING_RELEASE_AT_SUBMIT=1 (allocator_lock): chunks each closed list released at a fenced submit, until its Reset. +std::unordered_map released_upload_chunks; +LONG upload_resubmits_refused; // closed lists submitted again after a released chunk was reused; not executed LONG allocator_swaps, allocator_creates; @@ -1470,6 +1475,7 @@ void release_upload_recording(Wrapper* list) { AcquireSRWLockExclusive(&allocator_lock); discard_upload_chunks(list->own().upload_chunks, upload_chunks.data()); + released_upload_chunks.erase(list); ReleaseSRWLockExclusive(&allocator_lock); } @@ -1600,6 +1606,25 @@ x2w_upload::Allocation list_upload_range(Wrapper* self, UINT64 address, UINT64 b ReleaseSRWLockShared(&allocator_lock); return allocation; } +x2w_upload::Allocation list_upload_tail(Wrapper* self, UINT64 address) +{ + x2w_upload::Allocation allocation{}; + AcquireSRWLockShared(&allocator_lock); + const auto& state = self->own(); + if (state.list_open && state.list_uploads) { + for (auto it = state.list_uploads->allocations.rbegin(); it != state.list_uploads->allocations.rend(); ++it) { + if (address < it->cpu) continue; + const UINT64 offset = address - it->cpu; + if (offset < it->bytes) { + allocation = {static_cast(address), it->gpu + offset, it->bytes - offset, it->resource, + it->offset + offset}; + break; + } + } + } + ReleaseSRWLockShared(&allocator_lock); + return allocation; +} UINT64 list_upload_gpu(Wrapper* self, UINT64 address, UINT64 bytes) { return list_upload_range(self, address, bytes).gpu; } // Fixture lookup. The full range must belong to this list's open recording. @@ -1661,6 +1686,34 @@ bool submit_fence_fails() return on; } +// X2W_D3D12_RING_RELEASE_AT_SUBMIT=1 (opt-in): a closed list stops holding its upload ring chunks once its submit is +// fenced, so the queue fence alone guards them; the ring then grows in 16 MiB chunks up to 512 MiB. A later submit +// of the same list before its Reset fences its chunks again. One whose chunk was reused meanwhile is refused before +// ExecuteCommandLists (released_chunks_recycled), so it never reads replaced bytes. +bool ring_release_at_submit() +{ + static const bool on = GetEnvironmentVariableW(L"X2W_D3D12_RING_RELEASE_AT_SUBMIT", nullptr, 0) != 0; + return on; +} + +// draw_lock and allocator_lock held, before the queue executes `list`. True when the closed list released its chunks +// at an earlier fenced submit and one of them was reused since: the submit leaves it out, and it stays refused until +// its Reset. Counted and logged. +bool released_chunks_recycled(Wrapper* list) +{ + const auto released = released_upload_chunks.find(list); + if (released == released_upload_chunks.end()) return false; + UploadChunkMask recycled = 0; + resubmitted_upload_chunks(released->second, upload_chunks.data(), recycled); + if (!recycled) return false; + InterlockedIncrement(&upload_resubmits_refused); + static LONG logged; + if (first_calls(logged, 8)) + log("x2w-draw upload ring: closed list %p submitted again after its released chunks 0x%x were reused; " + "refused, it is not executed", static_cast(list), static_cast(recycled)); + return true; +} + // draw_lock and allocator_lock held, after the lists were executed on queue. Each list's allocator holds a fence value // the queue must pass before the allocator can be reset. If that fence cannot be created or // signalled, the work is on the GPU all the same: the allocators are marked untracked instead. @@ -1677,10 +1730,28 @@ void note_submits(ID3D12CommandQueue* queue, const std::vector& lists) } } UploadChunkMask chunks = 0; - for (auto* list : lists) chunks |= list->own().upload_chunks; + for (auto* list : lists) { + chunks |= list->own().upload_chunks; + const auto released = released_upload_chunks.find(list); + if (released == released_upload_chunks.end()) continue; + // A list with a reused chunk was refused before the execute, under the same locks: all of them are intact. + UploadChunkMask reused = 0; + chunks |= resubmitted_upload_chunks(released->second, upload_chunks.data(), reused); + } const bool signaled = fence && SUCCEEDED(queue->Signal(fence, value + 1)); if (signaled) ++value; submit.submitted(chunks, signaled); + if (signaled && ring_release_at_submit()) { + for (Wrapper* list : lists) { + if (!list->own().upload_chunks) continue; + try { + release_upload_chunks_at_submit(list->own().upload_chunks, upload_chunks.data(), + released_upload_chunks[list]); + } catch (const std::bad_alloc&) { + // Keep the holds: the list then pins its chunks until its Reset, as without the switch. + } + } + } if (signaled) { for (Wrapper* list : lists) { const auto found = list_recordings.find(list); @@ -1815,6 +1886,7 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator) on = title.current; ++on->lists; discard_upload_chunks(state.upload_chunks, upload_chunks.data()); + released_upload_chunks.erase(self); state.list_uploads = nullptr; state.list_scratch = nullptr; state.list_ready = false; @@ -1903,6 +1975,92 @@ void complete_when_reached(Wrapper* fence, UINT64 value) SetThreadpoolWait(wait, pending->event, nullptr); } +// The queued diagnostic readback's ownership: the submitted surface and queue references, the +// recording objects and the completion state, module-lifetime storage guarded by a mutex the +// sampling path and the drain below serialize through. The sample's wait event is created lazily +// with the recording, not at module load. +struct PresentedReadback { + std::mutex mutex; + x2w_startup::PresentReadbackState completion; + ID3D12CommandAllocator* allocator = nullptr; + ID3D12GraphicsCommandList* list = nullptr; + ID3D12Fence* fence = nullptr; + ID3D12Resource* readback = nullptr; + UINT64 readback_bytes = 0, fence_value = 0; + ID3D12Resource* submitted_surface = nullptr; + ID3D12CommandQueue* submitted_queue = nullptr; + HANDLE wait_event = nullptr; +} presented_readback; + +// Releases the ownership a completed submission held (exactly once, through retire); the caller +// must hold the mutex and have seen a completed observation. +void release_readback_ownership() +{ + presented_readback.submitted_surface->Release(); + presented_readback.submitted_queue->Release(); + presented_readback.submitted_surface = nullptr; + presented_readback.submitted_queue = nullptr; +} + +// Hold the fence and shim module until the asynchronous callback returns. +struct PendingDrain { + ID3D12Fence* fence; + std::uint64_t value; + HANDLE event; + HMODULE module; +}; + +// Retire only the registered submission; never publish a late diagnostic image. +void CALLBACK readback_drained(PTP_CALLBACK_INSTANCE instance, void* context, PTP_WAIT wait, TP_WAIT_RESULT) +{ + std::unique_ptr pending{static_cast(context)}; + CloseThreadpoolWait(wait); + { + const std::lock_guard lock(presented_readback.mutex); + if (presented_readback.fence == pending->fence) + presented_readback.completion.retire(pending->fence->GetCompletedValue(), release_readback_ownership, + pending->value); + } + pending->fence->Release(); + CloseHandle(pending->event); + FreeLibraryWhenCallbackReturns(instance, pending->module); +} + +// Caller holds the readback mutex. On registration failure, retain ownership. +void drain_readback_when_complete() +{ + HMODULE module = nullptr; + if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, reinterpret_cast(&presented_readback), + &module)) { + log("x2w-render readback drain unavailable: no shim module reference"); + return; + } + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + auto* pending = event ? new (std::nothrow) PendingDrain{presented_readback.fence, presented_readback.fence_value, + event, module} + : nullptr; + PTP_WAIT wait = pending ? CreateThreadpoolWait(&readback_drained, pending, nullptr) : nullptr; + if (!pending || !wait) { + if (event) CloseHandle(event); + delete pending; + if (wait) CloseThreadpoolWait(wait); + FreeLibrary(module); + log("x2w-render readback drain unavailable: event, wait or context allocation failed"); + return; + } + presented_readback.fence->AddRef(); + const HRESULT hr = presented_readback.fence->SetEventOnCompletion(pending->value, pending->event); + if (FAILED(hr)) { + presented_readback.fence->Release(); + delete pending; + CloseHandle(event); + CloseThreadpoolWait(wait); + FreeLibrary(module); + log("x2w-render readback drain registration failed 0x%08lx", static_cast(hr)); + return; + } + SetThreadpoolWait(wait, pending->event, nullptr); +} // The presented surface, read back and reduced for the window (BGRA, top-down). constexpr int shown_width = 960, shown_height = 540; std::vector shown_pixels; @@ -1927,12 +2085,38 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface, int static LONG raw_failures; if (first_calls(raw_failures, 4)) log("x2w-render raw plane %d (not composited): %s", raw_plane, failure); }; - static ID3D12CommandAllocator* allocator; - static ID3D12GraphicsCommandList* list; - static ID3D12Fence* fence; - static ID3D12Resource* readback; - static UINT64 readback_bytes, fence_value; - static HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const std::lock_guard lock(presented_readback.mutex); + auto& completion = presented_readback.completion; + auto& allocator = presented_readback.allocator; + auto& list = presented_readback.list; + auto& fence = presented_readback.fence; + auto& readback = presented_readback.readback; + auto& readback_bytes = presented_readback.readback_bytes; + auto& fence_value = presented_readback.fence_value; + auto& submitted_surface = presented_readback.submitted_surface; + auto& submitted_queue = presented_readback.submitted_queue; + HANDLE& event = presented_readback.wait_event; + const auto discard_recording = [&] { + if (list) { list->Release(); list = nullptr; } + if (allocator) { allocator->Release(); allocator = nullptr; } + if (fence) { fence->Release(); fence = nullptr; } + fence_value = 0; + }; + if (completion.unusable()) { + std::snprintf(failure, sizeof(failure), "readback unavailable after fence failure"); + report_failure(); + return; + } + if (completion.pending()) { + const auto state = completion.retire(fence->GetCompletedValue(), release_readback_ownership); + if (state != x2w_startup::FenceCompletion::completed) { + std::snprintf(failure, sizeof(failure), "%s", + state == x2w_startup::FenceCompletion::removed ? + "readback fence reported device removal" : "previous readback still in flight"); + report_failure(); + return; + } + } ID3D12Device* device = device_of(the_device); const D3D12_RESOURCE_DESC desc = surface->GetDesc(); D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; @@ -1973,6 +2157,7 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface, int if (SUCCEEDED(hr)) hr = allocator->Reset(); if (SUCCEEDED(hr)) hr = list->Reset(allocator, nullptr); if (FAILED(hr)) { + discard_recording(); std::snprintf(failure, sizeof(failure), "readback setup failed 0x%08lx", static_cast(hr)); report_failure(); return; @@ -1986,19 +2171,71 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface, int to.PlacedFootprint = footprint; list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); transition(list, surface, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); - list->Close(); + hr = list->Close(); + if (FAILED(hr)) { + discard_recording(); + std::snprintf(failure, sizeof(failure), "readback close failed 0x%08lx", static_cast(hr)); + report_failure(); + return; + } + // The sample's wait event is created with the first submission that needs it, not at load. + if (!event) event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (fence_value == UINT64_MAX - 1 || !event || !ResetEvent(event)) { + std::snprintf(failure, sizeof(failure), "readback fence or event unavailable"); + report_failure(); + return; + } + // ExecuteCommandLists does not retain the resources referenced by recorded commands. + surface->AddRef(); + queue->AddRef(); + submitted_surface = surface; + submitted_queue = queue; ID3D12CommandList* lists[] = {list}; queue->ExecuteCommandLists(1, lists); - queue->Signal(fence, ++fence_value); - fence->SetEventOnCompletion(fence_value, event); + hr = queue->Signal(fence, ++fence_value); + if (FAILED(hr)) { + completion.signal_failed(); + std::snprintf(failure, sizeof(failure), "readback fence signal failed 0x%08lx", static_cast(hr)); + report_failure(); + return; + } + completion.submitted(fence_value); + hr = fence->SetEventOnCompletion(fence_value, event); + if (FAILED(hr)) { + // The submission is signalled but the sample's own event registration failed. Hand it to + // the drain (which registers its own event) instead of keeping the ownership unbounded. + drain_readback_when_complete(); + std::snprintf(failure, sizeof(failure), "readback completion event failed 0x%08lx", static_cast(hr)); + report_failure(); + return; + } if (WaitForSingleObject(event, 3000) != WAIT_OBJECT_0) { + // The fence has not reported completion to the sample. Hand the submission to the drain, + // which retires its ownership once the fence completes and publishes no pixels. + drain_readback_when_complete(); std::snprintf(failure, sizeof(failure), "readback timed out"); report_failure(); return; } + const auto completed = completion.retire(fence->GetCompletedValue(), release_readback_ownership); + if (completed != x2w_startup::FenceCompletion::completed) { + // A removed device cannot confirm completion: keep the ownership and disable reuse. A + // still-pending fence after the event was reported is drained rather than released. + if (completed == x2w_startup::FenceCompletion::pending) drain_readback_when_complete(); + std::snprintf(failure, sizeof(failure), "%s", + completed == x2w_startup::FenceCompletion::removed ? + "readback fence reported device removal" : "readback fence incomplete after wait"); + report_failure(); + return; + } void* mapped = nullptr; const D3D12_RANGE range{0, static_cast(total)}; - if (FAILED(readback->Map(0, &range, &mapped))) return; + hr = readback->Map(0, &range, &mapped); + if (FAILED(hr) || !mapped) { + std::snprintf(failure, sizeof(failure), "readback map failed 0x%08lx", static_cast(hr)); + report_failure(); + return; + } if (!raw) { AcquireSRWLockExclusive(&shown_lock); shown_pixels.resize(shown_width * shown_height); @@ -2439,7 +2676,8 @@ ID3D12PipelineState* build_stream_pipeline(const D3D12_PIPELINE_STATE_STREAM_DES // Transient guest data is copied into mapped upload chunks. Chunks grow from // 16 MiB up to 256 MiB in total and stay alive for the process. A full chunk can be reused once -// no recording can submit its bytes and every queue that used it has finished. +// no recording can submit its bytes and every queue that used it has finished. With +// X2W_D3D12_RING_RELEASE_AT_SUBMIT=1 every chunk is 16 MiB, up to 512 MiB, and a fenced submit releases its lists. UploadReservation reserve_upload_ring(Wrapper* list, std::size_t bytes) { @@ -2464,9 +2702,11 @@ UploadReservation reserve_upload_ring(Wrapper* list, std::size_t bytes) if (reservation.mapped) return finish(active); } - const u64 remaining = total_bytes < max_upload_ring_bytes ? max_upload_ring_bytes - total_bytes : 0; + const bool release_at_submit = ring_release_at_submit(); + const u64 ring_bytes = release_at_submit ? max_released_upload_ring_bytes : max_upload_ring_bytes; + const u64 remaining = total_bytes < ring_bytes ? ring_bytes - total_bytes : 0; if (rounded <= remaining) { - u64 chunk_bytes = chunks.empty() ? initial_upload_chunk_bytes : chunks.back().capacity * 2; + u64 chunk_bytes = chunks.empty() || release_at_submit ? initial_upload_chunk_bytes : chunks.back().capacity * 2; if (chunk_bytes < rounded) chunk_bytes = rounded; if (chunk_bytes > remaining) chunk_bytes = remaining; auto* device = the_device ? device_of(the_device) : nullptr; @@ -2605,6 +2845,8 @@ struct Pass { std::uint32_t constants[16][8] = {}; unsigned char constant_words_bound[16] = {}; x2w_root_constants::Store compute_constants; // compute root constants (slots 37 and 39) + std::array compute_root_srvs{}; // title address of each compute root SRV (slot 43) + u64 compute_root_srv_set = 0; // bit per compute root parameter set by slot 43 since slot 33 / Reset Wrapper* compute_root_wrapper = nullptr; // compute root signature last set by slot 33 D3D12_VERTEX_BUFFER_VIEW vb[8] = {}; PlacedVertexView placed_vb[8] = {}; @@ -2734,6 +2976,8 @@ void retire_drop_recording(Wrapper* list) void reset_list_dynamic_state(Wrapper* self) { if (!self->own().pass) return; + pass_of(self).compute_root_srvs.fill(0); + pass_of(self).compute_root_srv_set = 0; pass_of(self).stencil_reference = 0; pass_of(self).viewport_set = false; pass_of(self).scissor_set = false; @@ -2841,7 +3085,11 @@ void __stdcall list_compute_root(Wrapper* self, void* root) Wrapper* w = as_wrapper(root); Pass& pass = pass_of(self); // A different root signature invalidates the title's cached compute root arguments. - if (pass.compute_root_wrapper != w) pass.compute_constants.clear(); + if (pass.compute_root_wrapper != w) { + pass.compute_constants.clear(); + pass.compute_root_srvs.fill(0); + pass.compute_root_srv_set = 0; + } pass.compute_root_wrapper = w; const bool real = w && w->own().kind == root_signature_kind && w->own().real && !root_heap_flags(w); pass.compute_root = real ? static_cast(w->own().real) : nullptr; @@ -3868,6 +4116,10 @@ void __stdcall list_compute_upload_srv(Wrapper* self, UINT parameter, UINT64 add { auto* list = recording(self); auto& pass = pass_of(self); + if (list && pass.compute_root_wrapper && parameter < pass.compute_root_srvs.size()) { + pass.compute_root_srvs[parameter] = address; + pass.compute_root_srv_set |= u64{1} << parameter; + } const auto* params = pass.compute_params; if (!list || !params || parameter >= params->size() || parameter >= pass.desktop_compute_upload_srvs.size() || (*params)[parameter].type != D3D12_ROOT_PARAMETER_TYPE_SRV) return; @@ -4065,6 +4317,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) for (UINT i = 0; i < count; ++i) { Wrapper* w = as_wrapper(lists[i]); if (w && w->own().kind == list_kind && w->own().list_ready) { + if (released_chunks_recycled(w)) continue; // its upload bytes were replaced: it is not executed ready.push_back(static_cast(w->own().real)); submitted.push_back(w); } @@ -4547,14 +4800,14 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) }; const char* skip = nullptr; bool default_view = false; - bool uav_denied = false; // a UAV of a resource without unordered access: recorded as not created, as before #2649 + bool record_refused_uav = false; if (N == 17) skip = "constant buffer view (title GPU address)"; if (N >= 18 && N <= 21 && args[0]) { const UINT flags = reinterpret_cast(args[0])->GetDesc().Flags; if (N == 18 && (flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) skip = "resource denies shader resource views"; if (N == 19 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { skip = "resource lacks unordered access"; - uav_denied = true; + record_refused_uav = true; } if (N == 20 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) skip = "resource lacks render target"; if (N == 21 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) skip = "resource lacks depth stencil"; @@ -4589,6 +4842,20 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) if (first_calls(mismatched, 6)) log("x2w-d3d12 Device::slot%d view dimension %u needs resource dimension %u, resource has %u", N, view_dimension, x2w_view_dimension::needed(N, view_dimension), dimension); + } else if constexpr (N == 19) { + if (view_dimension == D3D12_UAV_DIMENSION_TEXTURE3D && + x2w_local::readable(reinterpret_cast(described), sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC))) { + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + std::memcpy(&view, reinterpret_cast(described), sizeof(view)); + skip = volume_uav_range_error(resource_desc, view.Texture3D); + record_refused_uav = skip != nullptr; + } else if (view_dimension == D3D12_UAV_DIMENSION_TEXTURE1D && + x2w_local::readable(reinterpret_cast(described), sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC))) { + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + std::memcpy(&view, reinterpret_cast(described), sizeof(view)); + if (view.Texture1D.MipSlice >= resource_desc.MipLevels) skip = "an output 1D texture mip is outside the resource"; + record_refused_uav = skip != nullptr; + } } } } @@ -4607,7 +4874,7 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) } else if constexpr (N == 19) { // A translated compute Dispatch tells this refusal from a descriptor that holds no view by the record. // A refused creation leaves a descriptor that still holds a live view as it is. - if (uav_denied && !descriptor_has_live_view(args[D], title_dest)) record_view(false); + if (record_refused_uav && !descriptor_has_live_view(args[D], title_dest)) record_view(false); } }; if (skip) { diff --git a/src/startup_stubs/draw_dump_tracking.h b/src/startup_stubs/draw_dump_tracking.h index e2ecdc624d..488537d837 100644 --- a/src/startup_stubs/draw_dump_tracking.h +++ b/src/startup_stubs/draw_dump_tracking.h @@ -4,6 +4,7 @@ #include #include "startup_stubs/d3d12_teardown.h" +#include "startup_stubs/fence_completion.h" #include #include @@ -123,13 +124,12 @@ class DrawReadbacks { std::vector complete; std::lock_guard lock(mutex_); for (auto it = entries_.begin(); it != entries_.end();) { - const UINT64 value = it->fence ? it->fence->GetCompletedValue() : 0; - if (!value) { + const auto state = fence_completion(it->fence ? it->fence->GetCompletedValue() : 0, 1); + if (state == FenceCompletion::pending) { ++it; continue; } - // D3D12 reports UINT64_MAX for device removal, including during a wait. - if (value != UINT64_MAX) { + if (state == FenceCompletion::completed) { complete.push_back(std::move(it->dump)); ++consumed_; } diff --git a/src/startup_stubs/fence_completion.h b/src/startup_stubs/fence_completion.h new file mode 100644 index 0000000000..b13fc53151 --- /dev/null +++ b/src/startup_stubs/fence_completion.h @@ -0,0 +1,16 @@ +#pragma once + +#include + +namespace x2w_startup { + +enum class FenceCompletion { pending, completed, removed }; + +constexpr FenceCompletion fence_completion(std::uint64_t observed, std::uint64_t target) noexcept +{ + // D3D12 returns UINT64_MAX on device removal, not successful completion. + if (observed == UINT64_MAX) return FenceCompletion::removed; + return observed >= target ? FenceCompletion::completed : FenceCompletion::pending; +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/manifest_retry.h b/src/startup_stubs/manifest_retry.h new file mode 100644 index 0000000000..71d2824e49 --- /dev/null +++ b/src/startup_stubs/manifest_retry.h @@ -0,0 +1,43 @@ +// When to look again for a shader cache manifest (.txt) that was absent. +// +// The graphics and compute translation paths look for a missing manifest again on a later draw or Dispatch, because +// the translator (run.ps1 -Translate) can publish it while the title runs. Each look opens a file in the shader cache +// while the caller holds draw_lock, which every draw and Dispatch takes. With a fixed 1 s retry, many keys that +// never get a translation each cost one file open per second, and every other list call waits on that lock. +// +// The wait starts at 1 s after the first miss and doubles with each further miss up to 32 s. A translation published +// during the run is still found, within 32 s at the latest; a key that is never translated costs one look every 32 s. +#pragma once + +#include + +namespace x2w_startup { + +constexpr ULONGLONG manifest_retry_first_ms = 1000; +constexpr unsigned manifest_retry_max_doublings = 5; // 1 s, 2 s, 4 s, 8 s, 16 s, then 32 s + +// The wait after the (misses + 1)-th miss in a row. +constexpr ULONGLONG manifest_retry_delay_ms(unsigned misses) noexcept +{ + return manifest_retry_first_ms << (misses < manifest_retry_max_doublings ? misses : manifest_retry_max_doublings); +} + +struct ManifestRetry { + ULONGLONG at = 0; // GetTickCount64 value of the next look, 0 when none is pending + unsigned misses = 0; // misses in a row since the manifest was last found + + bool pending() const noexcept { return at != 0; } + bool due(ULONGLONG now) const noexcept { return at != 0 && now >= at; } + void missed(ULONGLONG now) noexcept + { + at = now + manifest_retry_delay_ms(misses); + if (misses < manifest_retry_max_doublings) ++misses; + } + void found() noexcept + { + at = 0; + misses = 0; + } +}; + +} // namespace x2w_startup diff --git a/src/startup_stubs/present_readback_state.h b/src/startup_stubs/present_readback_state.h new file mode 100644 index 0000000000..1a333504df --- /dev/null +++ b/src/startup_stubs/present_readback_state.h @@ -0,0 +1,41 @@ +#pragma once + +#include "startup_stubs/fence_completion.h" + +namespace x2w_startup { + +class PresentReadbackState { + std::uint64_t target_ = 0; + bool unusable_ = false; + + FenceCompletion classify(std::uint64_t observed) const noexcept + { + if (unusable_) return target_ ? FenceCompletion::removed : FenceCompletion::pending; + return fence_completion(observed, target_); + } + +public: + void submitted(std::uint64_t target) noexcept { target_ = target; } + void signal_failed() noexcept { unusable_ = true; } + bool pending() const noexcept { return target_ != 0; } + bool unusable() const noexcept { return unusable_; } + FenceCompletion observe(std::uint64_t observed) noexcept + { + const auto state = classify(observed); + if (state == FenceCompletion::removed) unusable_ = true; + if (state == FenceCompletion::completed) target_ = 0; + return state; + } + // A stale drain may observe the fence but must not settle another submission. + template + FenceCompletion retire(std::uint64_t observed, Release&& release, std::uint64_t expected = 0) + { + if (expected && expected != target_) return classify(observed); + const bool held = pending(); + const auto state = observe(observed); + if (state == FenceCompletion::completed && held) release(); + return state; + } +}; + +} // namespace x2w_startup diff --git a/src/startup_stubs/present_signature_sampler.h b/src/startup_stubs/present_signature_sampler.h index a9af26f9f5..c3c3dbce2b 100644 --- a/src/startup_stubs/present_signature_sampler.h +++ b/src/startup_stubs/present_signature_sampler.h @@ -10,7 +10,9 @@ // presented surface right after the present. The sampler therefore holds its own reference to the // surface from submission until the copy's fence has passed. If Signal fails after the list was // submitted, nothing can tell when the copy ends: the sampler stops sampling and keeps the surface, -// allocator, list and readback buffer referenced for the rest of the process ("stranded"). +// allocator, list and readback buffer referenced for the rest of the process ("stranded"). A removed +// device (the fence reports UINT64_MAX) is the same case, never a completion: no readback is mapped, +// no sample is published, and the source stays held. // // Sampling is opt-in: a sampler made with always = false records copies only while the block's // sampling_wanted is set (a script with a picture wait asks for it); otherwise it creates no GPU @@ -18,6 +20,8 @@ #pragma once #include "resource_budget.h" +#include "startup_stubs/fence_completion.h" + #include "startup_stubs/present_signature.h" #include "startup_stubs/present_view_format.h" @@ -47,33 +51,52 @@ class Sampler { explicit Sampler(int every, bool always = true, bool capture_center = false) : capture_center_(capture_center), every_(every), always_(always) {} - // Called once per present with the presented surface. Returns true when this call published a sample. + // Called once per present with the presented surface. Returns true when this call published a + // sample. A removed fence (device removal reports UINT64_MAX) never counts as completion: the + // readback is not mapped, nothing is published, and the copy's source stays held. bool present(ID3D12Device* device, ID3D12CommandQueue* queue, ID3D12Resource* surface, LONG64 present_number, Block* block) { bool published = false; - if (in_flight_ && fence_->GetCompletedValue() >= fence_value_) { - in_flight_ = false; - if (capture_center_) { - last_present_ = copied_present_; - last_format_ = format_; - last_surface_ = source_; - } - retire_source(); - void* mapped = nullptr; - const D3D12_RANGE range{0, static_cast(row_stride_ * rows_)}; - if (SUCCEEDED(readback_->Map(0, &range, &mapped))) { - const auto* base = static_cast(mapped); - if (capture_center_) - std::memcpy(last_rgba_, base + row_stride_ * (cells_y / 2) + (width_ / 2) * 4, 4); - std::uint8_t luma[cells]; - for (int band = 0; band < cells_y; ++band) reduce_row(base + row_stride_ * band, width_, layout_, luma + band * cells_x); - if (rows_ > cells_y) - for (int band = 0; band < fine_y; ++band) - reduce_row(base + row_stride_ * (cells_y + band), width_, layout_, fine_ + band * fine_x, fine_x); - const D3D12_RANGE none{0, 0}; - readback_->Unmap(0, &none); - if (block) publish(block, luma, copied_present_, rows_ > cells_y ? fine_ : nullptr); - published = true; + if (in_flight_) { + // One observation per present decision: device removal (UINT64_MAX) is never a + // completion, exactly like a failed Signal. + switch (x2w_startup::fence_completion(fence_->GetCompletedValue(), fence_value_)) { + case x2w_startup::FenceCompletion::completed: + in_flight_ = false; + if (capture_center_) { + last_present_ = copied_present_; + last_format_ = format_; + last_surface_ = source_; + } + retire_source(); + { + void* mapped = nullptr; + const D3D12_RANGE range{0, static_cast(row_stride_ * rows_)}; + if (SUCCEEDED(readback_->Map(0, &range, &mapped))) { + const auto* base = static_cast(mapped); + if (capture_center_) + std::memcpy(last_rgba_, base + row_stride_ * (cells_y / 2) + (width_ / 2) * 4, 4); + std::uint8_t luma[cells]; + for (int band = 0; band < cells_y; ++band) reduce_row(base + row_stride_ * band, width_, layout_, luma + band * cells_x); + if (rows_ > cells_y) + for (int band = 0; band < fine_y; ++band) + reduce_row(base + row_stride_ * (cells_y + band), width_, layout_, fine_ + band * fine_x, fine_x); + const D3D12_RANGE none{0, 0}; + readback_->Unmap(0, &none); + if (block) publish(block, luma, copied_present_, rows_ > cells_y ? fine_ : nullptr); + published = true; + } + } + break; + case x2w_startup::FenceCompletion::removed: + // Device removal: the copy's end cannot be seen. Publish nothing (the readback + // is stale) and keep the prior historical sample state as it is, as a failed + // Signal does: stranded, so the destructor retains every object the copy uses. + in_flight_ = false; + stranded_ = failed_ = true; + break; + case x2w_startup::FenceCompletion::pending: + break; } } if (block) note_present(block, present_number); @@ -149,14 +172,22 @@ class Sampler { // Waits (at most 10 s) for a copy in flight; if it cannot be seen to end, or the sampler is // stranded, the objects the copy uses stay referenced instead of being released under the GPU. + // A removed fence never counts as completion: the source is kept, and nothing is mapped. ~Sampler() { - if (in_flight_ && !stranded_ && fence_->GetCompletedValue() < fence_value_) { + if (in_flight_ && !stranded_ && + x2w_startup::fence_completion(fence_->GetCompletedValue(), fence_value_) == x2w_startup::FenceCompletion::pending) { HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); if (event && SUCCEEDED(fence_->SetEventOnCompletion(fence_value_, event))) WaitForSingleObject(event, 10000); if (event) CloseHandle(event); } - if (stranded_ || (in_flight_ && fence_->GetCompletedValue() < fence_value_)) return; + // Re-observe after the wait: a copy that completed while it ran releases normally, but + // the removal sentinel never becomes completion, so a fence that reports it (or never + // reached its value in 10 s) keeps every object the copy uses. + if (stranded_ || (in_flight_ && + x2w_startup::fence_completion(fence_->GetCompletedValue(), fence_value_) != + x2w_startup::FenceCompletion::completed)) + return; retire_source(); for (IUnknown* object : {static_cast(readback_), static_cast(fence_), static_cast(list_), static_cast(allocator_)}) diff --git a/src/startup_stubs/typed_uav_load.h b/src/startup_stubs/typed_uav_load.h new file mode 100644 index 0000000000..c3bab6bc76 --- /dev/null +++ b/src/startup_stubs/typed_uav_load.h @@ -0,0 +1,14 @@ +#pragma once +#include + +// A typed UAV load of `format` is available when Support2 has UAV_TYPED_LOAD. +// R32_FLOAT, R32_UINT and R32_SINT do not need TypedUAVLoadAdditionalFormats. +// Every other format does. Returns the refusal reason, or nullptr when a load may proceed. +inline const char* typed_uav_load_refusal(DXGI_FORMAT format, unsigned support2, bool additional_formats) +{ + const bool core = format == DXGI_FORMAT_R32_FLOAT || format == DXGI_FORMAT_R32_UINT || + format == DXGI_FORMAT_R32_SINT; + if ((support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD) != 0 && (core || additional_formats)) + return nullptr; + return "format has no typed UAV load on this device"; +} diff --git a/src/startup_stubs/upload_reservation.h b/src/startup_stubs/upload_reservation.h index 57bf321a59..eec33a9d33 100644 --- a/src/startup_stubs/upload_reservation.h +++ b/src/startup_stubs/upload_reservation.h @@ -7,8 +7,10 @@ struct ID3D12Resource; inline constexpr std::uint64_t initial_upload_chunk_bytes = 16ull << 20; inline constexpr std::uint64_t max_upload_ring_bytes = 256ull << 20; +// X2W_D3D12_RING_RELEASE_AT_SUBMIT=1: chunks of the initial size, up to this total. +inline constexpr std::uint64_t max_released_upload_ring_bytes = 512ull << 20; // Each allocation except possibly the final remainder is at least the initial size. -inline constexpr unsigned max_upload_chunks = max_upload_ring_bytes / initial_upload_chunk_bytes; +inline constexpr unsigned max_upload_chunks = max_released_upload_ring_bytes / initial_upload_chunk_bytes; using UploadChunkMask = std::uint32_t; static_assert(max_upload_chunks <= 32); @@ -60,6 +62,41 @@ inline void discard_upload_chunks(UploadChunkMask& recording, UploadRingChunk* c if (recording & 1) --chunks[i].recordings; } +// X2W_D3D12_RING_RELEASE_AT_SUBMIT=1: the chunks a closed list stopped holding when its submit was fenced, and +// each chunk's generation at that moment. The queue fence keeps those chunks from reuse until the GPU passes it. +struct ReleasedUploadChunks { + UploadChunkMask chunks = 0; + std::array generation{}; +}; + +// Caller holds the lock, after the queue recorded a signalled fence for the recording's chunks. +inline void release_upload_chunks_at_submit(UploadChunkMask& recording, UploadRingChunk* chunks, + ReleasedUploadChunks& released) +{ + for (unsigned i = 0; recording; ++i, recording >>= 1) { + if (!(recording & 1)) continue; + released.chunks |= UploadChunkMask{1} << i; + released.generation[i] = chunks[i].generation; + --chunks[i].recordings; + } +} + +// Caller holds the lock. A closed list submitted again before its Reset still reads the bytes it reserved: returns +// the released chunks that were not reused since, which the new submit must fence again, and sets `recycled` to +// those that were. +inline UploadChunkMask resubmitted_upload_chunks(const ReleasedUploadChunks& released, const UploadRingChunk* chunks, + UploadChunkMask& recycled) +{ + UploadChunkMask intact = 0; + recycled = 0; + for (unsigned i = 0; i < max_upload_chunks; ++i) { + const auto bit = UploadChunkMask{1} << i; + if (!(released.chunks & bit)) continue; + (chunks[i].generation == released.generation[i] ? intact : recycled) |= bit; + } + return intact; +} + struct UploadReservation { unsigned char* mapped = nullptr; std::uint64_t offset = 0; diff --git a/tests/checks/pixel-binary/pixel_image_store.txt b/tests/checks/pixel-binary/pixel_image_store.txt new file mode 100644 index 0000000000..3b2f6c6523 --- /dev/null +++ b/tests/checks/pixel-binary/pixel_image_store.txt @@ -0,0 +1 @@ +tests/startup_pixel_image_store_check.py binary llvm-mc-15 diff --git a/tests/checks/pixel-binary/startup_gfx2hlsl_image_store_3d1d.txt b/tests/checks/pixel-binary/startup_gfx2hlsl_image_store_3d1d.txt new file mode 100644 index 0000000000..195cfc4b28 --- /dev/null +++ b/tests/checks/pixel-binary/startup_gfx2hlsl_image_store_3d1d.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_image_store_3d1d_check.py --llvm-mc llvm-mc-15 diff --git a/tests/checks/pixel-binary/startup_image_sample_l_join.txt b/tests/checks/pixel-binary/startup_image_sample_l_join.txt new file mode 100644 index 0000000000..a0c9ab69c3 --- /dev/null +++ b/tests/checks/pixel-binary/startup_image_sample_l_join.txt @@ -0,0 +1 @@ +tests/startup_image_sample_l_join_check.py binary llvm-mc-15 diff --git a/tests/checks/python-linux/bvh_node_model.txt b/tests/checks/python-linux/bvh_node_model.txt new file mode 100644 index 0000000000..4eff1e650c --- /dev/null +++ b/tests/checks/python-linux/bvh_node_model.txt @@ -0,0 +1,2 @@ +# Pure-Python witness set for the console BVH node formats (no GPU, no LLVM). +tests/gfx1030_bvh_box/check.py --model-only diff --git a/tests/checks/python-linux/pixel_image_store.txt b/tests/checks/python-linux/pixel_image_store.txt new file mode 100644 index 0000000000..2e7a8b4229 --- /dev/null +++ b/tests/checks/python-linux/pixel_image_store.txt @@ -0,0 +1 @@ +tests/startup_pixel_image_store_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_bvh.txt b/tests/checks/python-linux/startup_gfx2hlsl_bvh.txt new file mode 100644 index 0000000000..26480c9d8e --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_bvh.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_bvh_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_cselect_descnum.txt b/tests/checks/python-linux/startup_gfx2hlsl_cselect_descnum.txt new file mode 100644 index 0000000000..e8d9138028 --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_cselect_descnum.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_cselect_descnum_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_image_store_3d1d.txt b/tests/checks/python-linux/startup_gfx2hlsl_image_store_3d1d.txt new file mode 100644 index 0000000000..156f018870 --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_image_store_3d1d.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_image_store_3d1d_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_ldexp.txt b/tests/checks/python-linux/startup_gfx2hlsl_ldexp.txt new file mode 100644 index 0000000000..74acfe0204 --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_ldexp.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_ldexp_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_lerp_u8.txt b/tests/checks/python-linux/startup_gfx2hlsl_lerp_u8.txt new file mode 100644 index 0000000000..1971e25dbb --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_lerp_u8.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_lerp_u8_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_perm_b32.txt b/tests/checks/python-linux/startup_gfx2hlsl_perm_b32.txt new file mode 100644 index 0000000000..fa20b986ff --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_perm_b32.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_perm_b32_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_pk_minmax.txt b/tests/checks/python-linux/startup_gfx2hlsl_pk_minmax.txt new file mode 100644 index 0000000000..062f169387 --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_pk_minmax.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_pk_minmax_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_s_bitcmp64.txt b/tests/checks/python-linux/startup_gfx2hlsl_s_bitcmp64.txt new file mode 100644 index 0000000000..cc4f3baebb --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_s_bitcmp64.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_s_bitcmp64_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_s_bitset64.txt b/tests/checks/python-linux/startup_gfx2hlsl_s_bitset64.txt new file mode 100644 index 0000000000..814b296124 --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_s_bitset64.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_s_bitset64_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_s_cmp64.txt b/tests/checks/python-linux/startup_gfx2hlsl_s_cmp64.txt new file mode 100644 index 0000000000..a1b938326e --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_s_cmp64.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_s_cmp64_check.py diff --git a/tests/checks/python-linux/startup_image_sample_l_join.txt b/tests/checks/python-linux/startup_image_sample_l_join.txt new file mode 100644 index 0000000000..db8c2fa17b --- /dev/null +++ b/tests/checks/python-linux/startup_image_sample_l_join.txt @@ -0,0 +1 @@ +tests/startup_image_sample_l_join_check.py diff --git a/tests/cmake/cpu_nt_store.cmake b/tests/cmake/cpu_nt_store.cmake new file mode 100644 index 0000000000..a1ba263740 --- /dev/null +++ b/tests/cmake/cpu_nt_store.cmake @@ -0,0 +1,16 @@ +# Legacy non-temporal stores in the shared lowering (MOVNTPS, MOVNTPD, MOVNTDQ, MOVNTI): each lowers to its +# streaming-store intrinsic, the XMM forms keep the 16-byte alignment fault, and the MMX, SSE4a and VEX +# neighbours stay refused. The fixture compares native bytes with the lowered C++ for stores, misaligned +# targets and a PAGE_NOACCESS target, with controls that remove the alignment test or the store. +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME cpu_nt_store COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/nt_store_check.py") + add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/nt_store_fixture.cpp" + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/nt_store_fixture.py" emit + "${CMAKE_CURRENT_BINARY_DIR}/nt_store_fixture.cpp" + DEPENDS tests/cpu/nt_store_fixture.py tools/ffx_version_query.py VERBATIM) + add_executable(cpu_nt_store_fixture "${CMAKE_CURRENT_BINARY_DIR}/nt_store_fixture.cpp") + target_compile_features(cpu_nt_store_fixture PRIVATE cxx_std_17) + add_test(NAME cpu_nt_store_fixture COMMAND cpu_nt_store_fixture) + set_tests_properties(cpu_nt_store_fixture PROPERTIES SKIP_RETURN_CODE 77) +endif() diff --git a/tests/cmake/pe_import_routing.cmake b/tests/cmake/pe_import_routing.cmake new file mode 100644 index 0000000000..955dc0486a --- /dev/null +++ b/tests/cmake/pe_import_routing.cmake @@ -0,0 +1,6 @@ +# Unit, boundary-validation, and temp-copy mutation checks for tools/import_routing.py. +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME pe_import_routing_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/import_routing_check.py") + set_tests_properties(pe_import_routing_check PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/runtime_host_commit_unit.cmake b/tests/cmake/runtime_host_commit_unit.cmake new file mode 100644 index 0000000000..3261e3806d --- /dev/null +++ b/tests/cmake/runtime_host_commit_unit.cmake @@ -0,0 +1,6 @@ +# Pure-Python unit, boundary-validation, and temp-copy mutation checks for tools/host_commit.py. +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME runtime_host_commit_unit_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/host_commit_unit_check.py") + set_tests_properties(runtime_host_commit_unit_check PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/startup_compute_root_srv.cmake b/tests/cmake/startup_compute_root_srv.cmake new file mode 100644 index 0000000000..fa30001130 --- /dev/null +++ b/tests/cmake/startup_compute_root_srv.cmake @@ -0,0 +1,8 @@ +if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_stream_consumer) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_root_srv_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_root_srv_dispatch_check.py" + "$" "${DXC_EXECUTABLE}" ${adapter}) + set_tests_properties(startup_compute_root_srv_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_bvh.cmake b/tests/cmake/startup_gfx2hlsl_bvh.cmake new file mode 100644 index 0000000000..aaf68adc60 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_bvh.cmake @@ -0,0 +1,14 @@ +# gfx2hlsl image_bvh_intersect_ray FP32 box-node slice: translator controls, a DXC compile when +# one is available, and a WARP/hardware dispatch when offscreen_check is built. +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_gfx2hlsl_bvh COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_bvh_check.py") +endif() +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_bvh_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_bvh_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_bvh_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_cselect_descnum.cmake b/tests/cmake/startup_gfx2hlsl_cselect_descnum.cmake new file mode 100644 index 0000000000..f4a1648b2a --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_cselect_descnum.cmake @@ -0,0 +1,13 @@ +# gfx2hlsl compute s_cselect_b32 on descriptor-derived data (#2618, the C500 rows): the select keeps both arms as an +# opaque symbol, every later use that needs its value is refused by name, and three mutated translators must fail; +# then case A of the compute check with the dead select is dispatched and all 320 words compared. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + add_test(NAME startup_gfx2hlsl_cselect_descnum_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cselect_descnum_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_cselect_descnum_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cselect_descnum_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_cselect_descnum_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_ldexp.cmake b/tests/cmake/startup_gfx2hlsl_ldexp.cmake new file mode 100644 index 0000000000..4dc81de4af --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_ldexp.cmake @@ -0,0 +1,6 @@ +# gfx2hlsl v_ldexp_f32 lowering (Refs #2618): +# validates that v_ldexp_f32 lowers to ldexp32 and refuses invalid modifiers. +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_gfx2hlsl_ldexp_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_ldexp_check.py") +endif() diff --git a/tests/cmake/startup_gfx2hlsl_lerp_u8.cmake b/tests/cmake/startup_gfx2hlsl_lerp_u8.cmake new file mode 100644 index 0000000000..6899cb8813 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_lerp_u8.cmake @@ -0,0 +1,12 @@ +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_gfx2hlsl_lerp_u8_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_lerp_u8_check.py") + if(DXC_EXECUTABLE AND TARGET offscreen_check) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_lerp_u8_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_lerp_u8_check.py" draw "${DXC_EXECUTABLE}" + "$" "${adapter}" "${STARTUP_FXC}") + set_tests_properties(startup_gfx2hlsl_lerp_u8_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() + endif() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_perm_b32.cmake b/tests/cmake/startup_gfx2hlsl_perm_b32.cmake new file mode 100644 index 0000000000..d119fc0bb7 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_perm_b32.cmake @@ -0,0 +1,12 @@ +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_gfx2hlsl_perm_b32_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_perm_b32_check.py") + if(DXC_EXECUTABLE AND TARGET offscreen_check) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_perm_b32_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_perm_b32_check.py" draw "${DXC_EXECUTABLE}" + "$" "${adapter}" "${STARTUP_FXC}") + set_tests_properties(startup_gfx2hlsl_perm_b32_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() + endif() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_pk_minmax.cmake b/tests/cmake/startup_gfx2hlsl_pk_minmax.cmake new file mode 100644 index 0000000000..d6b02452b7 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_pk_minmax.cmake @@ -0,0 +1,13 @@ +# Packed binary16 min/max translation controls and D3D12 readback (#2022). +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_gfx2hlsl_pk_minmax_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_pk_minmax_check.py") + if(TARGET offscreen_check) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_pk_minmax_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_pk_minmax_check.py" draw + "${DXC_EXECUTABLE}" "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_pk_minmax_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() + endif() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_s_bitcmp64.cmake b/tests/cmake/startup_gfx2hlsl_s_bitcmp64.cmake new file mode 100644 index 0000000000..f61a24c82e --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_s_bitcmp64.cmake @@ -0,0 +1,11 @@ +# 64-bit scalar bit-compare (s_bitcmp0_b64, s_bitcmp1_b64) in tools/startup/gfx2hlsl.py. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + add_test(NAME startup_gfx2hlsl_s_bitcmp64_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitcmp64_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_s_bitcmp64_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitcmp64_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_s_bitcmp64_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_s_bitset64.cmake b/tests/cmake/startup_gfx2hlsl_s_bitset64.cmake new file mode 100644 index 0000000000..f08344d82a --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_s_bitset64.cmake @@ -0,0 +1,11 @@ +# 64-bit scalar bit set/clear (s_bitset0_b64, s_bitset1_b64) in tools/startup/gfx2hlsl.py. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + add_test(NAME startup_gfx2hlsl_s_bitset64_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitset64_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_s_bitset64_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitset64_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_s_bitset64_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_s_cmp64.cmake b/tests/cmake/startup_gfx2hlsl_s_cmp64.cmake new file mode 100644 index 0000000000..8f24093378 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_s_cmp64.cmake @@ -0,0 +1,11 @@ +# 64-bit scalar equality comparisons (s_cmp_eq_u64, s_cmp_lg_u64) in tools/startup/gfx2hlsl.py. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + add_test(NAME startup_gfx2hlsl_s_cmp64_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_cmp64_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_s_cmp64_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_cmp64_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_s_cmp64_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_image_sample_l_join.cmake b/tests/cmake/startup_image_sample_l_join.cmake new file mode 100644 index 0000000000..5cf16c9087 --- /dev/null +++ b/tests/cmake/startup_image_sample_l_join.cmake @@ -0,0 +1,10 @@ +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_image_sample_l_join_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_sample_l_join_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_image_sample_l_join_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_sample_l_join_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_image_sample_l_join_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_manifest_retry.cmake b/tests/cmake/startup_manifest_retry.cmake new file mode 100644 index 0000000000..dfb9e53e57 --- /dev/null +++ b/tests/cmake/startup_manifest_retry.cmake @@ -0,0 +1,5 @@ +# The retry schedule for an absent shader cache manifest (startup_stubs/manifest_retry.h). +add_executable(startup_manifest_retry_check tests/startup_manifest_retry_check.cpp) +target_include_directories(startup_manifest_retry_check PRIVATE src) +target_compile_features(startup_manifest_retry_check PRIVATE cxx_std_17) +add_test(NAME startup_manifest_retry COMMAND startup_manifest_retry_check) diff --git a/tests/cmake/startup_present_readback.cmake b/tests/cmake/startup_present_readback.cmake new file mode 100644 index 0000000000..86f59c6992 --- /dev/null +++ b/tests/cmake/startup_present_readback.cmake @@ -0,0 +1,4 @@ +add_executable(startup_present_readback_check tests/startup_present_readback_check.cpp) +target_compile_features(startup_present_readback_check PRIVATE cxx_std_17) +target_include_directories(startup_present_readback_check PRIVATE src) +add_test(NAME startup_present_readback COMMAND startup_present_readback_check) diff --git a/tests/cmake/textures_texture_blocks.cmake b/tests/cmake/textures_texture_blocks.cmake new file mode 100644 index 0000000000..5d34079431 --- /dev/null +++ b/tests/cmake/textures_texture_blocks.cmake @@ -0,0 +1,5 @@ +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME textures_texture_blocks_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/texture_blocks_check.py") + set_tests_properties(textures_texture_blocks_check PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/compute_store_check.py b/tests/compute_store_check.py index 404f259e7f..79faca44d3 100644 --- a/tests/compute_store_check.py +++ b/tests/compute_store_check.py @@ -3729,6 +3729,34 @@ def mac_f32_controls(): rejects("Unsupported compute instruction", aot.lower, variant(MAC_F32, ("v_mac_f32_e32 v10, 0x45800800, v5", bad_line)), 64, **MAC_F32_BINDING) + # The mad() fusion probe against a simulated renderer whose mutated shader reads back `readback`. + class Case: + def write_bytes(self, data): + self.words = list(struct.unpack("<321I", data)[1:]) + + def probe(readback, code=None): + case = Case() + + def run(): + diff = next((i for i, (a, b) in enumerate(zip(case.words, readback)) if a != b), None) + if code is not None or diff is None: + return subprocess.CompletedProcess([], code or 0, "", "") + return subprocess.CompletedProcess([], 1, "", f"word={diff} expected={case.words[diff]:08x} " + f"actual={readback[diff]:08x}\nCompute readback differs\n") + fusion = mac_f32_mad_fusion(run, case, expected) + assert case.words == expected + return fusion + expected, fused = mac_f32_words(), mac_f32_words(fused=True) + folded = [e if i % 4 == 0 else f for i, (e, f) in enumerate(zip(expected, fused))] + assert probe(expected) == "unfused" # no FMad fusion, as on an RX 5700 XT (#2730) + assert probe(folded) == "fused" # fused FMad, word 0 folded unfused by DXC, as on an RTX 4090 (#2883) + for readback, code, message in ((fused, None, "neither model alone"), (expected, 3, "failed (exit 3)")): + try: + probe(readback, code) + except AssertionError as error: + assert message in str(error), error + else: + raise AssertionError(f"mac_f32: mad() fusion probe accepted a readback that must fail: {message}") def mac_f32_binary(directory, assembler, objcopy, library): @@ -3742,18 +3770,25 @@ def mac_f32_binary(directory, assembler, objcopy, library): def mac_f32_mad_fusion(run_mutated, case, expected): """Whether this target fuses the `precise mad()` mutation: 'fused' or 'unfused' (#2730). - The mutated shader is read back against the fused and the unfused model. They differ at word 0, the - cancellation 4097 * 4097 - 16785408 (1.0 fused, +0 unfused). Exactly one model must match all 320 words; - a compile, dispatch or readback failure, or any other readback, fails the test. + The mutated shader is read back against the fused and the unfused model. Word 0, the cancellation + 4097 * 4097 - 16785408, has only constant operands, and DXC 1.9.2602.17 folds it at compile time to the + unfused +0, so a target that fuses FMad fuses only the thread-dependent words (#2883). The fused model + therefore keeps word 0 unfused and differs from the unfused model at words 2, 10, 18, ... Exactly one model + must match all 320 words; a compile, dispatch or readback failure, or any other readback, fails the test. + A DXC that leaves word 0 to the driver would read back neither model on a fusing target and fail here. """ - matches = {} - for name, model in (("fused", mac_f32_words(fused=True)), ("unfused", expected)): + fused = mac_f32_words(fused=True) + fused[0::4] = expected[0::4] + assert next(i for i, (a, b) in enumerate(zip(expected, fused)) if a != b) == 2 + matches, first = {}, {} + for name, model in (("fused", fused), ("unfused", expected)): case.write_bytes(struct.pack("<321I", 1, *model)) run = run_mutated() if run.returncode == 0: matches[name] = True elif run.returncode == 1 and "Compute readback differs" in run.stderr: matches[name] = False + first[name] = next((line for line in run.stderr.splitlines() if line.startswith("word=")), "") else: raise AssertionError(f"mac_f32: mad() fusion probe against the {name} model failed " f"(exit {run.returncode})\n{run.stdout}{run.stderr}") @@ -3762,7 +3797,8 @@ def mac_f32_mad_fusion(run_mutated, case, expected): return "fused" if matches == {"fused": False, "unfused": True}: return "unfused" - raise AssertionError(f"mac_f32: mad() fusion probe read back neither model alone: {matches}") + raise AssertionError(f"mac_f32: mad() fusion probe read back neither model alone: {matches}, " + f"first mismatch: {first}") def mac_f32_draw(directory, compiler, renderer, backend): @@ -5597,7 +5633,12 @@ def shared_controls(): atomics = aot.lower(programs["shared_atomics"], 64, **SHARED_BINDING) for method in ("Add", "And", "Or", "Xor", "Min", "Max"): assert f"Interlocked{method}(lds[" in atomics, method - assert "(0u - tid.x)" in atomics + # ds_sub_u32 is two additions, ~v then 1, on the same word. A single InterlockedAdd of a negated word on + # groupshared memory fails compute PSO creation on NVIDIA GeForce RTX 5080 (driver 32.0.16.2124). + sub = (" if (lds_a5 < 256u) InterlockedAdd(lds[lds_a5], ~(tid.x));\n" + " if (lds_a5 < 256u) InterlockedAdd(lds[lds_a5], 1u);\n") + assert sub in atomics, atomics + assert "0u - " not in atomics, atomics lines = programs["shared_exchange"] # A barrier with no DS instruction before it is kept. assert aot.lower(SHARED_PREFIX + ["s_barrier"] + lines[len(SHARED_PREFIX):], 64, @@ -5665,8 +5706,15 @@ def shared_draw(directory, compiler, renderer, backend): execution = subprocess.run(run) if execution.returncode: return execution.returncode - for mutated, mismatched_word in shared_mutants(name, lines, binding): - src.write_text(aot.lower(mutated, 64, **binding), encoding="ascii") + mutants = [(aot.lower(mutated, 64, **binding), word) for mutated, word in shared_mutants(name, lines, binding)] + if name == "shared_atomics": + # Without the second addition ds_sub_u32 adds ~v, so the difference read as lane 0's second word + # is 64 short, one for each lane. + dropped = source.replace(" if (lds_a5 < 256u) InterlockedAdd(lds[lds_a5], 1u);\n", "") + assert dropped != source + mutants.append((dropped, 1)) + for mutated, mismatched_word in mutants: + src.write_text(mutated, encoding="ascii") subprocess.run(compile, check=True) bad = subprocess.run(run, capture_output=True, text=True) if bad.returncode != 1 or f"word={mismatched_word} expected=" not in bad.stderr: diff --git a/tests/cpu/nt_store_check.py b/tests/cpu/nt_store_check.py new file mode 100644 index 0000000000..72c8cb077e --- /dev/null +++ b/tests/cpu/nt_store_check.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Control for the legacy non-temporal stores in the shared lowering (tools/ffx_version_query.py). + +MOVNTPS, MOVNTPD and MOVNTDQ (`0F 2B /r`, `66 0F 2B /r`, `66 0F E7 /r`) store a whole XMM register; like +MOVAPS they raise #GP(0) when the target is not 16-byte aligned. MOVNTI (`0F C3 /r`) stores a 32- or 64-bit +register with no alignment requirement. None of them changes a flag. The non-temporal hint and the weak +ordering of the store are kept by lowering each one to the matching streaming-store intrinsic. + +What is checked, all on exact byte patterns: + + accepted - the encoding lowers to the streaming intrinsic of its width. The XMM forms test the target + against 15 and raise the aligned-operand fault before the store; MOVNTI does not. + refused - the neighbours that are not part of this slice stay refused: an XMM register above XMM2 (the + register set MOVAPS has here), the MMX MOVNTQ, the SSE4a scalar MOVNTSS and MOVNTSD, the VEX + VMOVNTPS/VMOVNTPD/VMOVNTDQ, and the MOVNTDQA load. A widened accepted set would show up here. + +The native-versus-lifted comparison is tests/cpu/nt_store_fixture.py. +""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from iced_x86 import Decoder +from ffx_version_query import lower + +ALIGN = "if (target & 15u) raise_aligned_m128_fault();" + +# encoding -> (description, intrinsic the body must call, whether the body checks 16-byte alignment) +ACCEPTED = { + "0f2b01": ("movntps [rcx], xmm0", "_mm_stream_si128", True), + "660f2b01": ("movntpd [rcx], xmm0", "_mm_stream_si128", True), + "660fe701": ("movntdq [rcx], xmm0", "_mm_stream_si128", True), + "0f2b5110": ("movntps [rcx+16], xmm2", "_mm_stream_si128", True), + "660fe70424": ("movntdq [rsp], xmm0", "_mm_stream_si128", True), + "0fc301": ("movnti [rcx], eax", "_mm_stream_si32", False), + "480fc301": ("movnti [rcx], rax", "_mm_stream_si64", False), + "4c0fc34103": ("movnti [rcx+3], r8", "_mm_stream_si64", False), +} + +REFUSED = { + "0f2b19": "movntps [rcx], xmm3 (the shared lowering models XMM0-XMM2, as for MOVAPS)", + "0fe701": "movntq [rcx], mm0 (MMX)", + "f30f2b01": "movntss [rcx], xmm0 (SSE4a)", + "f20f2b01": "movntsd [rcx], xmm0 (SSE4a)", + "c5f82b01": "vmovntps [rcx], xmm0 (VEX)", + "c5f92b01": "vmovntpd [rcx], xmm0 (VEX)", + "c5f9e701": "vmovntdq [rcx], xmm0 (VEX)", + "660f382a01": "movntdqa xmm0, [rcx] (non-temporal load)", +} + + +def body(hex_bytes: str) -> str: + return lower(list(Decoder(64, bytes.fromhex(hex_bytes + "c3"))), [], {}, {}, {}) + + +def main() -> int: + failures = [] + + def check(label, condition, detail=""): + print(f"{label}: {'ok' if condition else 'MISMATCH'}{(' (' + detail + ')') if detail and not condition else ''}") + if not condition: + failures.append(label) + + for encoding, (description, intrinsic, aligned) in ACCEPTED.items(): + try: + lifted = body(encoding) + except ValueError as error: + check(f"accepted {encoding} ({description})", False, str(error)) + continue + check(f"accepted {encoding} ({description})", True) + check(f" {encoding} stores with {intrinsic}", lifted.count(intrinsic + "(") == 1) + check(f" {encoding} {'checks' if aligned else 'does not check'} 16-byte alignment", + (ALIGN in lifted) == aligned) + if aligned: + check(f" {encoding} raises the fault before the store", lifted.find(ALIGN) < lifted.find(intrinsic)) + + for encoding, description in REFUSED.items(): + try: + body(encoding) + except ValueError: + check(f"refused {encoding} ({description})", True) + continue + check(f"refused {encoding} ({description})", False, "lowering accepted it") + + if failures: + print(f"FAIL: {len(failures)} case(s)") + return 1 + print(f"PASS: {len(ACCEPTED)} non-temporal stores lowered, {len(REFUSED)} neighbours still refused") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/cpu/nt_store_fixture.py b/tests/cpu/nt_store_fixture.py new file mode 100644 index 0000000000..463713f78d --- /dev/null +++ b/tests/cpu/nt_store_fixture.py @@ -0,0 +1,255 @@ +#!/usr/bin/env python3 +"""Emit the non-temporal store differential fixture (MOVNTPS, MOVNTPD, MOVNTDQ, MOVNTI). + +For the same inputs, compare what the host executes for each store against what the shared lowering +(tools/ffx_version_query.lower()) produces for it: + + native - the exact bytes in an executable section, called directly. + lifted - the same instructions lowered to C++ and compiled alongside. + +Each case is called as f(target, source, value). The XMM cases load XMM0 or XMM2 from `source` with MOVDQU +and store it to `target`; the MOVNTI cases store the low 32 or 64 bits of `value`. Every case ends with SFENCE +and returns RAX. The native and lifted calls write into two separate 64-byte buffers that start filled with a +sentinel, so the check compares the whole buffer, not only the stored bytes, and an independent reference +(the source bytes or the value at the target offset, the sentinel elsewhere) is checked as well. + +The fault cases run under a guard that records the exception code and its two parameters: + - an XMM store to a target that is not 16-byte aligned raises #GP(0), which Windows reports as an access + violation at address -1; nothing may be written; + - a store to a PAGE_NOACCESS page raises an access violation for a write at that address; + - MOVNTI to an odd address is not a fault. + +Controls that must break a rule, so the cases above are informative: + - `noalign`: the lifted MOVNTPS with its alignment test removed and a plain store in place of the streaming + one must store where the native one faults (the streaming intrinsic is MOVNTDQ and faults by itself); + - `nostore`: the native bytes with the store replaced by a NOP must leave the reference unmatched; + - a plain MOVUPS to the same misaligned target must not fault natively, so the fault above comes from the + alignment rule and not from the mapping. + +usage: nt_store_fixture.py emit +""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from iced_x86 import Decoder +from ffx_version_query import INTEGER_HEADER, lower + +LOAD_XMM0 = bytes.fromhex("f30f6f02") # movdqu xmm0, [rdx] +LOAD_XMM2 = bytes.fromhex("f30f6f12") # movdqu xmm2, [rdx] +VALUE_RAX = bytes.fromhex("4c89c0") # mov rax, r8 +EPILOGUE = bytes.fromhex("0faef8c3") # sfence ; ret +ALIGN = "if (target & 15u) raise_aligned_m128_fault();" + +PAGE = "page" # the target is the PAGE_NOACCESS page + +# (name, description, prologue, store bytes, offset of RCX in the 64-byte buffer or PAGE, stored width, +# expected fault: None, "gp" (aligned-operand #GP) or "write"[, displacement of the store from RCX]) +CASES = [ + ("nt_movntps", "movntps [rcx], xmm0", LOAD_XMM0, bytes.fromhex("0f2b01"), 16, 16, None), + ("nt_movntpd", "movntpd [rcx], xmm0", LOAD_XMM0, bytes.fromhex("660f2b01"), 32, 16, None), + ("nt_movntdq", "movntdq [rcx], xmm0", LOAD_XMM0, bytes.fromhex("660fe701"), 0, 16, None), + ("nt_movntps_disp", "movntps [rcx+16], xmm2", LOAD_XMM2, bytes.fromhex("0f2b5110"), 0, 16, None, 16), + ("nt_movnti32", "movnti [rcx], eax", VALUE_RAX, bytes.fromhex("0fc301"), 8, 4, None), + ("nt_movnti64", "movnti [rcx], rax", VALUE_RAX, bytes.fromhex("480fc301"), 24, 8, None), + ("nt_movnti32_odd", "movnti [rcx], eax at an odd address", VALUE_RAX, bytes.fromhex("0fc301"), 3, 4, None), + ("nt_movnti64_odd", "movnti [rcx], rax at an odd address", VALUE_RAX, bytes.fromhex("480fc301"), 41, 8, None), + ("nt_movntps_misaligned", "movntps [rcx], xmm0 at +8", LOAD_XMM0, bytes.fromhex("0f2b01"), 8, 16, "gp"), + ("nt_movntpd_misaligned", "movntpd [rcx], xmm0 at +4", LOAD_XMM0, bytes.fromhex("660f2b01"), 4, 16, "gp"), + ("nt_movntdq_misaligned", "movntdq [rcx], xmm0 at +1", LOAD_XMM0, bytes.fromhex("660fe701"), 1, 16, "gp"), + ("nt_movntps_noaccess", "movntps to PAGE_NOACCESS", LOAD_XMM0, bytes.fromhex("0f2b01"), PAGE, 16, "write"), + ("nt_movntdq_noaccess", "movntdq to PAGE_NOACCESS", LOAD_XMM0, bytes.fromhex("660fe701"), PAGE, 16, "write"), + ("nt_movnti64_noaccess", "movnti [rcx], rax to PAGE_NOACCESS", VALUE_RAX, bytes.fromhex("480fc301"), PAGE, 8, + "write"), +] + +TEST_MAIN = r""" +using Fn = word (*)(word, word, word); + +enum Expect { NONE, GP, WRITE }; + +struct Case { + const char* name; + const char* description; + const unsigned char* native_bytes; + Fn lifted; + int offset; // of RCX in the buffer; -1: the PAGE_NOACCESS page + int disp; // of the store from RCX + int width; + Expect expect; +}; + +struct Fault { + unsigned long code = 0; + unsigned long long info0 = 0, info1 = 0; + bool raised = false; +}; + +static int capture(EXCEPTION_POINTERS* pointers, Fault* fault) +{ + const EXCEPTION_RECORD* record = pointers->ExceptionRecord; + fault->raised = true; + fault->code = record->ExceptionCode; + fault->info0 = record->NumberParameters > 0 ? record->ExceptionInformation[0] : ~0ull; + fault->info1 = record->NumberParameters > 1 ? record->ExceptionInformation[1] : ~0ull; + return EXCEPTION_EXECUTE_HANDLER; +} + +static Fault call(Fn fn, word target, word source, word value) +{ + Fault fault; + __try { + (void)fn(target, source, value); + } __except (capture(GetExceptionInformation(), &fault)) { + } + return fault; +} + +static const Case cases[] = { +/*CASES*/ +}; + +static const unsigned char SENTINEL = 0xA5; +static const unsigned long long VALUE = 0x0123456789ABCDEFull; + +int main() +{ + // Page 0: the two 64-byte buffers (native at 0, lifted at 128) and the 16 source bytes at 256. + // Page 1: PAGE_NOACCESS. + unsigned char* base = + static_cast(VirtualAlloc(nullptr, 8192, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + DWORD old = 0; + if (!base || !VirtualProtect(base + 4096, 4096, PAGE_NOACCESS, &old)) { + std::printf("skip: VirtualAlloc/VirtualProtect failed\n"); + return 77; + } + unsigned char* native_buf = base; + unsigned char* lifted_buf = base + 128; + unsigned char* source = base + 256; + unsigned char* page = base + 4096; + for (int k = 0; k < 16; ++k) source[k] = static_cast(0x10 + 7 * k); + + int failures = 0; + for (const Case& test : cases) { + memset(native_buf, SENTINEL, 64); + memset(lifted_buf, SENTINEL, 64); + const Fn native = reinterpret_cast(const_cast(test.native_bytes)); + const word native_target = reinterpret_cast(test.offset < 0 ? page : native_buf + test.offset); + const word lifted_target = reinterpret_cast(test.offset < 0 ? page : lifted_buf + test.offset); + const Fault nf = call(native, native_target, reinterpret_cast(source), VALUE); + const Fault lf = call(test.lifted, lifted_target, reinterpret_cast(source), VALUE); + + // The reference: the stored bytes at the offset when the case does not fault, the sentinel elsewhere. + unsigned char reference[64]; + memset(reference, SENTINEL, 64); + if (test.expect == NONE) + memcpy(reference + test.offset + test.disp, test.width == 16 ? source : reinterpret_cast(&VALUE), + test.width); + bool expected_fault = false; + if (test.expect == NONE) expected_fault = !nf.raised; + if (test.expect == GP) + expected_fault = nf.raised && nf.code == 0xC0000005ul && nf.info0 == 0 && nf.info1 == ~0ull; + if (test.expect == WRITE) + expected_fault = nf.raised && nf.code == 0xC0000005ul && nf.info0 == 1 && + nf.info1 >= reinterpret_cast(page) && nf.info1 < reinterpret_cast(page) + 16; + const bool same_fault = nf.raised == lf.raised && nf.code == lf.code && nf.info0 == lf.info0 && + (test.expect == WRITE ? lf.info1 == nf.info1 : lf.info1 == nf.info1); + const bool native_ref = memcmp(native_buf, reference, 64) == 0; + const bool lifted_ref = memcmp(lifted_buf, reference, 64) == 0; + const bool ok = expected_fault && same_fault && native_ref && lifted_ref; + std::printf("%s (%s): native fault=%d code=0x%08lx info=%llu,0x%llx lifted fault=%d code=0x%08lx " + "info=%llu,0x%llx buffers native=%s lifted=%s %s\n", + test.name, test.description, nf.raised ? 1 : 0, nf.code, nf.info0, nf.info1, lf.raised ? 1 : 0, + lf.code, lf.info0, lf.info1, native_ref ? "ref" : "DIFF", lifted_ref ? "ref" : "DIFF", + ok ? "ok" : "MISMATCH"); + if (!ok) ++failures; + } + + // Control `noalign`: without its alignment test the lifted MOVNTPS stores at +8, where the native one faults. + { + memset(lifted_buf, SENTINEL, 64); + const Fault f = call(lifted_control_noalign, reinterpret_cast(lifted_buf + 8), + reinterpret_cast(source), VALUE); + const bool broke = !f.raised && memcmp(lifted_buf + 8, source, 16) == 0; + std::printf("control noalign: fault=%d %s\n", f.raised ? 1 : 0, + broke ? "ok (differs from native)" : "MISMATCH (the misaligned cases do not test the check)"); + if (!broke) ++failures; + } + // Control `nostore`: with the store replaced by a NOP the reference must not match. + { + memset(native_buf, SENTINEL, 64); + const Fault f = call(reinterpret_cast(const_cast(nat_control_nostore)), + reinterpret_cast(native_buf + 16), reinterpret_cast(source), VALUE); + const bool broke = !f.raised && memcmp(native_buf + 16, source, 16) != 0; + std::printf("control nostore: %s\n", broke ? "ok (reference unmatched)" : "MISMATCH (reference cannot see a store)"); + if (!broke) ++failures; + } + // Control: a plain MOVUPS to the same misaligned target does not fault. + { + memset(native_buf, SENTINEL, 64); + const Fault f = call(reinterpret_cast(const_cast(nat_control_movups)), + reinterpret_cast(native_buf + 8), reinterpret_cast(source), VALUE); + const bool ok = !f.raised && memcmp(native_buf + 8, source, 16) == 0; + std::printf("control movups at +8: fault=%d %s\n", f.raised ? 1 : 0, ok ? "ok" : "MISMATCH"); + if (!ok) ++failures; + } + + if (failures) { + std::printf("FAIL: %d case(s)\n", failures); + return 1; + } + std::printf("PASS: every non-temporal store matched native, including the alignment and access faults\n"); + return 0; +} +""" + + +def lifted(name: str, code: bytes, mutate=None) -> str: + text = lower(list(Decoder(64, code)), ["rcx = a; rdx = b; r8 = c;"], {}, {}, {}) + if mutate: + text = mutate(text) + return f'extern "C" __declspec(dllexport) word lifted_{name}(word a, word b, word c) {{\n{text}\n}}' + + +def native(name: str, code: bytes) -> str: + emitted = ", ".join("0x%02x" % byte for byte in code) + return f'#pragma section(".text")\n__declspec(allocate(".text")) const unsigned char nat_{name}[] = {{{emitted}}};' + + +def main() -> int: + if len(sys.argv) != 3 or sys.argv[1] != "emit": + print(__doc__) + return 2 + output = Path(sys.argv[2]) + + parts = [INTEGER_HEADER, "#include \n#include \n#include \n"] + rows = [] + for name, description, prologue, store, offset, width, fault, *disp in CASES: + code = prologue + store + EPILOGUE + parts.append(native(name, code)) + parts.append(lifted(name, code)) + expect = {None: "NONE", "gp": "GP", "write": "WRITE"}[fault] + rows.append(f' {{"{name}", "{description}", nat_{name}, lifted_{name}, ' + f'{-1 if offset == PAGE else offset}, {disp[0] if disp else 0}, {width}, {expect}}},') + + movntps = LOAD_XMM0 + bytes.fromhex("0f2b01") + EPILOGUE + + def drop_align(text: str) -> str: + # The streaming intrinsic compiles to MOVNTDQ, which faults on its own, so the control also turns it + # into a plain store: a lowering that ignores the alignment rule. + stream = "_mm_stream_si128(reinterpret_cast<__m128i*>(target), value);" + if text.count(ALIGN) != 1 or text.count(stream) != 1: + raise SystemExit("noalign control: the lifted MOVNTPS has no single alignment test and store to replace") + return text.replace(ALIGN, "").replace(stream, "memcpy(reinterpret_cast(target), &value, 16);") + + parts.append(lifted("control_noalign", movntps, drop_align)) + parts.append(native("control_nostore", LOAD_XMM0 + bytes.fromhex("0f1f00") + EPILOGUE)) # nop dword [rax] + parts.append(native("control_movups", LOAD_XMM0 + bytes.fromhex("0f1101") + EPILOGUE)) # movups [rcx], xmm0 + parts.append(TEST_MAIN.replace("/*CASES*/", "\n".join(rows))) + output.write_text("\n".join(parts) + "\n", encoding="utf-8") + print(f"emitted {len(CASES)} non-temporal store cases into {output}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index 09beb8ce19..a49d48dd87 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -30,7 +30,10 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const void check_startup_image_load_d16(ID3D12Device* device, const char* vertex_path, const char* pixel_path, bool depth16, std::uint32_t words[64], bool array = false); int check_startup_image_store(ID3D12Device* device, const char* vertex_path, const char* pixel_path, UINT x, UINT y, - const std::uint32_t expected[4]); + const std::uint32_t expected[4], unsigned coverage = 1); +// Queries colour formats and returns "typed_uav_load_refused" when one has no typed UAV load, before any draw. +// Returns nullptr only when the refusal helper itself accepts a cleared UAV_TYPED_LOAD bit. +const char* check_startup_image_store_typed_load(ID3D12Device* device); 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, D3D12_CULL_MODE cull = D3D12_CULL_MODE_NONE, BOOL front_ccw = FALSE, diff --git a/tests/gfx1030_bvh_box/bvh_model.py b/tests/gfx1030_bvh_box/bvh_model.py new file mode 100644 index 0000000000..da0b588e5c --- /dev/null +++ b/tests/gfx1030_bvh_box/bvh_model.py @@ -0,0 +1,235 @@ +# SPDX-License-Identifier: MIT +"""CPU model of the console BVH node test. + +This models one ``image_bvh_intersect_ray`` / ``image_bvh64_intersect_ray`` +call: a ray and a node pointer in, four result DWORDs out. Node traversal, +the stack and instance transforms belong to the calling shader and are not +part of this module. + +The node formats and the box test follow the public software emulation in +Mesa's RADV driver (MIT). The triangle test is the watertight formulation +from Woop, Benthin and Wald, JCGT 2013, as RADV uses it. The result layout +is the 40-bit ray-tracing descriptor's triangle return mode 1: +``{t_num, t_denom, I_num, J_num}``. Arithmetic is binary32 at every step, +rounding to nearest even; scalar Python floats only carry the values. +""" + +import math +import struct + + +MASK32 = (1 << 32) - 1 +MASK48 = (1 << 48) - 1 +MASK64 = (1 << 64) - 1 +INVALID = 0xffffffff + +NODE_BOX16 = 4 +NODE_BOX32 = 5 +SORT_ENABLE = 1 << 31 +RETURN_BARYCENTRICS = 1 << 24 + +TRIANGLE_VERTICES = ((0, 1, 2), (1, 3, 2), (2, 3, 4), (2, 4, 0)) +MISS = (math.inf, 1.0, 0.0, 0.0) +FLT_MAX = struct.unpack(" 0.0 else -math.inf + + +def f32_bits(value): + return struct.unpack("= b else b + + +def node_address(descriptor, pointer, wide=False): + """Return ``(kind, byte address)`` for a node pointer. + + The low three bits are the node kind. The rest addresses a 64-byte + node: ``(pointer >> 3) << 6``. The 32-bit form adds that offset to a + 40-bit base held in descriptor DWORD 0 and the low byte of DWORD 1, in + 256-byte units. The 64-bit form uses the absolute pointer. + """ + kind = pointer & 7 + if wide: + return kind, ((pointer >> 3) << 6) & MASK64 + base = (((descriptor[1] & 0xff) << 32) | (descriptor[0] & MASK32)) << 8 + return kind, (base + ((pointer >> 3) << 6)) & MASK48 + + +def descriptor(base=0, *, sort=True, return_barycentrics=True, size=0x3ffffffffff): + """Build the four descriptor DWORDs a node test reads. + + The base argument is a 256-byte aligned byte address. The DWORDs hold + it in 256-byte units, as the instruction's resource does. + """ + assert base & 0xff == 0, "the descriptor base is 256-byte aligned" + units = base >> 8 + return ( + units & MASK32, + ((units >> 32) & 0xff) | (SORT_ENABLE if sort else 0), + size & MASK32, + ((size >> 32) & 0x3fffff) + | (RETURN_BARYCENTRICS if return_barycentrics else 0) + | (8 << 28), + ) + + +def _load_box(data, offset, kind, index): + if kind == NODE_BOX32: + start = offset + 16 + 24 * index + return struct.unpack_from("<6f", data, start) + start = offset + 16 + 12 * index + return struct.unpack_from("<6e", data, start) + + +def _box_entry(lo, hi, origin, inverse, extent): + # RADV removes infinities so an origin exactly on a face does not turn + # zero times infinity into NaN. max then min is the order its NIR uses. + inv = [fmin(fmax(inverse[i], -FLT_MAX), FLT_MAX) for i in range(3)] + low = [fmul(fsub(lo[i], origin[i]), inv[i]) for i in range(3)] + high = [fmul(fsub(hi[i], origin[i]), inv[i]) for i in range(3)] + enter = fmax(fmax(fmin(low[0], high[0]), fmin(low[1], high[1])), fmin(low[2], high[2])) + leave = fmin(fmin(fmax(low[0], high[0]), fmax(low[1], high[1])), fmax(low[2], high[2])) + # min.x is the inactive-slot marker. Other NaN components are outside + # the defined input; fmin/fmax above use the non-NaN operand. + if math.isnan(lo[0]): + return None + if leave >= fmax(0.0, enter) and enter < extent: + return enter + return None + + +def _boxes(data, offset, kind, origin, inverse, extent, sort): + children = struct.unpack_from("<4I", data, offset) + indices = [INVALID] * 4 + distances = [math.inf] * 4 + for i in range(4): + if children[i] == INVALID: + continue + coords = _load_box(data, offset, kind, i) + enter = _box_entry(coords[:3], coords[3:], origin, inverse, extent) + if enter is not None: + indices[i] = children[i] + distances[i] = enter + if sort: + # RADV's five-comparator network. A strict comparison leaves equal + # entries in child order. + for a, b in ((0, 1), (2, 3), (0, 2), (1, 3), (1, 2)): + if distances[b] < distances[a]: + distances[a], distances[b] = distances[b], distances[a] + indices[a], indices[b] = indices[b], indices[a] + return indices + + +def _node_vertex(data, offset, index): + return struct.unpack_from("<3f", data, offset + 12 * index) + + +def _triangle(data, offset, kind, origin, direction, inverse): + id_dword = struct.unpack_from("> (8 * (kind & 3))) & 0xff + i = id_byte & 3 + j = (id_byte >> 2) & 3 + first = (3 - i - j) & 3 + # The fourth map nibble is zero in the node format; a malformed ID that + # names it reads the node's first vertex, as the arithmetic lands. + mapped = TRIANGLE_VERTICES[kind & 3] + (0,) + a, b, c = (_node_vertex(data, offset, mapped[n]) for n in (first, i, j)) + + size = (abs(direction[0]), abs(direction[1]), abs(direction[2])) + if size[0] >= size[1]: + kz = 0 if size[0] >= size[2] else 2 + elif size[1] >= size[2]: + kz = 1 + else: + kz = 2 + kx = (kz + 1) % 3 + ky = (kx + 1) % 3 + if direction[kz] < 0.0: + kx, ky = ky, kx + + sz = inverse[kz] + sx = fmul(direction[kx], sz) + sy = fmul(direction[ky], sz) + + def shear(vertex): + rel = [fsub(vertex[n], origin[n]) for n in range(3)] + return ( + fsub(rel[kx], fmul(sx, rel[kz])), + fsub(rel[ky], fmul(sy, rel[kz])), + fmul(sz, rel[kz]), + ) + + ax, ay, az = shear(a) + bx, by, bz = shear(b) + cx, cy, cz = shear(c) + u = fsub(fmul(cx, by), fmul(cy, bx)) + v = fsub(fmul(ax, cy), fmul(ay, cx)) + w = fsub(fmul(bx, ay), fmul(by, ax)) + + behind = u < 0.0 or v < 0.0 or w < 0.0 + before = u > 0.0 or v > 0.0 or w > 0.0 + det = fadd(u, fadd(v, w)) + t = fadd(fadd(fmul(u, az), fmul(v, bz)), fmul(w, cz)) + ahead = (det > 0.0 and t >= 0.0) or (det < 0.0 and t <= 0.0) + if (behind and before) or not ahead: + return MISS + # The instruction does not test the ray extent for triangles. + return f32(t), f32(det), f32(v), f32(w) + + +def intersect(data, descriptor_words, pointer, *, origin, direction, inverse, extent, + wide=False): + """Return the four result DWORDs for one node and one ray.""" + kind, address = node_address(descriptor_words, pointer, wide) + sort = bool(descriptor_words[1] & SORT_ENABLE) + if kind == NODE_BOX32 or kind == NODE_BOX16: + return _boxes(data, address, kind, origin, inverse, extent, sort) + if kind <= 3: + if not descriptor_words[3] & RETURN_BARYCENTRICS: + raise ValueError("triangle return mode 0 is not modeled") + # The instruction does not test the ray extent for triangles. + values = _triangle(data, address, kind, origin, direction, inverse) + return [f32_bits(value) for value in values] + # Instance and procedural nodes are not read by this instruction. + return [f32_bits(value) for value in MISS] diff --git a/tests/gfx1030_bvh_box/check.py b/tests/gfx1030_bvh_box/check.py index 3153ff5f90..66b69bca6c 100644 --- a/tests/gfx1030_bvh_box/check.py +++ b/tests/gfx1030_bvh_box/check.py @@ -3,9 +3,16 @@ import argparse import ctypes as ct import hashlib +import math import os from pathlib import Path import struct +import sys +from collections import namedtuple + + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import bvh_model ROOT = Path(__file__).resolve().parents[2] @@ -17,6 +24,9 @@ TRANSFER_TO_DEVICE = 1 TRANSFER_TO_HOST = 2 MASK32 = (1 << 32) - 1 +inf = math.inf +D_SORT = bvh_model.descriptor(0, sort=True) +D_NOSORT = bvh_model.descriptor(0, sort=False) def box(child, depth, x=-8): @@ -80,6 +90,910 @@ def model_check(): print("all_miss zero-fill control word=0 expected=ffffffff actual=00000000") +Witness = namedtuple("Witness", "name image descriptor pointer ray expected wide") +PointerWitness = namedtuple("PointerWitness", "name descriptor pointer wide expected") + + +def C(name, image, descriptor, pointer, ray, expected, wide=False): + return Witness(name, image, descriptor, pointer, ray, expected, wide) + + +def P(name, descriptor, pointer, wide, expected): + return PointerWitness(name, descriptor, pointer, wide, expected) + + +def witness_check(): + failures = 0 + for case in WITNESSES: + origin, direction, inverse, extent = case.ray + actual = tuple(bvh_model.intersect(case.image, case.descriptor, case.pointer, + origin=origin, direction=direction, inverse=inverse, + extent=extent, wide=case.wide)) + difference = first_difference(case.expected, actual) + if difference: + index, wanted, got = difference + print(f"witness {case.name} word={index} expected={wanted:08x} actual={got:08x}") + failures += 1 + for case in POINTER_WITNESSES: + actual = bvh_model.node_address(case.descriptor, case.pointer, case.wide) + if actual != case.expected: + print(f"pointer witness {case.name} expected={case.expected} actual={actual}") + failures += 1 + print(f"model_witness_cases={len(WITNESSES) + len(POINTER_WITNESSES)} " + f"node={len(WITNESSES)} pointer={len(POINTER_WITNESSES)} mismatches={failures}") + return failures + + +# box32/four-sorted +NODE_0 = bytes.fromhex( + "050100000c020000040300000004000000002041000080bf000080bf00003041" + "0000803f0000803f0000a041000080bf000080bf0000a8410000803f0000803f" + "0000f041000080bf000080bf0000f8410000803f0000803f00002042000080bf" + "000080bf000024420000803f0000803f00000000000000000000000000000000" +) +# box32/tie-sorted +NODE_1 = bytes.fromhex( + "050100000c020000040300000004000000002041000080bf000080bf00003041" + "0000803f0000803f00002041000080bf000080bf000030410000803f0000803f" + "00002041000080bf000080bf000030410000803f0000803f00002041000080bf" + "000080bf000030410000803f0000803f00000000000000000000000000000000" +) +# box32/tie-two-then-far +NODE_2 = bytes.fromhex( + "050100000c020000040300000004000000002041000080bf000080bf00003041" + "0000803f0000803f00002041000080bf000080bf000030410000803f0000803f" + "0000f041000080bf000080bf0000f8410000803f0000803f00002042000080bf" + "000080bf000024420000803f0000803f00000000000000000000000000000000" +) +# box32/mixed-sorted +NODE_3 = bytes.fromhex( + "05010000ffffffff04030000ffffffff00002041000080bf000080bf00003041" + "0000803f0000803f0000a041000080bf000080bf0000a8410000803f0000803f" + "0000f041000080bf000080bf0000f8410000803f0000803f00002042000080bf" + "000080bf000024420000803f0000803f00000000000000000000000000000000" +) +# box32/zero-child-sorted +NODE_4 = bytes.fromhex( + "0000000005010000000000000403000000002041000080bf000080bf00003041" + "0000803f0000803f0000a041000080bf000080bf0000a8410000803f0000803f" + "0000f041000080bf000080bf0000f8410000803f0000803f00002042000080bf" + "000080bf000024420000803f0000803f00000000000000000000000000000000" +) +# box32/overlap-sorted +NODE_5 = bytes.fromhex( + "050100000c020000040300000004000000002041000080bf000080bf0000f041" + "0000803f0000803f0000a041000080bf000080bf0000c8410000803f0000803f" + "00002042000080bf000080bf000024420000803f0000803f0000a040000080bf" + "000080bf0000c0400000803f0000803f00000000000000000000000000000000" +) +# box32/3d-0.5-0.5 +NODE_6 = bytes.fromhex( + "050100000c020000040300000004000000002041000000000000000000003041" + "0000803f0000803f00002041000000400000000000003041000040400000803f" + "000020410000000000000040000030410000803f000040400000204100000040" + "0000004000003041000040400000404000000000000000000000000000000000" +) +# box32/behind-0-e1e+09 +NODE_7 = bytes.fromhex( + "050100000c02000004030000000400000000a0c1000080bf000080bf000020c1" + "0000803f0000803f000020c1000080bf000080bf000020410000803f0000803f" + "00000000000080bf000080bf000020410000803f0000803f00002041000080bf" + "000080bf0000a0410000803f0000803f00000000000000000000000000000000" +) +# box32/zerodir-10.5-0 +NODE_8 = bytes.fromhex( + "050100000c02000004030000000400000000204100002041000080bf00003041" + "000030410000803f0000a04100002041000080bf0000a841000030410000803f" + "0000f04100002041000080bf0000f841000030410000803f0000204200002041" + "000080bf00002442000030410000803f00000000000000000000000000000000" +) +# box32/inverted +NODE_9 = bytes.fromhex( + "050100000c020000040300000004000000003041000080bf000080bf00002041" + "0000803f0000803f00000000000080bf000080bf0000a0410000803f0000803f" + "0000f041000080bf000080bf0000c8410000803f0000803f00002042000080bf" + "000080bf000024420000803f0000803f00000000000000000000000000000000" +) +# box32/infinite-bounds +NODE_10 = bytes.fromhex( + "050100000c020000040300000004000000002041000080bf000080bf0000807f" + "0000803f0000803f000080ff000080bf000080bf0000a0410000803f0000803f" + "000080ff000080bf000080bf0000807f0000803f0000803f00002041000080bf" + "000080bf000020410000803f0000803f00000000000000000000000000000000" +) +# box32/nan-min-disabled +NODE_11 = bytes.fromhex( + "050100000c02000004030000000400000000c07f000080bf000080bf00003041" + "0000803f0000803f0000a041000080bf000080bf0000a8410000803f0000803f" + "0000f041000080bf000080bf0000f8410000803f0000803f00002042000080bf" + "000080bf000024420000803f0000803f00000000000000000000000000000000" +) +# box32/nan-max-convention +NODE_12 = bytes.fromhex( + "050100000c020000040300000004000000002041000080bf000080bf0000c07f" + "0000803f0000803f0000a041000080bf000080bf0000a8410000803f0000803f" + "0000f041000080bf000080bf0000f8410000803f0000803f00002042000080bf" + "000080bf000024420000803f0000803f00000000000000000000000000000000" +) +# box16/four-sorted +NODE_13 = bytes.fromhex( + "050100000c0200000403000000040000004900bc00bc8049003c003c004d00bc" + "00bc404d003c003c804f00bc00bcc04f003c003c005100bc00bc2051003c003c" +) +# box16/tie-sorted +NODE_14 = bytes.fromhex( + "050100000c0200000403000000040000004900bc00bc8049003c003c004900bc" + "00bc8049003c003c004900bc00bc8049003c003c004900bc00bc8049003c003c" +) +# box16/mixed-sorted +NODE_15 = bytes.fromhex( + "05010000ffffffff04030000ffffffff004900bc00bc8049003c003c004d00bc" + "00bc404d003c003c804f00bc00bcc04f003c003c005100bc00bc2051003c003c" +) +# box16/zero-child-sorted +NODE_16 = bytes.fromhex( + "00000000050100000000000004030000004900bc00bc8049003c003c004d00bc" + "00bc404d003c003c804f00bc00bcc04f003c003c005100bc00bc2051003c003c" +) +# box16/round-low-e0 +NODE_17 = bytes.fromhex( + "050100000c0200000403000000040000662e00bc00bc003c003c003c662e00bc" + "00bc003c003c003c662e00bc00bc003c003c003c662e00bc00bc003c003c003c" +) +# box16/round-high-neg +NODE_18 = bytes.fromhex( + "050100000c0200000403000000040000000000bc00bc3340003c003c000000bc" + "00bc3340003c003c000000bc00bc3340003c003c000000bc00bc3340003c003c" +) +# box16/subnormal-e1 +NODE_19 = bytes.fromhex( + "050100000c0200000403000000040000010000bc00bc0200003c003c000400bc" + "00bc0008003c003c003c00bc00bc0040003c003c000000bc00bc0038003c003c" +) +# box16/65504-e10 +NODE_20 = bytes.fromhex( + "050100000c0200000403000000040000ff7b00bc00bcff7b003c003cff7b00bc" + "00bcff7b003c003cff7b00bc00bcff7b003c003cff7b00bc00bcff7b003c003c" +) +# box16/infinite-bounds +NODE_21 = bytes.fromhex( + "050100000c0200000403000000040000004900bc00bc007c003c003c00fc00bc" + "00bc004d003c003c00fc00bc00bc007c003c003c004900bc00bc0049003c003c" +) +# box16/nan-min-disabled +NODE_22 = bytes.fromhex( + "050100000c0200000403000000040000007e00bc00bc8049003c003c004d00bc" + "00bc404d003c003c804f00bc00bcc04f003c003c005100bc00bc2051003c003c" +) +# box16/negzero-0.0 +NODE_23 = bytes.fromhex( + "050100000c0200000403000000040000008000bc00bc0000003c003c008000bc" + "00bc0000003c003c008000bc00bc0000003c003c008000bc00bc0000003c003c" +) +# box32/scramble-sorted +NODE_24 = bytes.fromhex( + "050100000c020000040300000004000000002042000080bf000080bf00002442" + "0000803f0000803f00002041000080bf000080bf000030410000803f0000803f" + "0000f041000080bf000080bf0000f8410000803f0000803f0000a041000080bf" + "000080bf0000a8410000803f0000803f00000000000000000000000000000000" +) +# box16/scramble-sorted +NODE_25 = bytes.fromhex( + "050100000c0200000403000000040000005100bc00bc2051003c003c004900bc" + "00bc8049003c003c804f00bc00bcc04f003c003c004d00bc00bc404d003c003c" +) +# box32/pairs-sorted +NODE_26 = bytes.fromhex( + "050100000c02000004030000000400000000a041000080bf000080bf0000a841" + "0000803f0000803f0000a041000080bf000080bf0000a8410000803f0000803f" + "00002041000080bf000080bf000030410000803f0000803f00002041000080bf" + "000080bf000030410000803f0000803f00000000000000000000000000000000" +) +# box16/pairs-sorted +NODE_27 = bytes.fromhex( + "050100000c0200000403000000040000004d00bc00bc404d003c003c004d00bc" + "00bc404d003c003c004900bc00bc8049003c003c004900bc00bc8049003c003c" +) +# box32/interleaved-sorted +NODE_28 = bytes.fromhex( + "050100000c020000040300000004000000002041000080bf000080bf00003041" + "0000803f0000803f0000a041000080bf000080bf0000a8410000803f0000803f" + "00002041000080bf000080bf000030410000803f0000803f0000a041000080bf" + "000080bf0000a8410000803f0000803f00000000000000000000000000000000" +) +# box16/interleaved-sorted +NODE_29 = bytes.fromhex( + "050100000c0200000403000000040000004900bc00bc8049003c003c004d00bc" + "00bc404d003c003c004900bc00bc8049003c003c004d00bc00bc404d003c003c" +) +# box16/3d-0.5-0.5 +NODE_30 = bytes.fromhex( + "050100000c02000004030000000400000049000000008049003c003c00490040" + "000080490042003c0049000000408049003c0042004900400040804900420042" +) +# box16/inverted +NODE_31 = bytes.fromhex( + "050100000c0200000403000000040000804900bc00bc0049003c003c000000bc" + "00bc004d003c003c804f00bc00bc404e003c003c005100bc00bc2051003c003c" +) +# tri/kind0-center +NODE_32 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f09090909" +) +# tri/kind0-id09 +NODE_33 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f09000000" +) +# tri/kind0-id09-hi +NODE_34 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f59000000" +) +# tri/kind0-id06 +NODE_35 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f06000000" +) +# tri/kind0-id06-hi +NODE_36 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f56000000" +) +# tri/kind0-id08 +NODE_37 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f08000000" +) +# tri/kind0-id08-hi +NODE_38 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f58000000" +) +# tri/kind0-id02 +NODE_39 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f02000000" +) +# tri/kind0-id02-hi +NODE_40 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f52000000" +) +# tri/kind0-id04 +NODE_41 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f04000000" +) +# tri/kind0-id04-hi +NODE_42 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f54000000" +) +# tri/kind0-id01 +NODE_43 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f01000000" +) +# tri/kind0-id01-hi +NODE_44 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f51000000" +) +# tri/kind1-id09 +NODE_45 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00090000" +) +# tri/kind1-id09-hi +NODE_46 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00590000" +) +# tri/kind1-id06 +NODE_47 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00060000" +) +# tri/kind1-id06-hi +NODE_48 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00560000" +) +# tri/kind1-id08 +NODE_49 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00080000" +) +# tri/kind1-id08-hi +NODE_50 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00580000" +) +# tri/kind1-id02 +NODE_51 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00020000" +) +# tri/kind1-id02-hi +NODE_52 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00520000" +) +# tri/kind1-id04 +NODE_53 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00040000" +) +# tri/kind1-id04-hi +NODE_54 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00540000" +) +# tri/kind1-id01 +NODE_55 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00010000" +) +# tri/kind1-id01-hi +NODE_56 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00510000" +) +# tri/kind2-id09 +NODE_57 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000900" +) +# tri/kind2-id09-hi +NODE_58 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00005900" +) +# tri/kind2-id06 +NODE_59 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000600" +) +# tri/kind2-id06-hi +NODE_60 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00005600" +) +# tri/kind2-id08 +NODE_61 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000800" +) +# tri/kind2-id08-hi +NODE_62 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00005800" +) +# tri/kind2-id02 +NODE_63 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000200" +) +# tri/kind2-id02-hi +NODE_64 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00005200" +) +# tri/kind2-id04 +NODE_65 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000400" +) +# tri/kind2-id04-hi +NODE_66 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00005400" +) +# tri/kind2-id01 +NODE_67 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000100" +) +# tri/kind2-id01-hi +NODE_68 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00005100" +) +# tri/kind3-id09 +NODE_69 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000009" +) +# tri/kind3-id09-hi +NODE_70 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000059" +) +# tri/kind3-id06 +NODE_71 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000006" +) +# tri/kind3-id06-hi +NODE_72 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000056" +) +# tri/kind3-id08 +NODE_73 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000008" +) +# tri/kind3-id08-hi +NODE_74 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000058" +) +# tri/kind3-id02 +NODE_75 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000002" +) +# tri/kind3-id02-hi +NODE_76 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000052" +) +# tri/kind3-id04 +NODE_77 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000004" +) +# tri/kind3-id04-hi +NODE_78 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000054" +) +# tri/kind3-id01 +NODE_79 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000001" +) +# tri/kind3-id01-hi +NODE_80 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000051" +) +# tri/kind0-hibits10 +NODE_81 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f19090909" +) +# tri/kind0-hibits80 +NODE_82 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f89090909" +) +# tri/kind0-hibitsf0 +NODE_83 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803ff9090909" +) +# tri/kind1-hibits10 +NODE_84 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f09190909" +) +# tri/kind1-hibits80 +NODE_85 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f09890909" +) +# tri/kind1-hibitsf0 +NODE_86 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f09f90909" +) +# tri/kind2-hibits10 +NODE_87 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f09091909" +) +# tri/kind2-hibits80 +NODE_88 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f09098909" +) +# tri/kind2-hibitsf0 +NODE_89 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f0909f909" +) +# tri/kind3-hibits10 +NODE_90 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f09090919" +) +# tri/kind3-hibits80 +NODE_91 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f09090989" +) +# tri/kind3-hibitsf0 +NODE_92 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f090909f9" +) +# tri/kind0-mal00 +NODE_93 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000000" +) +# tri/kind0-malff +NODE_94 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803fff000000" +) +# tri/kind1-malff +NODE_95 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00ff0000" +) +# tri/kind2-malff +NODE_96 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f0000ff00" +) +# tri/kind3-malff +NODE_97 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f000000ff" +) +# tri/kind0-nan +NODE_98 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000c07f00000000" + "0000803f00008040000080400000803f00000041000000000000803f09090909" +) +# tri/kind0-negzero-vertex +NODE_99 = bytes.fromhex( + "00000080000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f09090909" +) +# tri/kind0-x1024 +NODE_100 = bytes.fromhex( + "0000000000000000000080440000804500000000000080440000000000008045" + "0000804400008045000080450000804400000046000000000000804409090909" +) +# tri/kind0-div1024 +NODE_101 = bytes.fromhex( + "00000000000000000000803a0000803b000000000000803a000000000000803b" + "0000803a0000803b0000803b0000803a0000003c000000000000803a09090909" +) +# tri/kind0-degenerate +NODE_102 = bytes.fromhex( + "00000000000000000000803f0000803f000000000000803f0000004000000000" + "0000803f00004040000000000000803f00008040000000000000803f09090909" +) + +WITNESSES = [ + C("box32/four-sorted", NODE_0, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/reverse-sorted", NODE_0, D_SORT, 5, ((50.0, 0.0, 0.0), (-1.0, 0.0, 0.0), (-1.0, -inf, -inf), 1000000000.0,), (0x00000400, 0x00000304, 0x0000020c, 0x00000105,)), + C("box32/four-nosort", NODE_0, D_NOSORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/reverse-nosort", NODE_0, D_NOSORT, 5, ((50.0, 0.0, 0.0), (-1.0, 0.0, 0.0), (-1.0, -inf, -inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/extent-45", NODE_0, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 45.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/extent-35", NODE_0, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 35.0,), (0x00000105, 0x0000020c, 0x00000304, 0xffffffff,)), + C("box32/extent-25", NODE_0, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 25.0,), (0x00000105, 0x0000020c, 0xffffffff, 0xffffffff,)), + C("box32/extent-20", NODE_0, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 20.0,), (0x00000105, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/extent-19.999998", NODE_0, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 19.999998,), (0x00000105, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/extent-5", NODE_0, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 5.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/extent-0", NODE_0, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/extent--1", NODE_0, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), -1.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-10.5-0-e1e+09", NODE_0, D_SORT, 5, ((10.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/origin-10.5-0-e0.1", NODE_0, D_SORT, 5, ((10.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.1,), (0x00000105, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-10.5-0-e0", NODE_0, D_SORT, 5, ((10.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0x00000105, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-12.5-0-e1e+09", NODE_0, D_SORT, 5, ((12.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x0000020c, 0x00000304, 0x00000400, 0xffffffff,)), + C("box32/origin-12.5-0-e0.1", NODE_0, D_SORT, 5, ((12.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.1,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-12.5-0-e0", NODE_0, D_SORT, 5, ((12.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-35.5-0-e1e+09", NODE_0, D_SORT, 5, ((35.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000400, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-35.5-0-e0.1", NODE_0, D_SORT, 5, ((35.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.1,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-35.5-0-e0", NODE_0, D_SORT, 5, ((35.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-0-1-e1e+09", NODE_0, D_SORT, 5, ((0.0, 1.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-0-1-e0.1", NODE_0, D_SORT, 5, ((0.0, 1.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.1,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-0-1-e0", NODE_0, D_SORT, 5, ((0.0, 1.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-0--1-e1e+09", NODE_0, D_SORT, 5, ((0.0, -1.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/origin-0--1-e0.1", NODE_0, D_SORT, 5, ((0.0, -1.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.1,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-0--1-e0", NODE_0, D_SORT, 5, ((0.0, -1.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/tie-sorted", NODE_1, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/tie-nosort", NODE_1, D_NOSORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/tie-two-then-far", NODE_2, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/mixed-sorted", NODE_3, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x00000304, 0xffffffff, 0xffffffff,)), + C("box32/mixed-nosort", NODE_3, D_NOSORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0xffffffff, 0x00000304, 0xffffffff,)), + C("box32/zero-child-sorted", NODE_4, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000000, 0x00000105, 0x00000000, 0x00000304,)), + C("box32/zero-child-nosort", NODE_4, D_NOSORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000000, 0x00000105, 0x00000000, 0x00000304,)), + C("box32/overlap-sorted", NODE_5, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000400, 0x00000105, 0x0000020c, 0x00000304,)), + C("box32/overlap-nosort", NODE_5, D_NOSORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/3d-0.5-0.5", NODE_6, D_SORT, 5, ((0.0, 0.5, 0.5), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/3d-2.5-2.5", NODE_6, D_SORT, 5, ((0.0, 2.5, 2.5), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000400, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/3d-1.5-1.5", NODE_6, D_SORT, 5, ((0.0, 1.5, 1.5), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/behind-0-e1e+09", NODE_7, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x0000020c, 0x00000304, 0x00000400, 0xffffffff,)), + C("box32/behind-0-e0", NODE_7, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0x0000020c, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/behind-0-e5", NODE_7, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 5.0,), (0x0000020c, 0x00000304, 0xffffffff, 0xffffffff,)), + C("box32/behind-5-e1e+09", NODE_7, D_SORT, 5, ((5.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x0000020c, 0x00000304, 0x00000400, 0xffffffff,)), + C("box32/behind-5-e0", NODE_7, D_SORT, 5, ((5.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0x0000020c, 0x00000304, 0xffffffff, 0xffffffff,)), + C("box32/behind-5-e5", NODE_7, D_SORT, 5, ((5.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 5.0,), (0x0000020c, 0x00000304, 0xffffffff, 0xffffffff,)), + C("box32/behind--15-e1e+09", NODE_7, D_SORT, 5, ((-15.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/behind--15-e0", NODE_7, D_SORT, 5, ((-15.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0x00000105, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/behind--15-e5", NODE_7, D_SORT, 5, ((-15.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 5.0,), (0x00000105, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/zerodir-10.5-0", NODE_8, D_SORT, 5, ((10.5, 0.0, 0.0), (0.0, 1.0, 0.0), (inf, 1.0, inf), 100.0,), (0x00000105, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/zerodir-0-10.5", NODE_8, D_SORT, 5, ((0.0, 10.5, 0.0), (0.0, 1.0, 0.0), (inf, 1.0, inf), 100.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/zerodir-50-10.5", NODE_8, D_SORT, 5, ((50.0, 10.5, 0.0), (0.0, 1.0, 0.0), (inf, 1.0, inf), 100.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/negzero-y", NODE_1, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, -0.0, 0.0), (1.0, -inf, inf), 100.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/negzero-z", NODE_1, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, -0.0), (1.0, inf, -inf), 100.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/inverted", NODE_9, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x0000020c, 0x00000105, 0x00000304, 0x00000400,)), + C("box32/infinite-bounds", NODE_10, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x0000020c, 0x00000304, 0x00000105, 0x00000400,)), + C("box32/infinite-bounds-nosort", NODE_10, D_NOSORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/nan-min-disabled", NODE_11, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x0000020c, 0x00000304, 0x00000400, 0xffffffff,)), + C("box32/nan-max-convention", NODE_12, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/four-sorted", NODE_13, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/reverse-sorted", NODE_13, D_SORT, 4, ((50.0, 0.0, 0.0), (-1.0, 0.0, 0.0), (-1.0, -inf, -inf), 1000000000.0,), (0x00000400, 0x00000304, 0x0000020c, 0x00000105,)), + C("box16/four-nosort", NODE_13, D_NOSORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/reverse-nosort", NODE_13, D_NOSORT, 4, ((50.0, 0.0, 0.0), (-1.0, 0.0, 0.0), (-1.0, -inf, -inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/extent-45", NODE_13, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 45.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/extent-25", NODE_13, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 25.0,), (0x00000105, 0x0000020c, 0xffffffff, 0xffffffff,)), + C("box16/extent-20", NODE_13, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 20.0,), (0x00000105, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/extent-19.999998", NODE_13, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 19.999998,), (0x00000105, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/extent-5", NODE_13, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 5.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/extent-0", NODE_13, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/tie-sorted", NODE_14, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/tie-nosort", NODE_14, D_NOSORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/mixed-sorted", NODE_15, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x00000304, 0xffffffff, 0xffffffff,)), + C("box16/mixed-nosort", NODE_15, D_NOSORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0xffffffff, 0x00000304, 0xffffffff,)), + C("box16/zero-child-sorted", NODE_16, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000000, 0x00000105, 0x00000000, 0x00000304,)), + C("box16/zero-child-nosort", NODE_16, D_NOSORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000000, 0x00000105, 0x00000000, 0x00000304,)), + C("box16/round-low-e0", NODE_17, D_SORT, 4, ((0.09999000281095505, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/round-low-e0.001", NODE_17, D_SORT, 4, ((0.09999000281095505, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.001,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/round-low-e1", NODE_17, D_SORT, 4, ((0.09999000281095505, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/round-high-neg", NODE_18, D_SORT, 4, ((2.0998001098632812, 0.0, 0.0), (-1.0, 0.0, 0.0), (-1.0, -inf, -inf), 0.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/round-high-pos", NODE_18, D_SORT, 4, ((2.0998001098632812, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/subnormal-e1", NODE_19, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1.0,), (0x00000400, 0x00000105, 0x0000020c, 0xffffffff,)), + C("box16/subnormal-e0.00012207", NODE_19, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0001220703125,), (0x00000400, 0x00000105, 0x0000020c, 0xffffffff,)), + C("box16/subnormal-e0", NODE_19, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/65504-e10", NODE_20, D_SORT, 4, ((65500.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 10.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/65504-e4", NODE_20, D_SORT, 4, ((65500.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 4.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/65504-e3.9999998", NODE_20, D_SORT, 4, ((65500.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 3.9999998,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/infinite-bounds", NODE_21, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x0000020c, 0x00000304, 0x00000105, 0x00000400,)), + C("box16/infinite-bounds-nosort", NODE_21, D_NOSORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/nan-min-disabled", NODE_22, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x0000020c, 0x00000304, 0x00000400, 0xffffffff,)), + C("box16/negzero-0.0", NODE_23, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 10.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/negzero--0.0", NODE_23, D_SORT, 4, ((-0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 10.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/negzero-0.5", NODE_23, D_SORT, 4, ((0.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 10.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/negzero--1.0", NODE_23, D_SORT, 4, ((-1.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 10.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/scramble-sorted", NODE_24, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x0000020c, 0x00000400, 0x00000304, 0x00000105,)), + C("box32/scramble-nosort", NODE_24, D_NOSORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/scramble-sorted", NODE_25, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x0000020c, 0x00000400, 0x00000304, 0x00000105,)), + C("box16/scramble-nosort", NODE_25, D_NOSORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/pairs-sorted", NODE_26, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000304, 0x00000400, 0x00000105, 0x0000020c,)), + C("box32/pairs-nosort", NODE_26, D_NOSORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/pairs-sorted", NODE_27, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000304, 0x00000400, 0x00000105, 0x0000020c,)), + C("box16/pairs-nosort", NODE_27, D_NOSORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/interleaved-sorted", NODE_28, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x00000304, 0x0000020c, 0x00000400,)), + C("box32/interleaved-nosort", NODE_28, D_NOSORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/interleaved-sorted", NODE_29, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x00000304, 0x0000020c, 0x00000400,)), + C("box16/interleaved-nosort", NODE_29, D_NOSORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/all-tie-sorted", NODE_1, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/all-tie-nosort", NODE_1, D_NOSORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/all-tie-sorted", NODE_14, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/all-tie-nosort", NODE_14, D_NOSORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/3d-0.5-0.5", NODE_30, D_SORT, 4, ((0.0, 0.5, 0.5), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/3d-2.5-2.5", NODE_30, D_SORT, 4, ((0.0, 2.5, 2.5), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000400, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/3d-1.5-1.5", NODE_30, D_SORT, 4, ((0.0, 1.5, 1.5), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/inverted", NODE_31, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x0000020c, 0x00000105, 0x00000304, 0x00000400,)), + C("tri/kind0-center", NODE_32, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind1-center", NODE_32, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind2-center", NODE_32, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind3-center", NODE_32, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x40800000, 0x41a00000,)), + C("tri/kind0-edge-ac", NODE_32, D_SORT, 0, ((0.0, 2.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0x00000000, 0xc1000000,)), + C("tri/kind3-edge-ac", NODE_32, D_SORT, 3, ((0.0, 2.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x80000000, 0x41800000,)), + C("tri/kind0-vertex-a", NODE_32, D_SORT, 0, ((0.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0x00000000, 0x00000000,)), + C("tri/kind3-vertex-a", NODE_32, D_SORT, 3, ((0.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x00000000, 0x42000000,)), + C("tri/kind2-edge-ce", NODE_32, D_SORT, 2, ((4.0, 2.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x00000000, 0x41000000,)), + C("tri/kind0-outside", NODE_32, D_SORT, 0, ((5.0, 5.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind1-outside", NODE_32, D_SORT, 1, ((0.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind2-outside", NODE_32, D_SORT, 2, ((0.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind3-outside", NODE_32, D_SORT, 3, ((4.0, 4.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind0-id09", NODE_33, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind0-id09-hi", NODE_34, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind0-id06", NODE_35, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x40800000,)), + C("tri/kind0-id06-hi", NODE_36, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x40800000,)), + C("tri/kind0-id08", NODE_37, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind0-id08-hi", NODE_38, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind0-id02", NODE_39, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc1000000,)), + C("tri/kind0-id02-hi", NODE_40, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc1000000,)), + C("tri/kind0-id04", NODE_41, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind0-id04-hi", NODE_42, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind0-id01", NODE_43, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x41000000,)), + C("tri/kind0-id01-hi", NODE_44, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x41000000,)), + C("tri/kind1-id09", NODE_45, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind1-id09-hi", NODE_46, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind1-id06", NODE_47, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x41000000,)), + C("tri/kind1-id06-hi", NODE_48, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x41000000,)), + C("tri/kind1-id08", NODE_49, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x40800000,)), + C("tri/kind1-id08-hi", NODE_50, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x40800000,)), + C("tri/kind1-id02", NODE_51, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind1-id02-hi", NODE_52, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind1-id04", NODE_53, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc1000000,)), + C("tri/kind1-id04-hi", NODE_54, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc1000000,)), + C("tri/kind1-id01", NODE_55, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind1-id01-hi", NODE_56, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind2-id09", NODE_57, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind2-id09-hi", NODE_58, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind2-id06", NODE_59, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc1000000,)), + C("tri/kind2-id06-hi", NODE_60, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc1000000,)), + C("tri/kind2-id08", NODE_61, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind2-id08-hi", NODE_62, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind2-id02", NODE_63, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x40800000,)), + C("tri/kind2-id02-hi", NODE_64, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x40800000,)), + C("tri/kind2-id04", NODE_65, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x41000000,)), + C("tri/kind2-id04-hi", NODE_66, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x41000000,)), + C("tri/kind2-id01", NODE_67, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind2-id01-hi", NODE_68, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind3-id09", NODE_69, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x40800000, 0x41a00000,)), + C("tri/kind3-id09-hi", NODE_70, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x40800000, 0x41a00000,)), + C("tri/kind3-id06", NODE_71, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc2000000, 0xc2000000, 0xc1a00000, 0xc0800000,)), + C("tri/kind3-id06-hi", NODE_72, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc2000000, 0xc2000000, 0xc1a00000, 0xc0800000,)), + C("tri/kind3-id08", NODE_73, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc2000000, 0xc2000000, 0xc1000000, 0xc1a00000,)), + C("tri/kind3-id08-hi", NODE_74, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc2000000, 0xc2000000, 0xc1000000, 0xc1a00000,)), + C("tri/kind3-id02", NODE_75, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x41a00000, 0x41000000,)), + C("tri/kind3-id02-hi", NODE_76, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x41a00000, 0x41000000,)), + C("tri/kind3-id04", NODE_77, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x41000000, 0x40800000,)), + C("tri/kind3-id04-hi", NODE_78, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x41000000, 0x40800000,)), + C("tri/kind3-id01", NODE_79, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc2000000, 0xc2000000, 0xc0800000, 0xc1000000,)), + C("tri/kind3-id01-hi", NODE_80, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc2000000, 0xc2000000, 0xc0800000, 0xc1000000,)), + C("tri/kind0-hibits10", NODE_81, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind0-hibits80", NODE_82, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind0-hibitsf0", NODE_83, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind1-hibits10", NODE_84, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind1-hibits80", NODE_85, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind1-hibitsf0", NODE_86, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind2-hibits10", NODE_87, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind2-hibits80", NODE_88, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind2-hibitsf0", NODE_89, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind3-hibits10", NODE_90, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x40800000, 0x41a00000,)), + C("tri/kind3-hibits80", NODE_91, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x40800000, 0x41a00000,)), + C("tri/kind3-hibitsf0", NODE_92, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x40800000, 0x41a00000,)), + C("tri/kind0-mal00", NODE_93, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind0-malff", NODE_94, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind1-mal00", NODE_93, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind1-malff", NODE_95, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind2-mal00", NODE_93, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind2-malff", NODE_96, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind3-mal00", NODE_93, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind3-malff", NODE_97, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind0-nan", NODE_98, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind1-nan", NODE_98, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind2-nan", NODE_98, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind3-nan", NODE_98, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind0-negzero-vertex", NODE_99, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind3-negzero-vertex", NODE_99, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x40800000, 0x41a00000,)), + C("tri/kind0-zerodir", NODE_32, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 0.0), (inf, inf, inf), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind1-zerodir", NODE_32, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 0.0), (inf, inf, inf), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind2-zerodir", NODE_32, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 0.0), (inf, inf, inf), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind3-zerodir", NODE_32, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 0.0), (inf, inf, inf), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind0-negzero-dir", NODE_32, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, -0.0, 1.0), (0.0, -inf, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind3-negzero-dir", NODE_32, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, -0.0, 1.0), (0.0, -inf, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x40800000, 0x41a00000,)), + C("tri/kind0-behind", NODE_32, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, -1.0), (0.0, 0.0, -1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind1-behind", NODE_32, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, -1.0), (0.0, 0.0, -1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind2-behind", NODE_32, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, -1.0), (0.0, 0.0, -1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind3-behind", NODE_32, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, -1.0), (0.0, 0.0, -1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind0-t0", NODE_32, D_SORT, 0, ((1.0, 1.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x80000000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind1-t0", NODE_32, D_SORT, 1, ((3.0, 3.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x80000000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind2-t0", NODE_32, D_SORT, 2, ((4.0, 3.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x00000000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind3-t0", NODE_32, D_SORT, 3, ((1.0, 1.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x00000000, 0x42000000, 0x40800000, 0x41a00000,)), + C("tri/kind0-extent0", NODE_32, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 0.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind1-extent0", NODE_32, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 0.0,), (0xc1800000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind2-extent0", NODE_32, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 0.0,), (0x41800000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind3-extent0", NODE_32, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 0.0,), (0x42000000, 0x42000000, 0x40800000, 0x41a00000,)), + C("tri/kind0-x1024", NODE_100, D_SORT, 0, ((1024.0, 1024.0, 0.0), (0.0, 0.0, 1024.0), (0.0, 0.0, 0.0009765625), 1000000000.0,), (0xcb800000, 0xcb800000, 0xca800000, 0xca800000,)), + C("tri/kind1-x1024", NODE_100, D_SORT, 1, ((3072.0, 3072.0, 0.0), (0.0, 0.0, 1024.0), (0.0, 0.0, 0.0009765625), 1000000000.0,), (0xcb800000, 0xcb800000, 0xcb000000, 0xca800000,)), + C("tri/kind2-x1024", NODE_100, D_SORT, 2, ((4096.0, 3072.0, 0.0), (0.0, 0.0, 1024.0), (0.0, 0.0, 0.0009765625), 1000000000.0,), (0x4b800000, 0x4b800000, 0x4b000000, 0x4a800000,)), + C("tri/kind3-x1024", NODE_100, D_SORT, 3, ((1024.0, 1024.0, 0.0), (0.0, 0.0, 1024.0), (0.0, 0.0, 0.0009765625), 1000000000.0,), (0x4c000000, 0x4c000000, 0x4a800000, 0x4ba00000,)), + C("tri/kind0-div1024", NODE_101, D_SORT, 0, ((0.0009765625, 0.0009765625, 0.0), (0.0, 0.0, 0.0009765625), (0.0, 0.0, 1024.0), 1000000000.0,), (0xb7800000, 0xb7800000, 0xb6800000, 0xb6800000,)), + C("tri/kind1-div1024", NODE_101, D_SORT, 1, ((0.0029296875, 0.0029296875, 0.0), (0.0, 0.0, 0.0009765625), (0.0, 0.0, 1024.0), 1000000000.0,), (0xb7800000, 0xb7800000, 0xb7000000, 0xb6800000,)), + C("tri/kind2-div1024", NODE_101, D_SORT, 2, ((0.00390625, 0.0029296875, 0.0), (0.0, 0.0, 0.0009765625), (0.0, 0.0, 1024.0), 1000000000.0,), (0x37800000, 0x37800000, 0x37000000, 0x36800000,)), + C("tri/kind3-div1024", NODE_101, D_SORT, 3, ((0.0009765625, 0.0009765625, 0.0), (0.0, 0.0, 0.0009765625), (0.0, 0.0, 1024.0), 1000000000.0,), (0x38000000, 0x38000000, 0x36800000, 0x37a00000,)), + C("tri/kind0-degenerate", NODE_102, D_SORT, 0, ((0.5, 0.5, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind1-degenerate", NODE_102, D_SORT, 1, ((0.5, 0.5, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind2-degenerate", NODE_102, D_SORT, 2, ((0.5, 0.5, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind3-degenerate", NODE_102, D_SORT, 3, ((0.5, 0.5, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind6-notriangle", NODE_32, D_SORT, 6, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind7-notriangle", NODE_32, D_SORT, 7, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), +] + +POINTER_WITNESSES = [ + P("ptr/base0-0-k0", bvh_model.descriptor(0x0), 0x0, False, (0, 0x0)), + P("ptr/base0-0-k1", bvh_model.descriptor(0x0), 0x1, False, (1, 0x0)), + P("ptr/base0-0-k2", bvh_model.descriptor(0x0), 0x2, False, (2, 0x0)), + P("ptr/base0-0-k3", bvh_model.descriptor(0x0), 0x3, False, (3, 0x0)), + P("ptr/base0-0-k4", bvh_model.descriptor(0x0), 0x4, False, (4, 0x0)), + P("ptr/base0-0-k5", bvh_model.descriptor(0x0), 0x5, False, (5, 0x0)), + P("ptr/base0-0-k6", bvh_model.descriptor(0x0), 0x6, False, (6, 0x0)), + P("ptr/base0-0-k7", bvh_model.descriptor(0x0), 0x7, False, (7, 0x0)), + P("ptr/base0-64-k0", bvh_model.descriptor(0x0), 0x8, False, (0, 0x40)), + P("ptr/base0-64-k1", bvh_model.descriptor(0x0), 0x9, False, (1, 0x40)), + P("ptr/base0-64-k2", bvh_model.descriptor(0x0), 0xa, False, (2, 0x40)), + P("ptr/base0-64-k3", bvh_model.descriptor(0x0), 0xb, False, (3, 0x40)), + P("ptr/base0-64-k4", bvh_model.descriptor(0x0), 0xc, False, (4, 0x40)), + P("ptr/base0-64-k5", bvh_model.descriptor(0x0), 0xd, False, (5, 0x40)), + P("ptr/base0-64-k6", bvh_model.descriptor(0x0), 0xe, False, (6, 0x40)), + P("ptr/base0-64-k7", bvh_model.descriptor(0x0), 0xf, False, (7, 0x40)), + P("ptr/base0-128-k0", bvh_model.descriptor(0x0), 0x10, False, (0, 0x80)), + P("ptr/base0-128-k1", bvh_model.descriptor(0x0), 0x11, False, (1, 0x80)), + P("ptr/base0-128-k2", bvh_model.descriptor(0x0), 0x12, False, (2, 0x80)), + P("ptr/base0-128-k3", bvh_model.descriptor(0x0), 0x13, False, (3, 0x80)), + P("ptr/base0-128-k4", bvh_model.descriptor(0x0), 0x14, False, (4, 0x80)), + P("ptr/base0-128-k5", bvh_model.descriptor(0x0), 0x15, False, (5, 0x80)), + P("ptr/base0-128-k6", bvh_model.descriptor(0x0), 0x16, False, (6, 0x80)), + P("ptr/base0-128-k7", bvh_model.descriptor(0x0), 0x17, False, (7, 0x80)), + P("ptr/base0-192-k0", bvh_model.descriptor(0x0), 0x18, False, (0, 0xc0)), + P("ptr/base0-192-k1", bvh_model.descriptor(0x0), 0x19, False, (1, 0xc0)), + P("ptr/base0-192-k2", bvh_model.descriptor(0x0), 0x1a, False, (2, 0xc0)), + P("ptr/base0-192-k3", bvh_model.descriptor(0x0), 0x1b, False, (3, 0xc0)), + P("ptr/base0-192-k4", bvh_model.descriptor(0x0), 0x1c, False, (4, 0xc0)), + P("ptr/base0-192-k5", bvh_model.descriptor(0x0), 0x1d, False, (5, 0xc0)), + P("ptr/base0-192-k6", bvh_model.descriptor(0x0), 0x1e, False, (6, 0xc0)), + P("ptr/base0-192-k7", bvh_model.descriptor(0x0), 0x1f, False, (7, 0xc0)), + P("ptr/base0-256-k0", bvh_model.descriptor(0x0), 0x20, False, (0, 0x100)), + P("ptr/base0-256-k1", bvh_model.descriptor(0x0), 0x21, False, (1, 0x100)), + P("ptr/base0-256-k2", bvh_model.descriptor(0x0), 0x22, False, (2, 0x100)), + P("ptr/base0-256-k3", bvh_model.descriptor(0x0), 0x23, False, (3, 0x100)), + P("ptr/base0-256-k4", bvh_model.descriptor(0x0), 0x24, False, (4, 0x100)), + P("ptr/base0-256-k5", bvh_model.descriptor(0x0), 0x25, False, (5, 0x100)), + P("ptr/base0-256-k6", bvh_model.descriptor(0x0), 0x26, False, (6, 0x100)), + P("ptr/base0-256-k7", bvh_model.descriptor(0x0), 0x27, False, (7, 0x100)), + P("ptr/base0-448-k0", bvh_model.descriptor(0x0), 0x38, False, (0, 0x1c0)), + P("ptr/base0-448-k1", bvh_model.descriptor(0x0), 0x39, False, (1, 0x1c0)), + P("ptr/base0-448-k2", bvh_model.descriptor(0x0), 0x3a, False, (2, 0x1c0)), + P("ptr/base0-448-k3", bvh_model.descriptor(0x0), 0x3b, False, (3, 0x1c0)), + P("ptr/base0-448-k4", bvh_model.descriptor(0x0), 0x3c, False, (4, 0x1c0)), + P("ptr/base0-448-k5", bvh_model.descriptor(0x0), 0x3d, False, (5, 0x1c0)), + P("ptr/base0-448-k6", bvh_model.descriptor(0x0), 0x3e, False, (6, 0x1c0)), + P("ptr/base0-448-k7", bvh_model.descriptor(0x0), 0x3f, False, (7, 0x1c0)), + P("ptr/base40-0-k0", bvh_model.descriptor(0x4000), 0x0, False, (0, 0x4000)), + P("ptr/base40-0-k5", bvh_model.descriptor(0x4000), 0x5, False, (5, 0x4000)), + P("ptr/base40-0-k7", bvh_model.descriptor(0x4000), 0x7, False, (7, 0x4000)), + P("ptr/base40-64-k0", bvh_model.descriptor(0x4000), 0x8, False, (0, 0x4040)), + P("ptr/base40-64-k5", bvh_model.descriptor(0x4000), 0xd, False, (5, 0x4040)), + P("ptr/base40-64-k7", bvh_model.descriptor(0x4000), 0xf, False, (7, 0x4040)), + P("ptr/base40-256-k0", bvh_model.descriptor(0x4000), 0x20, False, (0, 0x4100)), + P("ptr/base40-256-k5", bvh_model.descriptor(0x4000), 0x25, False, (5, 0x4100)), + P("ptr/base40-256-k7", bvh_model.descriptor(0x4000), 0x27, False, (7, 0x4100)), + P("ptr/highbase-0-k0", bvh_model.descriptor(0x1234567800), 0x0, False, (0, 0x1234567800)), + P("ptr/highbase-0-k4", bvh_model.descriptor(0x1234567800), 0x4, False, (4, 0x1234567800)), + P("ptr/highbase-0-k5", bvh_model.descriptor(0x1234567800), 0x5, False, (5, 0x1234567800)), + P("ptr/highbase-64-k0", bvh_model.descriptor(0x1234567800), 0x8, False, (0, 0x1234567840)), + P("ptr/highbase-64-k4", bvh_model.descriptor(0x1234567800), 0xc, False, (4, 0x1234567840)), + P("ptr/highbase-64-k5", bvh_model.descriptor(0x1234567800), 0xd, False, (5, 0x1234567840)), + P("ptr/highbase-4096-k0", bvh_model.descriptor(0x1234567800), 0x200, False, (0, 0x1234568800)), + P("ptr/highbase-4096-k4", bvh_model.descriptor(0x1234567800), 0x204, False, (4, 0x1234568800)), + P("ptr/highbase-4096-k5", bvh_model.descriptor(0x1234567800), 0x205, False, (5, 0x1234568800)), + P("ptr/wrap-100", bvh_model.descriptor(0xffffffffff00), 0x25, False, (5, 0x0)), + P("ptr/wrap-80", bvh_model.descriptor(0xffffffffff00), 0x14, False, (4, 0xffffffffff80)), + P("ptr/wide-0-k0", bvh_model.descriptor(0x0), 0x0, True, (0, 0x0)), + P("ptr/wide-0-k5", bvh_model.descriptor(0x0), 0x5, True, (5, 0x0)), + P("ptr/wide-0-k7", bvh_model.descriptor(0x0), 0x7, True, (7, 0x0)), + P("ptr/wide-40-k0", bvh_model.descriptor(0x0), 0x8, True, (0, 0x40)), + P("ptr/wide-40-k5", bvh_model.descriptor(0x0), 0xd, True, (5, 0x40)), + P("ptr/wide-40-k7", bvh_model.descriptor(0x0), 0xf, True, (7, 0x40)), + P("ptr/wide-1000-k0", bvh_model.descriptor(0x0), 0x200, True, (0, 0x1000)), + P("ptr/wide-1000-k5", bvh_model.descriptor(0x0), 0x205, True, (5, 0x1000)), + P("ptr/wide-1000-k7", bvh_model.descriptor(0x0), 0x207, True, (7, 0x1000)), + P("ptr/wide-1234567800-k0", bvh_model.descriptor(0x0), 0x2468acf00, True, (0, 0x1234567800)), + P("ptr/wide-1234567800-k5", bvh_model.descriptor(0x0), 0x2468acf05, True, (5, 0x1234567800)), + P("ptr/wide-1234567800-k7", bvh_model.descriptor(0x0), 0x2468acf07, True, (7, 0x1234567800)), + P("ptr/wide-ffffffffffffffc0-k0", bvh_model.descriptor(0x0), 0x1ffffffffffffff8, True, (0, 0xffffffffffffffc0)), + P("ptr/wide-ffffffffffffffc0-k5", bvh_model.descriptor(0x0), 0x1ffffffffffffffd, True, (5, 0xffffffffffffffc0)), + P("ptr/wide-ffffffffffffffc0-k7", bvh_model.descriptor(0x0), 0x1fffffffffffffff, True, (7, 0xffffffffffffffc0)), + P("ptr/wide-ignores-base", bvh_model.descriptor(0x1234567800), 0x205, True, (5, 0x1000)), +] + + def descriptor_for(base, wide): # Absolute typed pointers use base zero and the full 42-bit node-count field. # Relative pointers are constructed only for the two nodes in this allocation. @@ -193,13 +1107,14 @@ def main(): parser.add_argument("--model-only", action="store_true") args = parser.parse_args() model_check() + failures = witness_check() if args.model_only: - return 0 + return int(failures != 0) if any(key.startswith("HSA_OVERRIDE_GFX_VERSION") for key in os.environ): parser.error("Unset HSA_OVERRIDE_GFX_VERSION before measuring native behavior") if not OBJECT.is_file(): parser.error("Build the gfx1030 code object with sh tests/gfx1030_bvh_box/build.sh") - return run(args.library, args.device) + return int(run(args.library, args.device) + failures != 0) if __name__ == "__main__": diff --git a/tests/host_commit_unit_check.py b/tests/host_commit_unit_check.py new file mode 100644 index 0000000000..2de69aa701 --- /dev/null +++ b/tests/host_commit_unit_check.py @@ -0,0 +1,239 @@ +"""Pure-Python unit, boundary, mocked WinAPI, and temp-copy mutation suite for tools/host_commit.py.""" + +import ctypes +import importlib.util +from pathlib import Path +import sys +from tempfile import TemporaryDirectory +from types import MappingProxyType +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +MODULE_PATH = ROOT / "tools" / "host_commit.py" +sys.path.insert(0, str(ROOT / "tools")) + +import host_commit # noqa: E402 + + +MUTATIONS = ( + ( + "drop_is_int_bool_guard", + " return isinstance(value, int) and not isinstance(value, bool)\n", + " return isinstance(value, int)\n", + ), + ( + "drop_used_pages_nonneg_guard", + " if not _is_int(used_pages) or used_pages < 0:\n", + " if False:\n", + ), + ( + "drop_snapshot_mapping_guard", + " if not isinstance(snapshot, Mapping):\n", + " if False:\n", + ), + ( + "drop_snapshot_field_validation", + " for key in _SNAPSHOT_KEYS:\n", + " for key in ():\n", + ), + ( + "drop_free_bytes_clamp", + " free_bytes = max(limit_bytes - used_bytes, 0)\n", + " free_bytes = limit_bytes - used_bytes\n", + ), + ( + "drop_winmode_800", + ' psapi = C.WinDLL("psapi.dll", winmode=0x800, use_last_error=True)\n', + ' psapi = C.WinDLL("psapi.dll", use_last_error=True)\n', + ), +) + + +class _FakeGetPerformanceInfo: + def __init__(self, *, limit=1024, used=256, page_size=65536, success=True): + self.limit = limit + self.used = used + self.page_size = page_size + self.success = success + self.argtypes = None + self.restype = None + self.calls = [] + + def __call__(self, ptr, cb_size, struct_cls): + info = ctypes.cast(ptr, ctypes.POINTER(struct_cls)).contents + self.calls.append((info.cb, cb_size)) + if self.success: + info.CommitLimit = self.limit + info.CommitTotal = self.used + info.PageSize = self.page_size + return int(self.success) + + +def _load_temp_module(path: Path, name: str): + spec = importlib.util.spec_from_file_location(name, path) + if spec is None or spec.loader is None: + raise AssertionError(f"could not create module spec for {path}") + mod = importlib.util.module_from_spec(spec) + sys.modules[name] = mod + try: + spec.loader.exec_module(mod) + except Exception: + sys.modules.pop(name, None) + raise + return mod + + +class HostCommitUnitTests(unittest.TestCase): + def _verify_module_contract(self, mod) -> None: + mib = mod.MIB + self.assertEqual(mib, 1 << 20) + + # Exact MiB math and 0-used floor. + self.assertEqual( + mod.snapshot_from_pages(64, 0, mib), + {"limit_mib": 64, "used_mib": 0, "available_mib": 64, "available_bytes": 64 * mib}, + ) + self.assertEqual( + mod.snapshot_from_pages(256, 128, 4096), + {"limit_mib": 1, "used_mib": 0, "available_mib": 0, "available_bytes": 128 * 4096}, + ) + self.assertEqual( + mod.snapshot_from_pages(100, 100, 65536), + {"limit_mib": (100 * 65536) // mib, "used_mib": (100 * 65536) // mib, + "available_mib": 0, "available_bytes": 0}, + ) + + # Clamping when used_pages > limit_pages. + clamped = mod.snapshot_from_pages(2, 5, mib) + self.assertEqual( + clamped, + {"limit_mib": 2, "used_mib": 5, "available_mib": 0, "available_bytes": 0}, + ) + + # Bool / non-int / negative / zero refusals in snapshot_from_pages. + for bad_args in ( + (True, 0, 4096), + (False, 0, 4096), + (10, True, 4096), + (10, False, 4096), + (10, 0, True), + (10, 0, False), + (0, 0, 4096), + (-1, 0, 4096), + (10, 0, 0), + (10, 0, -4096), + (10, -1, 4096), + ("10", 0, 4096), + (10.0, 0, 4096), + (10, 0.5, 4096), + (10, 0, 4096.0), + (None, 0, 4096), + ): + with self.assertRaises(ValueError, msg=f"args={bad_args!r}"): + mod.snapshot_from_pages(*bad_args) + + # Budget boundary checks (exact pass, 1-byte-short fail, max cap). + snap = mod.snapshot_from_pages(10, 4, mib) + self.assertEqual( + mod.require_commit_budget(6, snap), + {"limit_mib": 10, "used_mib": 4, "available_mib": 6, + "minimum_mib": 6, "meets_minimum": True}, + ) + self.assertEqual(mod.require_commit_budget(0, MappingProxyType(snap))["meets_minimum"], True) + + one_short = dict(snap, available_bytes=6 * mib - 1) + with self.assertRaises(ValueError): + mod.require_commit_budget(6, one_short) + + huge = mod.snapshot_from_pages((1 << 20) + 1, 0, mib) + self.assertEqual(mod.require_commit_budget(1 << 20, huge)["minimum_mib"], 1 << 20) + with self.assertRaises(ValueError): + mod.require_commit_budget((1 << 20) + 1, huge) + + # Reject bool/non-int/out-of-range minimum_mib. + for bad_min in (True, False, -1, (1 << 20) + 1, "6", 6.0, None): + with self.assertRaises(ValueError, msg=f"minimum_mib={bad_min!r}"): + mod.require_commit_budget(bad_min, snap) + + # Reject non-Mapping snapshot, missing keys, and bool/non-int/negative fields. + for bad_snap in (None, [], (), "snapshot", 42, [0, 0, 0, 0]): + with self.assertRaises(ValueError, msg=f"snapshot={bad_snap!r}"): + mod.require_commit_budget(0, bad_snap) + + required = ("available_bytes", "limit_mib", "used_mib", "available_mib") + for missing_key in required: + partial = {k: v for k, v in snap.items() if k != missing_key} + with self.assertRaises(ValueError, msg=f"missing={missing_key}"): + mod.require_commit_budget(0, partial) + + for key in required: + for bad_val in (True, False, -1, "1", 1.5, None): + bad_row = dict(snap) + bad_row[key] = bad_val + with self.assertRaises(ValueError, msg=f"{key}={bad_val!r}"): + mod.require_commit_budget(0, bad_row) + + # Mocked read_host_commit success, GetPerformanceInfo==0, and non-win32 OSError. + fake = _FakeGetPerformanceInfo(limit=512, used=128, page_size=65536, success=True) + + def call_success(ptr, cb_size): + return fake(ptr, cb_size, mod.PerformanceInformation) + + with patch.object(mod.sys, "platform", "win32"), \ + patch.object(mod.C, "WinDLL", create=True) as win_dll: + win_dll.return_value.GetPerformanceInfo = call_success + got = mod.read_host_commit() + win_dll.assert_called_once_with("psapi.dll", winmode=0x800, use_last_error=True) + expected_cb = ctypes.sizeof(mod.PerformanceInformation) + self.assertEqual(fake.calls, [(expected_cb, expected_cb)]) + self.assertEqual( + got, + {"limit_mib": (512 * 65536) // mib, "used_mib": (128 * 65536) // mib, + "available_mib": (384 * 65536) // mib, "available_bytes": 384 * 65536}, + ) + + fake_fail = _FakeGetPerformanceInfo(success=False) + + def call_fail(ptr, cb_size): + return fake_fail(ptr, cb_size, mod.PerformanceInformation) + + with patch.object(mod.sys, "platform", "win32"), \ + patch.object(mod.C, "WinDLL", create=True) as win_dll, \ + patch.object(mod.C, "get_last_error", create=True, return_value=87): + win_dll.return_value.GetPerformanceInfo = call_fail + with self.assertRaises(OSError) as raised: + mod.read_host_commit() + self.assertEqual(raised.exception.errno, 87) + + for non_win in ("linux", "darwin"): + with patch.object(mod.sys, "platform", non_win): + with self.assertRaises(OSError): + mod.read_host_commit() + + def test_contract_and_boundaries(self) -> None: + self._verify_module_contract(host_commit) + + def test_fast_temp_copy_mutations(self) -> None: + source = MODULE_PATH.read_text(encoding="utf-8") + with TemporaryDirectory() as tmp: + tmp_dir = Path(tmp) + for label, target, replacement in MUTATIONS: + with self.subTest(mutation=label): + self.assertEqual(source.count(target), 1, target) + mut_path = tmp_dir / f"host_commit_{label}.py" + mut_path.write_text(source.replace(target, replacement, 1), encoding="utf-8") + mod_name = f"host_commit_mut_{label}" + mod = _load_temp_module(mut_path, mod_name) + try: + with self.assertRaises( + (AssertionError, AttributeError, KeyError, TypeError), + msg=f"mutation {label} escaped detection", + ): + self._verify_module_contract(mod) + finally: + sys.modules.pop(mod_name, None) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/import_routing_check.py b/tests/import_routing_check.py new file mode 100644 index 0000000000..c945f8b35a --- /dev/null +++ b/tests/import_routing_check.py @@ -0,0 +1,245 @@ +"""Unit, boundary-validation, and temp-copy mutation suite for tools/import_routing.py.""" + +from collections import UserDict +import importlib.util +from pathlib import Path +import sys +from tempfile import TemporaryDirectory +from types import MappingProxyType +import unittest + +ROOT = Path(__file__).resolve().parents[1] +MODULE_PATH = ROOT / "tools" / "import_routing.py" +sys.path.insert(0, str(ROOT / "tools")) + +import import_routing # noqa: E402 + + +MUTATIONS = ( + ( + "drop_non_str_guard", + ' if not isinstance(module, str):\n' + ' raise ValueError(f"module name must be a str, got {type(module).__name__}")\n', + ' if False:\n' + ' raise ValueError(f"module name must be a str, got {type(module).__name__}")\n', + ), + ( + "drop_empty_whitespace_control_guard", + ' if not module or any(ch.isspace() or ord(ch) < 0x20 or 0x7F <= ord(ch) <= 0x9F for ch in module):\n' + ' raise ValueError(f"invalid module name: {module!r}")\n', + ' if False:\n' + ' raise ValueError(f"invalid module name: {module!r}")\n', + ), + ( + "drop_mutable_mapping_guard", + ' if not isinstance(row, MutableMapping):\n' + ' raise TypeError(f"row must be a MutableMapping, got {type(row).__name__}")\n', + ' if False:\n' + ' raise TypeError(f"row must be a MutableMapping, got {type(row).__name__}")\n', + ), + ( + "drop_lower_normalization", + " name = module.lower()\n", + " name = module\n", + ), + ( + "substring_api_set_prefix", + " if name.startswith(prefix):\n", + " if prefix in name:\n", + ), + ( + "lowercase_candidate_provider", + ' "candidate_provider": module if route == "hle" else None,\n', + ' "candidate_provider": module.lower() if route == "hle" else None,\n', + ), +) + + +def _load_temp_module(path: Path, name: str): + spec = importlib.util.spec_from_file_location(name, path) + if spec is None or spec.loader is None: + raise AssertionError(f"could not create module spec for {path}") + mod = importlib.util.module_from_spec(spec) + sys.modules[name] = mod + try: + spec.loader.exec_module(mod) + except Exception: + sys.modules.pop(name, None) + raise + return mod + + +class ImportRoutingTests(unittest.TestCase): + def _verify_module_contract(self, mod) -> None: + self.assertEqual(mod.POLICY_VERSION, 2) + self.assertEqual(mod.ROUTE_KIND, "candidate") + self.assertEqual(mod.RESOLUTION, "not_checked") + self.assertEqual(mod.ROUTES, ("hle", "windows", "stub", "unsupported")) + + # All 4 policy routes and mixed-case normalization. + for name, expected_route in ( + ("xmem.dll", "hle"), + ("XMem.DLL", "hle"), + ("d3d12_xs.dll", "hle"), + ("D3D12_Xs.Dll", "hle"), + ("xgameruntime.dll", "stub"), + ("XGameRuntime.DLL", "stub"), + ("xg_xs.dll", "stub"), + ("XG_XS.dll", "stub"), + ("kernel32.dll", "windows"), + ("Kernel32.DLL", "windows"), + ("ntdll.dll", "windows"), + ("xaudio2_8.dll", "windows"), + ("XAudio2_9.DLL", "windows"), + ("gameinput.dll", "windows"), + ("mystery.dll", "unsupported"), + ("Mystery.DLL", "unsupported"), + ("winhttp2.dll", "unsupported"), + ("my-api-ms-win-core.dll", "unsupported"), + ("not-ext-ms-core.dll", "unsupported"), + ): + route, reason = mod.classify(name) + self.assertEqual(route, expected_route, name) + self.assertIsInstance(reason, str) + self.assertTrue(reason) + + # Prefix routes preserve contract reason across mixed case. + for prefix_name in ( + "api-ms-win-core-file-l1-1-0.dll", + "API-MS-WIN-CORE-SYNCH-L1-2-0.DLL", + "ext-ms-win-ntuser-window-l1-1-0.dll", + "EXT-MS-ONECORE-TEST-L1-1-0.DLL", + ): + self.assertEqual( + mod.classify(prefix_name), + ("windows", "Windows API-set contract"), + prefix_name, + ) + + # Invalid module names must raise ValueError (never AttributeError or 'unsupported'). + for bad_module in ( + None, + 123, + True, + b"xmem.dll", + bytearray(b"xmem.dll"), + ["xmem.dll"], + {"module": "xmem.dll"}, + "", + " ", + "\t\n\r", + "\u00a0", + " xmem.dll", + "xmem.dll ", + "x mem.dll", + "kernel32\t.dll", + "\x00", + "xmem\x00.dll", + "xmem\x1f.dll", + "xmem\x7f.dll", + "xmem\x85.dll", + "xmem\x9f.dll", + ): + with self.assertRaises(ValueError, msg=f"module={bad_module!r}"): + mod.classify(bad_module) + + # annotate() requires a MutableMapping containing module_key before mutating. + for bad_row, key in ( + (None, "module"), + (123, "module"), + ("xmem.dll", "module"), + (["xmem.dll"], 0), + (("xmem.dll",), 0), + (MappingProxyType({"module": "xmem.dll"}), "module"), + ): + with self.assertRaises(TypeError, msg=f"row={bad_row!r}"): + mod.annotate(bad_row, module_key=key) + + missing_row = {"dll": "xmem.dll", "caller": "app.exe"} + with self.assertRaises(KeyError): + mod.annotate(missing_row) + self.assertEqual(missing_row, {"dll": "xmem.dll", "caller": "app.exe"}) + + for invalid_val in ("", None, " bad.dll", "bad\x00.dll"): + untouched = {"module": invalid_val, "caller": "app.exe", "symbol": "Sym"} + snapshot = dict(untouched) + with self.assertRaises(ValueError): + mod.annotate(untouched) + self.assertEqual(untouched, snapshot) + + # annotate() preserves caller keys, return schema, and original casing for HLE candidate_provider. + hle_row = {"image": "app.exe", "kind": "normal", "dll": "XMem.DLL", "symbol": "XMemAlloc", "extra": 42} + ret = mod.annotate(hle_row, module_key="dll") + self.assertIs(ret, hle_row) + self.assertEqual( + hle_row, + { + "image": "app.exe", + "kind": "normal", + "dll": "XMem.DLL", + "symbol": "XMemAlloc", + "extra": 42, + "route": "hle", + "reason": mod.POLICY["hle"]["xmem.dll"], + "route_kind": mod.ROUTE_KIND, + "resolution": mod.RESOLUTION, + "provider": None, + "stub": False, + "candidate_provider": "XMem.DLL", + }, + ) + + stub_row = UserDict({"module": "XGameRuntime.DLL", "symbol": "XUserGetId"}) + ret_stub = mod.annotate(stub_row) + self.assertIs(ret_stub, stub_row) + self.assertEqual(stub_row["route"], "stub") + self.assertTrue(stub_row["stub"]) + self.assertIsNone(stub_row["candidate_provider"]) + self.assertIsNone(stub_row["provider"]) + self.assertEqual(stub_row["symbol"], "XUserGetId") + + win_row = {"module": "API-MS-WIN-CORE-FILE-L1-1-0.DLL", "caller": "app.exe"} + mod.annotate(win_row) + self.assertEqual(win_row["route"], "windows") + self.assertFalse(win_row["stub"]) + self.assertIsNone(win_row["candidate_provider"]) + + unsup_row = {"module": "Mystery.DLL", "caller": "app.exe"} + mod.annotate(unsup_row) + self.assertEqual(unsup_row["route"], "unsupported") + self.assertFalse(unsup_row["stub"]) + self.assertIsNone(unsup_row["candidate_provider"]) + + def test_contract_and_policy_coverage(self) -> None: + self._verify_module_contract(import_routing) + + for mod_name, reason in import_routing.POLICY["hle"].items(): + self.assertEqual(import_routing.classify(mod_name), ("hle", reason)) + for mod_name, reason in import_routing.POLICY["stub"].items(): + self.assertEqual(import_routing.classify(mod_name), ("stub", reason)) + for mod_name in import_routing.POLICY["windows"]: + self.assertEqual(import_routing.classify(mod_name), ("windows", "Windows system DLL")) + + def test_fast_temp_copy_mutations(self) -> None: + source = MODULE_PATH.read_text(encoding="utf-8") + with TemporaryDirectory() as tmp: + tmp_dir = Path(tmp) + for label, target, replacement in MUTATIONS: + with self.subTest(mutation=label): + self.assertEqual(source.count(target), 1, target) + mut_path = tmp_dir / f"import_routing_{label}.py" + mut_path.write_text(source.replace(target, replacement, 1), encoding="utf-8") + mod_name = f"import_routing_mut_{label}" + mod = _load_temp_module(mut_path, mod_name) + try: + with self.assertRaises( + (AssertionError, AttributeError, KeyError, TypeError), + msg=f"mutation {label} escaped detection", + ): + self._verify_module_contract(mod) + finally: + sys.modules.pop(mod_name, None) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/native_compute_clear_check.py b/tests/native_compute_clear_check.py index e703513b0c..f619876622 100644 --- a/tests/native_compute_clear_check.py +++ b/tests/native_compute_clear_check.py @@ -13,7 +13,7 @@ def write_request(work, words, root, sa=None): sa = struct.pack("<7I", 0, 0, 0, 32 | (8 << 16), 1, 0, (6 << 1) | (1 << 10)) desc = struct.pack("<12Q", 0, 0, len(sa), 0, 0, 0, len(code), 0, len(data), 0, 0, 0) parts = {".c67":code, ".data":data, ".root":root, ".desc":desc, ".sa":sa, ".sb":b""} - payload = b"x2w-startup-shader-28cs" + b"".join(struct.pack(" prints one RGBA32F pixel. +// --startup-image-2d-view [0|1] prints one RGBA32F pixel. +// The optional selector is forwarded as the existing second root constant. +// --startup-image-2d-array-view takes the identical args; argv[2] selects the two-slice 2D-array renderer. OperationResult run_startup_image_2d_view(const OperationContext& ctx) { const std::string_view window = ctx.argv[6]; if (window.size() != 3 || window[1] != '/' || window[0] < '0' || window[0] > '2' || window[2] < '1' || window[2] > '3') return {OutcomeKind::fail, "expected a first/count mip window on a three-mip texture"}; + const bool array = std::strcmp(ctx.argv[2], "--startup-image-2d-array-view") == 0; + float selector = 0.0f; + if (ctx.argc == 8) { + if (std::strcmp(ctx.argv[7], "1") == 0) + selector = 1.0f; + else if (std::strcmp(ctx.argv[7], "0") != 0) + return {OutcomeKind::fail, "view selector must be 0 or 1"}; + } float color[4]{}; - check_startup_image_3d(ctx.device, ctx.argv[3], ctx.argv[4], 0, color, ctx.argv[5], false, 3, false, true, + check_startup_image_3d(ctx.device, ctx.argv[3], ctx.argv[4], selector, color, ctx.argv[5], array, 3, false, !array, UINT(window[0] - '0'), UINT(window[2] - '0')); std::uint32_t bits[4]; std::memcpy(bits, color, sizeof(bits)); @@ -1416,20 +1426,31 @@ OperationResult run_startup_image_load_d16(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } -// --startup-image-store : the translated pixel stage stores to -// u0 (tests/startup_image_store.cpp); texel (x, y) must hold the four hex words and every other texel -1.0. +// --startup-image-store [coverage]: the translated pixel +// stage stores to u0 (tests/startup_image_store.cpp); texel (x, y) must hold the four hex words and +// every other texel -1.0. Coverage is 1 (one pixel) or 2 (two pixels in one draw). OperationResult run_startup_image_store(const OperationContext& ctx) { - unsigned x = 0, y = 0; + unsigned x = 0, y = 0, coverage = 1; std::uint32_t expected[4]{}; if (std::sscanf(ctx.argv[5], "%u,%u", &x, &y) != 2) return {OutcomeKind::fail, "texel is not x,y"}; if (std::sscanf(ctx.argv[6], "%8x,%8x,%8x,%8x", &expected[0], &expected[1], &expected[2], &expected[3]) != 4) return {OutcomeKind::fail, "expected value is not four hex words"}; - if (check_startup_image_store(ctx.device, ctx.argv[3], ctx.argv[4], x, y, expected)) + if (ctx.argc == 8 && (std::sscanf(ctx.argv[7], "%u", &coverage) != 1 || (coverage != 1 && coverage != 2))) + return {OutcomeKind::fail, "coverage is not 1 or 2"}; + if (check_startup_image_store(ctx.device, ctx.argv[3], ctx.argv[4], x, y, expected, coverage)) return {OutcomeKind::fail, "image store readback differs"}; return {OutcomeKind::pass, nullptr}; } +// --startup-image-store-reject-load: a colour format without typed UAV load is refused before any draw. +OperationResult run_startup_image_store_reject_load(const OperationContext& ctx) +{ + if (const char* reason = check_startup_image_store_typed_load(ctx.device)) + return {OutcomeKind::fail, reason}; + return {OutcomeKind::fail, "typed UAV load negative control found no refusal"}; +} + const char* check_startup_sharedexp_target(ID3D12Device* device, ID3D12InfoQueue* messages); OperationResult run_startup_sharedexp_target(const OperationContext& ctx) @@ -1717,9 +1738,11 @@ const OperationSpec kOperations[] = { {"--startup-image-1d", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-1d-mips", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-2d", 7, 8, nullptr, kNoGate, run_startup_image_3d}, - {"--startup-image-2d-view", 7, 7, nullptr, kNoGate, run_startup_image_2d_view}, + {"--startup-image-2d-view", 7, 8, nullptr, kNoGate, run_startup_image_2d_view}, + {"--startup-image-2d-array-view", 7, 8, nullptr, kNoGate, run_startup_image_2d_view}, {"--startup-image-3d", 7, 8, nullptr, kNoGate, run_startup_image_3d}, - {"--startup-image-store", 7, 7, nullptr, kNoGate, run_startup_image_store}, + {"--startup-image-store", 7, 8, nullptr, kNoGate, run_startup_image_store}, + {"--startup-image-store-reject-load", 3, 3, nullptr, kNoGate, run_startup_image_store_reject_load}, {"--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}, diff --git a/tests/run_checks_fragments_check.py b/tests/run_checks_fragments_check.py index 43e00d48a6..4eaf4af25f 100644 --- a/tests/run_checks_fragments_check.py +++ b/tests/run_checks_fragments_check.py @@ -71,13 +71,22 @@ def write(path, text): refused = run("--from-dir", bad_list) assert refused.returncode == 1 and needle in refused.stdout, (name, refused.stdout) assert "echo ran" not in refused.stdout, (name, refused.stdout) - # The same command in two files is a duplicate too. + # The same command in two files is a duplicate too, even with different path spellings. two = os.path.join(tmp, "case_two") os.mkdir(two) write(os.path.join(two, "a.txt"), f"{q(echo)}\n") write(os.path.join(two, "b.txt"), f"{q(echo)}\n") twice = run("--from-dir", two) assert twice.returncode == 1 and "b.txt:1" in twice.stdout and "duplicate" in twice.stdout, twice.stdout + dot_two = os.path.join(tmp, "case_dot_two") + os.mkdir(dot_two) + dot_echo = os.path.join(tmp, ".", os.path.basename(echo)) + write(os.path.join(dot_two, "a.txt"), f"{q(echo)}\n") + write(os.path.join(dot_two, "b.txt"), f"{q(dot_echo)}\n") + dot_twice = run("--from-dir", dot_two) + assert dot_twice.returncode == 1 and "b.txt:1" in dot_twice.stdout and "duplicate" in dot_twice.stdout, dot_twice.stdout + dedup = run("--from-dir", lists, dot_echo) + assert dedup.returncode == 0 and "all 3 checks passed" in dedup.stdout, dedup.stdout assert run().returncode == 2 # A listing saved with a UTF-8 byte-order mark (Notepad, Windows PowerShell 5.1 Set-Content diff --git a/tests/run_checks_parallel_check.py b/tests/run_checks_parallel_check.py index 16beed43a7..7484751def 100644 --- a/tests/run_checks_parallel_check.py +++ b/tests/run_checks_parallel_check.py @@ -73,6 +73,12 @@ def group(out, script, status): assert both.returncode == 1, both.stdout assert "FAILED: " + bad + "\n" in both.stdout, both.stdout assert "SKIPPED: " + skip + "\n" in both.stdout, both.stdout + # Equivalent script path spellings on the command line (e.g. a.py vs ./a.py) count as duplicates. + dot_good = os.path.join(tmp, ".", "good.py") + spelled_twice = run(good, dot_good) + assert spelled_twice.returncode == 1, spelled_twice.stdout + assert spelled_twice.stdout.strip() == "duplicate command-line script: " + dot_good, spelled_twice.stdout + assert "good ran" not in spelled_twice.stdout and "::group::" not in spelled_twice.stdout, spelled_twice.stdout # -j 0 is clamped to one worker instead of reaching ThreadPoolExecutor(max_workers=0). serial = run(good, jobs="0") assert serial.returncode == 0 and "all 1 checks passed" in serial.stdout, serial.stdout diff --git a/tests/startup_address_console_check.py b/tests/startup_address_console_check.py index 41ba62e265..be74340afa 100644 --- a/tests/startup_address_console_check.py +++ b/tests/startup_address_console_check.py @@ -9,6 +9,14 @@ refuses the uploads past its cap, the refused draws read the null view and the left half keeps payload 0 gate-ring-reuse after completion, a new ring upload draws payload 18 over the right half + gate-ring-keep list A uploads 32 payloads (512 MiB) from the ring, is submitted, completes + and is never Reset; list B then draws payload 32 over the right half. Without + X2W_D3D12_RING_RELEASE_AT_SUBMIT, A keeps its chunks: the ring refuses past 256 MiB + and the right half reads the null view + gate-ring-keep-release the same with X2W_D3D12_RING_RELEASE_AT_SUBMIT=1: A releases its + chunks at its fenced submit, so B draws payload 32; A submitted again afterwards + would read reused chunks, so it is refused before the execute: the target, read + back after that submit, still holds payload 32 on the right (not A's payload 31) The backing bytes are built here, independently of src/startup_stubs/gfx10_layout.h, from the address equations of AMD addrlib's GFX10 pattern tables, written out below. Reference: addrlib as Mesa carries it @@ -211,6 +219,7 @@ def check(directory, consumer, backend, case, extra=None, held=None, late=False) GATE_PAYLOADS = 18 +KEEP_PAYLOADS = 32 # tests/startup_stream_draw.cpp, X2W_TEST_CONSOLE_KEEP def gate_colour(payload): @@ -240,6 +249,16 @@ def check_gate(directory, consumer, backend, mode): modes = {"X2W_TEST_CONSOLE_GATE": "1", "X2W_TRAP_LOG": str(trap_log)} ring = mode != "gate" reuse = mode == "gate-ring-reuse" + keep = mode in ("gate-ring-keep", "gate-ring-keep-release") + release = mode == "gate-ring-keep-release" + if keep: + modes["X2W_TEST_CONSOLE_KEEP"] = "1" + else: + os.environ.pop("X2W_TEST_CONSOLE_KEEP", None) + if release: + modes["X2W_D3D12_RING_RELEASE_AT_SUBMIT"] = "1" + else: + os.environ.pop("X2W_D3D12_RING_RELEASE_AT_SUBMIT", None) if reuse: modes["X2W_TEST_ADDRESS_UPLOAD_RING_REUSE"] = "1" else: @@ -258,6 +277,8 @@ def check_gate(directory, consumer, backend, mode): last = bytes(4) if ring else gate_colour(GATE_PAYLOADS - 1) if reuse: last = gate_colour(GATE_PAYLOADS) + if release: + last = gate_colour(KEEP_PAYLOADS) wrong = {"left": 0, "right": 0} seen = set() for y in range(TARGET_H): @@ -270,6 +291,22 @@ def check_gate(directory, consumer, backend, mode): log = trap_log.read_text(errors="replace") released = f"x2w-draw by-address uploads: {GATE_PAYLOADS} submits completed and released" half = TARGET_W * TARGET_H // 2 + if keep: + if wrong["left"] or wrong["right"]: + ring_lines = "\n".join(line for line in log.splitlines() if "upload ring" in line) + raise AssertionError(f"{mode}: {wrong} wrong pixels, found {sorted(seen)[:4]}; expected {first.hex()} left, " + f"{last.hex()} right\n{ring_lines}") + refused = "x2w-draw upload ring reservation refused: no unused capacity" in log + reported = "were reused; refused, it is not executed" in log + if release and not reported: + raise AssertionError(f"{mode}: list A submitted again after B reused its chunk was not refused") + if not release and (not refused or reported): + raise AssertionError(f"{mode}: expected the 256 MiB refusal and no resubmit refusal (refused={refused}, reported={reported})") + print(f"{backend} {mode}: {half} left pixels hold payload 0 and {half} right pixels hold {last.hex()} after A's " + "resubmit; " + + ("A's chunks were released at its fenced submit and its stale resubmit was refused, not executed" if release + else "the never-Reset list kept its chunks and the ring refused past its cap")) + return 0 if ring: if wrong["left"] or wrong["right"]: raise AssertionError(f"{mode}: {wrong} wrong pixels, found {sorted(seen)[:4]}; expected {first.hex()} left, {last.hex()} right") @@ -290,9 +327,11 @@ def check_gate(directory, consumer, backend, mode): return 0 +GATES = ("gate", "gate-ring", "gate-ring-reuse", "gate-ring-keep", "gate-ring-keep-release") + if __name__ == "__main__": - if len(sys.argv) not in (3, 4) or (len(sys.argv) == 4 and sys.argv[3] not in ("gate", "gate-ring", "gate-ring-reuse")): - usage = "usage: startup_address_console_check.py [gate | gate-ring | gate-ring-reuse]\n" + if len(sys.argv) not in (3, 4) or (len(sys.argv) == 4 and sys.argv[3] not in GATES): + usage = "usage: startup_address_console_check.py [gate | gate-ring | gate-ring-reuse | gate-ring-keep | gate-ring-keep-release]\n" sys.exit(usage + "\n\n".join(__doc__.split("\n\n")[:2])) if len(sys.argv) == 4: with tempfile.TemporaryDirectory() as temporary: diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index 183f25d0a8..38ba6ec090 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -485,6 +486,105 @@ int draw_formatted_view(void* guest, void* list) return 0; } +// X2W_TEST_TABLE_ALIAS_WRITE: a buffer view the title creates over a placed buffer, at table entry 0 +// (tests/startup_table_alias_check.py). +// 1 a raw view of the whole 256-byte buffer. The title writes the record, draws the left half, writes +// it again, draws the right half, and writes it a third time after recording, before the list runs. +// A per-draw copy shows the first two values; a live alias shows the third in both halves. +// shared-index the same buffer is also the index buffer of one indexed draw (indices 0-2 at offset 0). The alias +// must be in both the index-buffer and the shader-resource states at that draw. +// odd-size a 254-byte buffer under a structured view of 127 two-byte records. The desktop raw view covers +// 256 bytes, past the alias, so the draw takes a copy: it shows the value written before recording. +// With X2W_TEST_DEBUG_LAYER, errors the debug layer stored for the device from the fixture's start +// (ID3D12InfoQueue; the message callback of ID3D12InfoQueue1 needs a newer runtime). +ID3D12InfoQueue* table_alias_messages = nullptr; + +void table_alias_debug_report() +{ + if (!table_alias_messages) return; + int errors = 0; + const UINT64 stored = table_alias_messages->GetNumStoredMessages(); + for (UINT64 i = 0; i < stored; ++i) { + SIZE_T bytes = 0; + if (FAILED(table_alias_messages->GetMessage(i, nullptr, &bytes)) || !bytes) continue; + std::vector storage(bytes); + auto* message = reinterpret_cast(storage.data()); + if (FAILED(table_alias_messages->GetMessage(i, message, &bytes)) || message->Severity > D3D12_MESSAGE_SEVERITY_ERROR) + continue; + if (++errors <= 8) std::printf("debug layer id %d: %.300s\n", static_cast(message->ID), message->pDescription); + } + std::printf("table alias debug layer errors: %d\n", errors); +} + +int draw_table_alias_writes(ID3D12Device* desktop, void* guest, void* list) +{ + D3D12_FEATURE_DATA_EXISTING_HEAPS heaps{}; + if (FAILED(desktop->CheckFeatureSupport(D3D12_FEATURE_EXISTING_HEAPS, &heaps, sizeof(heaps))) || !heaps.Supported) + return 77; + if (GetEnvironmentVariableW(L"X2W_TEST_DEBUG_LAYER", nullptr, 0)) { + if (FAILED(desktop->QueryInterface(IID_PPV_ARGS(&table_alias_messages)))) { + std::printf("no debug layer message queue: skipped\n"); + return 77; + } + table_alias_messages->SetMessageCountLimit(4096); + table_alias_messages->ClearStoredMessages(); + } + char mode[16]{}; + GetEnvironmentVariableA("X2W_TEST_TABLE_ALIAS_WRITE", mode, sizeof(mode)); + const bool shared_index = !std::strcmp(mode, "shared-index"); + const bool odd_size = !std::strcmp(mode, "odd-size"); + if (!shared_index && !odd_size && std::strcmp(mode, "1")) return 70; + // VirtualAlloc memory, so the placement can alias it (an existing heap cannot open image memory). + auto* const records = static_cast(VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!records) return 71; + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, odd_size ? 254u : 256u, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + void* placed = nullptr; + if (FAILED(static_cast(invoke(guest, 133, ptr(records), ptr(&desc), D3D12_RESOURCE_STATE_COMMON, + 0, ptr(&__uuidof(ID3D12Resource)), ptr(&placed))))) return 47; + Word cpu = 0; + if (!bind_view_table(guest, list, cpu)) return 42; + D3D12_SHADER_RESOURCE_VIEW_DESC view{odd_size ? DXGI_FORMAT_UNKNOWN : DXGI_FORMAT_R32_TYPELESS, + D3D12_SRV_DIMENSION_BUFFER, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + view.Buffer.NumElements = odd_size ? 127 : 64; + view.Buffer.StructureByteStride = odd_size ? 2 : 0; + view.Buffer.Flags = odd_size ? D3D12_BUFFER_SRV_FLAG_NONE : D3D12_BUFFER_SRV_FLAG_RAW; + invoke(guest, 18, ptr(placed), ptr(&view), cpu); + if (shared_index || odd_size) { + auto* const indices = reinterpret_cast(records); + for (std::uint16_t i = 0; i < 3; ++i) indices[i] = i; + records[4] = 40; + records[5] = 41; + const D3D12_RECT full{0, 0, 8, 4}; + invoke(list, 22, 1, ptr(&full)); + if (shared_index) { + const D3D12_INDEX_BUFFER_VIEW index_view{ptr(records), 6, DXGI_FORMAT_R16_UINT}; + invoke(list, 47, ptr(&index_view)); + invoke(list, 13, 3, 1, 0, 0, 0); + } else { + invoke(list, 12, 3, 1); + records[4] = 120; // after recording: only a live alias would show it + records[5] = 121; + } + return 0; + } + const auto write = [&](std::uint32_t value) { + records[4] = value; + records[5] = value + 1; + }; + const auto draw = [&](LONG left, LONG right) { + const D3D12_RECT strip{left, 0, right, 4}; + invoke(list, 22, 1, ptr(&strip)); + invoke(list, 12, 3, 1); + }; + write(40); + draw(0, 4); + write(80); + draw(4, 8); + write(120); // after recording: only a binding that reads at execution sees it + return 0; +} + int draw_copied_vertex_buffer_srv(void* guest, void* list) { constexpr UINT full_bytes = 512; diff --git a/tests/startup_compute_dispatch_check.py b/tests/startup_compute_dispatch_check.py index bc1ee05770..33ca1733c4 100644 --- a/tests/startup_compute_dispatch_check.py +++ b/tests/startup_compute_dispatch_check.py @@ -6,7 +6,7 @@ stand-in list, the descriptor heap, the pipeline, its root signature, two root constants (word 0 by slot 37, word 1 by slot 39, with a slot 40 call of other words in between), one table of two hardware buffer descriptors and Dispatch(3, 2, 2). Input and output are placed buffers that alias the consumer's -memory; the output words are read from that memory after the queue's fence. Four runs share one cache: +memory; the output words are read from that memory after the queue's fence. The runs share one cache: 1. before translation: the request is published, the Dispatch is refused with "no translation" and every output word keeps the sentinel (the check fails when nothing translated is dispatched); @@ -19,7 +19,10 @@ call), dispatch-root-changed (another compute root and back after the constants), dispatch-reset (list closed and reset after the constants), dispatch-wrong-root (recorded under a root the pipeline was not created with) and dispatch-same-buffer (the output buffer is also the input). -Exit 77 when the adapter is not available. +7. slot 35 selects the correct table at descriptor index 2 instead of the swapped pair at the heap start; + setting the same heap again preserves the table, but changing the compute root or view heap after binding + must refuse at the table lookup, not an earlier check. +Exit 77 only if the initial probe cannot use the adapter or required heaps. """ import os from pathlib import Path @@ -34,16 +37,19 @@ from startup_stream_check import gfx2hlsl as G -def dispatch(directory, consumer, env, mode): +def dispatch(directory, consumer, env, mode, *, probe=False): out = directory / 'out.bin' out.unlink(missing_ok=True) args = [consumer, directory / 'vertex', directory / 'pixel', directory / 'root', 'slot67', directory / 'program', directory / 'data', directory / 'state', mode] result = subprocess.run(args, env=dict(env, X2W_TEST_DISPATCH_OUT=str(out)), capture_output=True, text=True) - if result.returncode == 77: + if 'device removed' in result.stderr.lower(): + raise RuntimeError(f'{mode}: device removed\n{result.stderr[-3000:]}') + if result.returncode == 77 and probe: print(result.stdout, end='') sys.exit(77) - assert result.returncode == 0, f'{mode}: consumer exit {result.returncode}\n{result.stderr[-3000:]}' + if result.returncode: + raise RuntimeError(f'{mode}: consumer exit {result.returncode}\n{result.stdout[-1000:]}\n{result.stderr[-3000:]}') return list(struct.unpack('<%dI' % C.WORDS, out.read_bytes())), result @@ -75,7 +81,7 @@ def main(consumer, dxc, adapter): untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A') assert expected != untouched - got, result = dispatch(directory, consumer, env, 'dispatch') + got, result = dispatch(directory, consumer, env, 'dispatch', probe=True) print(result.stdout, end='') assert got == untouched, 'a Dispatch without a translation wrote the output' assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] @@ -129,8 +135,28 @@ def main(consumer, dxc, adapter): assert got == untouched, f'{mode}: a refused Dispatch wrote the output' refused = lines(result, 'refused: ') assert len(refused) == 1 and refused[0].endswith('refused: ' + reason), f'{mode}: {refused}\n{result.stderr[-3000:]}' - print(f'startup_compute_dispatch: PASS on {adapter} (all {C.WORDS} words match after translation and with the ' - 'same root set again; untouched before translation, without a Dispatch and for 6 refusals)') + debug_enabled = bool(layer and '0x00000000' in layer[0]) + for mode in ('dispatch-table-root-changed', 'dispatch-table-heap-changed', 'dispatch-table-offset'): + got, result = dispatch(directory, consumer, env, mode) + if debug_enabled: + initialized = lines(result, 'x2w-d3d12 debug layer: ') + assert len(initialized) == 1 and '0x00000000' in initialized[0], f'{mode}: debug layer not initialized' + refused = lines(result, 'refused: ') + translated = lines(result, 'Dispatch(3, 2, 2) translated') + if mode == 'dispatch-table-offset': + wrong = sum(a != b for a, b in zip(got, expected)) + assert not wrong, f'{mode}: {wrong} words differ from the CPU reference\n{result.stderr[-3000:]}' + assert len(translated) == 1 and not refused, result.stderr[-3000:] + print(f'{mode}: all {C.WORDS} words match the CPU reference') + else: + written = sum(word != C.SENTINEL for word in got) + assert not written, f'{mode}: {written} output words changed after table invalidation\n{result.stderr[-3000:]}' + assert not translated and len(refused) == 1 and refused[0].endswith( + 'Dispatch(3, 2, 2) refused: a table descriptor is not bound'), result.stderr[-3000:] + print(f'{mode}: exact table refusal, all {C.WORDS} sentinel words unchanged') + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + print(f'startup_compute_dispatch: PASS on {adapter}') if __name__ == '__main__': diff --git a/tests/startup_compute_dispatch_texture_check.py b/tests/startup_compute_dispatch_texture_check.py index fd09c48dec..54a6dce2b4 100644 --- a/tests/startup_compute_dispatch_texture_check.py +++ b/tests/startup_compute_dispatch_texture_check.py @@ -13,6 +13,7 @@ 4. texture-store-denied (a texture without unordered access, whose view the stand-in does not create): refused with one logged reason, every half keeps its sentinel. A fifth run binds the same program under a manifest edited to declare no entry values. +The 1D and 3D float texture cases check mip-one readback, a mismatched view, and an invalid 3D W range. Texture input: case A of startup_gfx2hlsl_compute_check.py with a level-zero sample of a 2D texture XORed into the stored word (a static sampler, a texture view at table byte 64). The consumer adds a 1x1 RGBA8 texture whose red @@ -34,6 +35,7 @@ import startup_compute_image_store_d16_check as S import startup_gfx2hlsl_compute_check as C +import startup_gfx2hlsl_image_store_3d1d_check as V from startup_compute_dispatch_check import lines from startup_compute_request_check import DATA, prepare from startup_compute_translate_check import state_a @@ -148,6 +150,54 @@ def store(directory, consumer, dxc, env): f'untouched before translation, without a Dispatch and for a refused view; debug layer: {layer}') +def store_3d1d(directory, consumer, dxc, env, form): + cache, base = prepare(directory) + env = dict(base, **env) + (directory / 'compute_root').write_bytes(C.root_blob(3, table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + (directory / 'program').write_bytes(V.program(form)) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(V.group(form), V.A.RSRC2)) + + volume = form != 'line' + mode = 'texture-volume' if volume else 'texture-line' + width, height, depth = 32, 8 if volume else 1, 6 if volume else 1 + plane_words = width * height * 4 + initial = [0xbf000000 | (z << 12) | i for z in range(depth) for i in range(plane_words)] + expected = initial.copy() + for y in range(V.group(form)[1]): + # The 3D view starts at W slice 1 and the shader writes relative z=1. + start = (2 * plane_words if volume else 0) + y * width * 4 + expected[start:start + 32] = V.VALUES * 8 + layout = '<%dI' % len(initial) + got, result = run(directory, consumer, env, mode, layout) + assert got == initial and len(lines(result, 'Dispatch(2, 1, 1) refused: no translation')) == 1 + key = int(lines(result, 'x2w-draw compute request')[0].split()[3], 16) + translate(cache, dxc, key) + manifest = (cache / f'{key:016x}.txt').read_text().splitlines() + dim = '3d' if volume else '1d' + assert f'uav 0 tex{dim} float table 1 64 channels 4' in manifest, manifest + got, result = run(directory, consumer, env, mode, layout) + assert len(lines(result, 'Dispatch(2, 1, 1) translated')) == 1, result.stderr[-3000:] + assert got == expected, (form, sum(a != b for a, b in zip(got, expected, strict=True))) + clean(result) + + mismatch = initial[:32 * 8 * 4] if volume else [0xbf000000 | i for i in range(32 * 8 * 4)] + cases = [('texture-array-2d', mismatch, f'an output texture view or resource is not {dim.upper()}')] + if volume: + # Manual mutant: skipping the mip-relative W-range check must fail the required refusal. + cases.append(('texture-volume-bad-w', initial, 'an output 3D texture W range is outside the mip')) + else: + # Manual mutant: dropping the 1D mip check before `created` must fail this required refusal. + cases.append(('texture-line-bad-mip', initial, 'an output 1D texture mip is outside the resource')) + for bad_mode, untouched, reason in cases: + got, result = run(directory, consumer, env, bad_mode, '<%dI' % len(untouched)) + refusal = lines(result, 'Dispatch(2, 1, 1) refused:') + assert len(refusal) == 1 and refusal[0].endswith(reason), result.stderr[-3000:] + assert got == untouched and not lines(result, 'Dispatch(2, 1, 1) translated') + print(f'{form}: {len(expected)} mip-one words match; incompatible views refused with sentinels intact') + + # v_xor_b32 v5, v5, v12: the assembled `v_xor_b32 v5, v5, v6` of case A with its second source register changed # (not assembled by llvm-mc here; the translation below is checked to read it as written). XOR = 'v_xor_b32 v5, v5, v12' @@ -269,6 +319,8 @@ def main(consumer, dxc, adapter): env['X2W_TEST_DISPATCH_HARDWARE'] = '1' with tempfile.TemporaryDirectory() as temporary: store(Path(temporary) / 'store', consumer, dxc, env) + for form in V.FORMS: + store_3d1d(Path(temporary) / form, consumer, dxc, env, form) sample(Path(temporary) / 'sample', consumer, dxc, env) filtered(Path(temporary) / 'filtered', consumer, dxc, env) print(f'startup_compute_dispatch_texture: PASS on {adapter}') diff --git a/tests/startup_compute_image_store_check.py b/tests/startup_compute_image_store_check.py index 1623afee8e..d4831af416 100644 --- a/tests/startup_compute_image_store_check.py +++ b/tests/startup_compute_image_store_check.py @@ -150,17 +150,13 @@ def encoded(line, hex_words): (fixture.STORE.replace('v[14:17]', 'v[14:15]').replace('dmask:0xf', 'dmask:0x3'), '080320f0080e0600', 'typed UAV store writes all four channels'), (fixture.STORE.replace('v[8:9]', 'v8') + ' a16', '080f20f0080e0640', 'modifier a16'), - (fixture.STORE.replace('v[8:9]', 'v[8:10]').replace('IMG_2D', 'IMG_3D'), - '100f20f0080e0600', 'only 2D images'), ): instruction = encoded(asm, code) refused(reason, lambda: pipeline(instruction)) - # 1D, 3D and cube keep the same refusal with the address count their form would take. - for dim, address in (('SQ_RSRC_IMG_1D', 'v8'), ('SQ_RSRC_IMG_3D', 'v[8:10]'), - ('SQ_RSRC_IMG_CUBE', 'v[8:10]')): - refused('only 2D images', - lambda: pipe.cs.op_image_store(['v[14:17]', address, 's[24:31]'], ['dmask:0xf', 'dim:' + dim])) + refused('only 1D, 2D, 2D-array and 3D images', + lambda: pipe.cs.op_image_store(['v[14:17]', 'v[8:10]', 's[24:31]'], + ['dmask:0xf', 'dim:SQ_RSRC_IMG_CUBE'])) wait = encoded('s_waitcnt lgkmcnt(0)', '7fc08cbf') changed = encoded('s_mov_b32 s26, 0', '80039abe') diff --git a/tests/startup_compute_image_store_d16_check.py b/tests/startup_compute_image_store_d16_check.py index 9c7fd55160..310e26be39 100644 --- a/tests/startup_compute_image_store_d16_check.py +++ b/tests/startup_compute_image_store_d16_check.py @@ -89,8 +89,6 @@ def encoded(line, hex_words): (fixture.STORE.replace('v[14:15]', 'v14').replace('dmask:0xf', 'dmask:0x3'), '080320f0080e0680', 'typed UAV store writes all four channels'), (fixture.STORE.replace('v[8:9]', 'v8').replace(' d16', ' a16 d16'), '080f20f0080e06c0', 'modifier a16'), - (fixture.STORE.replace('v[8:9]', 'v[8:10]').replace('IMG_2D', 'IMG_3D'), - '100f20f0080e0680', 'only 2D images'), ): instruction = encoded(asm, code) refused(reason, lambda: pipeline(instruction)) diff --git a/tests/startup_compute_request_offline_check.py b/tests/startup_compute_request_offline_check.py index 89519ce701..7ea4df8da9 100644 --- a/tests/startup_compute_request_offline_check.py +++ b/tests/startup_compute_request_offline_check.py @@ -25,12 +25,12 @@ DESC = struct.pack('<12Q', 0, 0, 24, 0, 20, 0, len(CODE), 0, len(DATA), 0, 0, 11) STATE_A = struct.pack('<3Q', 1, 0x2c, 0xfff0000000000003) STATE_B = struct.pack('<5I', 0x1234abcd, 0xffff0000, 0, 0, 0) -KEY = 0x39e7422f5da15950 # framed key at revision 28cs +KEY = 0x96c99985746a35d1 # framed key at revision 29cs def framed_key(): h = 1469598103934665603 - for b in b'x2w-startup-shader-28cs': + for b in b'x2w-startup-shader-29cs': h = ((h ^ b) * 1099511628211) & 0xffffffffffffffff for part in (CODE, DATA, ROOT, DESC, STATE_A, STATE_B): for b in struct.pack(' buf root ` at slot-14 Dispatch (Refs #2618, #2274).""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from startup_compute_dispatch_texture_check import clean, lines, run as _run, translate +from startup_compute_global_load_check import ( + GLOBAL_LOAD_DWORD, + encode_global, + encode_mubuf, + encode_smem, + encode_sop1, + encode_sop2, + encode_sopp, + encode_vop2, + encode_vop3a, +) +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_gfx2hlsl_compute_check import ( + KEY, + MASK, + SENTINEL, + STRIDE, + TGID_X, + TGID_Y, + TGID_Z, + WORDS, + tidig, +) + +IN = [(0x8b02a7f1 + i * 0x413b1) & MASK for i in range(WORDS)] +IN2 = [(0x3c6ef372 + i * 0x19660d) & MASK for i in range(WORDS)] +NEIGHBOR0 = [(0xdeadbeef + i) & MASK for i in range(64)] +NEIGHBOR2 = [(0xfeedface + i) & MASK for i in range(64)] +GROUP = (2, 3, 4) + + +def run(directory, consumer, env, mode): + return _run(directory, consumer, env, mode, f"<{WORDS}I") + + +def no_debug_errors(result): + errors = [line for line in lines(result, "x2w-d3d12-debug ") if " sev=0 " in line or " sev=1 " in line] + assert not errors, errors[0] + + +def root_srv_blob(*, two_srvs=False, param2_type=3): + """DXBC RTS0 (v1.1) container matching startup_stream_consumer.cpp root-SRV bindings: + param 0 = 3 root constants at b0 (s4-s6; shader uses s4-s5), + param 1 = descriptor table with 2 UAV slots at u0 (s7; output UAV at table byte 16), + param 2 = root descriptor at register(t1/b1, space0) (s[8:9]; type 3=SRV, 2=CBV), + optional param 3 = root SRV descriptor at register(t2, space0) (s[10:11]). + """ + nparams = 4 if two_srvs else 3 + poff = 24 + coff = poff + 12 * nparams + toff = coff + 12 + roff = toff + 8 + srv2_off = roff + 24 + srv3_off = srv2_off + 12 + soff = (srv3_off + 12) if two_srvs else (srv2_off + 12) + params = [ + struct.pack("<3I", 1, 0, coff), + struct.pack("<3I", 0, 0, toff), + struct.pack("<3I", param2_type, 0, srv2_off), + ] + if two_srvs: + params.append(struct.pack("<3I", 3, 0, srv3_off)) + payload = ( + struct.pack("<3I", 0, 0, 3) + + struct.pack("<2I", 1, roff) + + struct.pack("<6I", 1, 2, 0, 0, 0, 0xffffffff) + + struct.pack("<3I", 1, 0, 0) + ) + if two_srvs: + payload += struct.pack("<3I", 2, 0, 0) + rts0 = struct.pack("<6I", 2, nparams, poff, 0, soff, 0) + b"".join(params) + payload + assert len(rts0) == soff + part = b"RTS0" + struct.pack(", 3 + encode_sop2(0x00, 24, 24, gx), # s_add_u32 s24, s24, s + encode_sop2(0x26, 25, gz, 0x80 + 6), # s_mul_i32 s25, s, 6 + encode_sop2(0x00, 24, 24, 25), # s_add_u32 s24, s24, s25 + encode_sop2(0x26, 24, 24, 0x80 + 24), # s_mul_i32 s24, s24, 24 + encode_vop2(0x25, 3, 24, 3), # v_add_nc_u32 v3, s24, v3 + encode_vop2(0x1a, 4, 0x80 + 2, 3), # v_lshlrev_b32 v4, 2, v3 + encode_global(GLOBAL_LOAD_DWORD, 5, 4, 8, offset=0), # global_load_dword v5, v4, s[8:9] + encode_global(GLOBAL_LOAD_DWORD, 7, 4, second_saddr, offset=128), # global_load_dword v7, v4, s[...] offset:128 + encode_vop3a(0x169, 6, 256 + 3, 5, 0), # v_mul_lo_u32 v6, v3, s5 + encode_vop2(0x25, 6, 4, 6), # v_add_nc_u32 v6, s4, v6 + encode_sopp(0x0c, 0x3f70), # s_waitcnt vmcnt(0) + encode_vop3a(0x169, 5, 256 + 5, 0x80 + 33, 0), # v_mul_lo_u32 v5, v5, 33 + encode_vop2(0x25, 5, 256 + 5, 7), # v_add_nc_u32 v5, v5, v7 + encode_vop2(0x1d, 5, 256 + 5, 6), # v_xor_b32 v5, v5, v6 + encode_mubuf(0x1c, 5, 4, 20, offen=True), # buffer_store_dword v5, v4, s[20:23], 0 offen + encode_sopp(0x01, 0), # s_endpgm + ]) + return code, rsrc2 + + +def reference(*, two_srvs=False, offset0=0, offset1=0, shift1=32, swap_srvs=False, leak_neighbor=False): + src0 = (IN2 if swap_srvs else IN) + (NEIGHBOR2 if swap_srvs else NEIGHBOR0) + src1 = (IN if swap_srvs else (IN2 if two_srvs else IN)) + (NEIGHBOR0 if swap_srvs else (NEIGHBOR2 if two_srvs else NEIGHBOR0)) + off0 = offset1 if swap_srvs else offset0 + off1 = offset0 if swap_srvs else (offset1 if two_srvs else offset0) + bound0 = WORDS - off0 + bound1 = WORDS - off1 + out = [SENTINEL] * WORDS + for i in range(12 * 24): + v5 = src0[off0 + i] if (leak_neighbor or i < bound0) else 0 + idx1 = i + shift1 + v7 = src1[off1 + idx1] if (leak_neighbor or idx1 < bound1) else 0 + out[i] = (((v5 * 33 + v7) & MASK) ^ ((KEY + i * STRIDE) & MASK)) + return out + + +def setup_case(directory, *, two_srvs=False, param2_type=3, adapter="warp"): + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP="1", X2W_D3D12_DEBUG="1") + if adapter == "hardware": + env["X2W_TEST_DISPATCH_HARDWARE"] = "1" + (directory / "compute_root").write_bytes(root_srv_blob(two_srvs=two_srvs, param2_type=param2_type)) + env["X2W_TEST_COMPUTE_ROOT"] = str(directory / "compute_root") + code, rsrc2 = make_program(two_srvs=two_srvs) + (directory / "program").write_bytes(code) + (directory / "data").write_bytes(DATA) + (directory / "state").write_bytes(state_a(GROUP, rsrc2)) + return cache, env + + +def check_single_root_srv(base, consumer, dxc, adapter): + directory = base / "single" + cache, env = setup_case(directory, two_srvs=False, adapter=adapter) + + # First run before translation publishes the request and leaves output sentinels untouched. + got, result = run(directory, consumer, env, "dispatch-root-srv") + assert got == [SENTINEL] * WORDS + assert len(lines(result, "Dispatch(3, 2, 2) refused: no translation")) == 1, result.stderr[-3000:] + key = int(lines(result, "x2w-draw compute request")[0].split()[3], 16) + translate(cache, dxc, key) + + manifest_path = cache / f"{key:016x}.txt" + hlsl_path = cache / f"{key:016x}.cs.hlsl" + cso_path = cache / f"{key:016x}.cs.cso" + manifest = manifest_path.read_text(encoding="utf-8") + hlsl = hlsl_path.read_text(encoding="utf-8") + assert "srv 0 buf root 2" in manifest.splitlines(), manifest + assert "ByteAddressBuffer r0 : register(t0);" in hlsl, hlsl + assert "r0.Load(a)" in hlsl and "r0.Load(a + 128u)" in hlsl, hlsl + + # Manifest parser refusal controls on bad `srv ... buf root ...` lines and descriptor-word udsrc on a root SRV. + for bad_manifest, expected_reason in ( + (manifest.replace("srv 0 buf root 2", "srv 0 buf root -1"), + "a resource that is not a raw table buffer or a 2D texture"), + (manifest.replace("srv 0 buf root 2", "srv 0 buf root 2 trailing"), + "a resource that is not a raw table buffer or a 2D texture"), + (manifest.replace("srv 0 buf root 2", "srv 1 buf root 2"), + "a resource that is not a raw table buffer or a 2D texture"), + (manifest.replace("ud 3\nudsrc 0 rootconst 0 0\nudsrc 1 rootconst 0 1\nudsrc 2 rootconst 0 2", + "ud 4\nudsrc 0 rootconst 0 0\nudsrc 1 rootconst 0 1\nudsrc 2 rootconst 0 2\nudsrc 3 stride 0"), + "an entry value names a descriptor that is not a buffer input or output"), + ): + sub = base / f"bad-manifest-{ abs(hash(bad_manifest)) }" + sub_cache, sub_env = setup_case(sub, two_srvs=False, adapter=adapter) + (sub_cache / f"{key:016x}.txt").write_text(bad_manifest, encoding="utf-8") + (sub_cache / f"{key:016x}.cs.cso").write_bytes(cso_path.read_bytes()) + got, result = run(sub, consumer, sub_env, "dispatch-root-srv") + assert got == [SENTINEL] * WORDS + assert lines(result, f"compute pipeline {key:016x} not translated: {expected_reason}"), result.stderr[-3000:] + + # Translated single-root-SRV dispatch (and re-binding the same compute root signature). + expected0 = reference(two_srvs=False, offset0=0) + for mode in ("dispatch-root-srv", "dispatch-root-srv-same-root"): + got, result = run(directory, consumer, env, mode) + assert len(lines(result, "Dispatch(3, 2, 2) translated")) == 1, result.stderr[-3000:] + debug = clean(result) + assert got == expected0, (mode, sum(a != b for a, b in zip(got, expected0))) + print(f"{adapter}: single root SRV (srv 0 buf root 2) and same-root rebind verified; debug: {debug}", flush=True) + + # Non-zero byte offset into placed buffer (+16 bytes = 4 dwords) and upload allocation (+16 bytes = 4 dwords), + # plus out-of-bounds offset past the bounded backing returning 0 rather than reading neighbor 0xdeadbeef words. + expected_off4 = reference(two_srvs=False, offset0=4) + leaked_off4 = reference(two_srvs=False, offset0=4, leak_neighbor=True) + assert sum(a != b for a, b in zip(expected_off4, leaked_off4)) == 4 + got, result = run(directory, consumer, env, "dispatch-root-srv-offset") + assert len(lines(result, "Dispatch(3, 2, 2) translated")) == 1, result.stderr[-3000:] + clean(result) + assert got == expected_off4 and got != leaked_off4 + + got, result = run(directory, consumer, env, "dispatch-root-srv-upload") + assert len(lines(result, "Dispatch(3, 2, 2) translated")) == 1, result.stderr[-3000:] + clean(result) + assert got == expected_off4 and got != leaked_off4 + print(f"{adapter}: single root SRV non-zero offset (+16B placed, +16B upload) and bounded OOB=0 verified", flush=True) + + # Refusal controls leaving output sentinels untouched and logging the exact refusal reason. + for mode, reason in ( + ("dispatch-root-srv-unset", "a compute root SRV was not set since the compute root"), + ("dispatch-root-srv-reset", "a compute root SRV was not set since the compute root"), + ("dispatch-root-srv-root-changed", "a compute root SRV was not set since the compute root"), + ("dispatch-root-srv-null", "a compute root SRV has a null address"), + ("dispatch-root-srv-unaligned", "a compute root SRV address is not 4-byte aligned"), + ("dispatch-root-srv-unaligned-16", "a compute root SRV range is not 16-byte aligned in its resource"), + ("dispatch-root-srv-unmapped", "a compute root SRV is in title memory outside any placed buffer"), + ("dispatch-root-srv-copied", "a compute root SRV is in a placed buffer that does not alias title memory"), + ("dispatch-root-srv-same-buffer", "an output buffer is also an input"), + ): + got, result = run(directory, consumer, env, mode) + assert got == [SENTINEL] * WORDS, mode + refusal = lines(result, "Dispatch(3, 2, 2) refused:") + assert len(refusal) == 1 and refusal[0].endswith(reason), (mode, refusal, result.stderr[-3000:]) + assert not lines(result, "Dispatch(3, 2, 2) translated"), mode + no_debug_errors(result) + print(f"{adapter}: single root SRV refusal controls (unset, reset, root-changed, unaligned, unmapped, copied, UAV alias) verified", flush=True) + + # Wrong root parameter kind refusal control: param 2 declared as root CBV (type 2) instead of root SRV (type 3). + cbv_dir = base / "wrong-kind-cbv" + cbv_cache, cbv_env = setup_case(cbv_dir, two_srvs=False, param2_type=2, adapter=adapter) + got, result = run(cbv_dir, consumer, cbv_env, "dispatch-root-srv") + assert got == [SENTINEL] * WORDS + cbv_key = int(lines(result, "x2w-draw compute request")[0].split()[3], 16) + translate(cbv_cache, dxc, cbv_key) + assert "srv 0 buf root 2" in (cbv_cache / f"{cbv_key:016x}.txt").read_text(encoding="utf-8").splitlines() + got, result = run(cbv_dir, consumer, cbv_env, "dispatch-root-srv") + assert got == [SENTINEL] * WORDS + refusal = lines(result, "Dispatch(3, 2, 2) refused:") + assert len(refusal) == 1 and refusal[0].endswith("a compute root input is not a shader resource view parameter"), ( + refusal, + result.stderr[-3000:], + ) + no_debug_errors(result) + print(f"{adapter}: wrong root parameter kind (root CBV at param 2) refused cleanly", flush=True) + + +def check_two_root_srvs(base, consumer, dxc, adapter): + directory = base / "two" + cache, env = setup_case(directory, two_srvs=True, adapter=adapter) + + got, result = run(directory, consumer, env, "dispatch-root-srv") + assert got == [SENTINEL] * WORDS + assert len(lines(result, "Dispatch(3, 2, 2) refused: no translation")) == 1, result.stderr[-3000:] + key = int(lines(result, "x2w-draw compute request")[0].split()[3], 16) + translate(cache, dxc, key) + + manifest_path = cache / f"{key:016x}.txt" + hlsl_path = cache / f"{key:016x}.cs.hlsl" + cso_path = cache / f"{key:016x}.cs.cso" + manifest = manifest_path.read_text(encoding="utf-8") + hlsl = hlsl_path.read_text(encoding="utf-8") + assert "srv 0 buf root 2" in manifest.splitlines() and "srv 1 buf root 3" in manifest.splitlines(), manifest + assert "ByteAddressBuffer r0 : register(t0);" in hlsl and "ByteAddressBuffer r1 : register(t1);" in hlsl, hlsl + assert "r0.Load(a)" in hlsl and "r1.Load(a + 128u)" in hlsl, hlsl + + expected_two = reference(two_srvs=True, offset0=0, offset1=0) + assert expected_two != reference(two_srvs=False, offset0=0) + got, result = run(directory, consumer, env, "dispatch-root-srv") + assert len(lines(result, "Dispatch(3, 2, 2) translated")) == 1, result.stderr[-3000:] + clean(result) + assert got == expected_two + print(f"{adapter}: two root SRVs (srv 0 buf root 2, srv 1 buf root 3) verified", flush=True) + + # Non-zero offsets into both placed buffers (+16B = 4 dwords on root SRV 0, +32B = 8 dwords on root SRV 1) + OOB=0 on root SRV 1. + expected_off = reference(two_srvs=True, offset0=4, offset1=8) + leaked_off = reference(two_srvs=True, offset0=4, offset1=8, leak_neighbor=True) + assert sum(a != b for a, b in zip(expected_off, leaked_off)) == 8 + got, result = run(directory, consumer, env, "dispatch-root-srv-offset") + assert len(lines(result, "Dispatch(3, 2, 2) translated")) == 1, result.stderr[-3000:] + clean(result) + assert got == expected_off and got != leaked_off + print(f"{adapter}: two root SRVs non-zero offsets (+16B/+32B) and bounded OOB=0 (8 OOB lanes) verified", flush=True) + + # Second root SRV unset while first root SRV is set must refuse cleanly. + got, result = run(directory, consumer, env, "dispatch-root-srv-unset-second") + assert got == [SENTINEL] * WORDS + refusal = lines(result, "Dispatch(3, 2, 2) refused:") + assert len(refusal) == 1 and refusal[0].endswith("a compute root SRV was not set since the compute root"), ( + refusal, + result.stderr[-3000:], + ) + no_debug_errors(result) + + # Negative control 1: skipping the Dispatch leaves all 320 output words at SENTINEL (288 mismatches vs expected). + got, result = run(directory, consumer, env, "dispatch-root-srv-none") + assert not lines(result, "Dispatch(3, 2, 2) translated") + assert got == [SENTINEL] * WORDS and sum(a != b for a, b in zip(got, expected_two)) == 288 + + # Negative control 2: mutating the root SRV binding in the manifest (swapping root 2 and root 3) changes all 288 active words. + swapped_manifest = manifest.replace("srv 0 buf root 2\nsrv 1 buf root 3", "srv 0 buf root 3\nsrv 1 buf root 2") + assert swapped_manifest != manifest + manifest_path.write_text(swapped_manifest, encoding="utf-8") + expected_swapped = reference(two_srvs=True, swap_srvs=True) + assert sum(a != b for a, b in zip(expected_swapped, expected_two)) == 288 + got, result = run(directory, consumer, env, "dispatch-root-srv") + assert len(lines(result, "Dispatch(3, 2, 2) translated")) == 1, result.stderr[-3000:] + clean(result) + assert got == expected_swapped and sum(a != b for a, b in zip(got, expected_two)) == 288 + manifest_path.write_text(manifest, encoding="utf-8") + + # Negative control 3: mutating the translated shader (dropping the +128u byte offset on r1.Load) changes all 288 active words. + mutated_hlsl = hlsl.replace("r1.Load(a + 128u)", "r1.Load(a)") + assert mutated_hlsl != hlsl + hlsl_path.write_text(mutated_hlsl, encoding="utf-8") + subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", cso_path, hlsl_path], check=True) + expected_mutated = reference(two_srvs=True, shift1=0) + assert sum(a != b for a, b in zip(expected_mutated, expected_two)) == 288 + got, result = run(directory, consumer, env, "dispatch-root-srv") + assert len(lines(result, "Dispatch(3, 2, 2) translated")) == 1, result.stderr[-3000:] + clean(result) + assert got == expected_mutated and sum(a != b for a, b in zip(got, expected_two)) == 288 + print(f"{adapter}: negative controls (skip Dispatch, swap root SRV bindings, mutate HLSL offset) verified", flush=True) + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + check_single_root_srv(base, consumer, dxc, adapter) + check_two_root_srvs(base, consumer, dxc, adapter) + print(f"startup_compute_root_srv_dispatch: PASS on {adapter}") + + +if __name__ == "__main__": + if len(sys.argv) != 4 or sys.argv[3] not in ("warp", "hardware"): + sys.exit(__doc__) + main(*sys.argv[1:4]) diff --git a/tests/startup_gfx2hlsl_buffer_store_check.py b/tests/startup_gfx2hlsl_buffer_store_check.py index 8a84bbe2dc..fa75e9892e 100644 --- a/tests/startup_gfx2hlsl_buffer_store_check.py +++ b/tests/startup_gfx2hlsl_buffer_store_check.py @@ -212,8 +212,8 @@ def main(): '%s %s' % (result, fail_reason(name))) # 8. The cache revision moved, so a translation from before the store lowering is never loaded. - check('cache key uses revision 28', G.pipeline_key(b'a', b'b', ROOT) == - G.fnv(ROOT, G.fnv(b'b', G.fnv(b'a', G.fnv(b'x2w-startup-shader-28'))))) + check('cache key uses revision 29', G.pipeline_key(b'a', b'b', ROOT) == + G.fnv(ROOT, G.fnv(b'b', G.fnv(b'a', G.fnv(b'x2w-startup-shader-29'))))) if failures: print('FAILED: ' + ', '.join(failures)) diff --git a/tests/startup_gfx2hlsl_bvh_check.py b/tests/startup_gfx2hlsl_bvh_check.py new file mode 100644 index 0000000000..35cecf48d9 --- /dev/null +++ b/tests/startup_gfx2hlsl_bvh_check.py @@ -0,0 +1,394 @@ +"""image_bvh_intersect_ray: the FP32 box-node (kind 5) translation slice. + +The instruction is RDNA 2 MIMG opcode 230. This check covers the translator path and the +box model only: a constant inline BVH T#[12:15], an 11-dword packed address, a constant +node base whose low three bits are 5, and the four child results. Triangle nodes, 16-bit +box nodes, the 64-bit form, A16, NSA and every dynamic descriptor or node base are refused +by name before any HLSL is emitted. The CPU box reference is the one in +tests/gfx1030_bvh_box/check.py; the sort network is the five compare-exchange stages of +Mesa 25.1.0 radv_nir_rt_common.c (MIT). +""" +import math +import os +from pathlib import Path +import shutil +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT / "tools" / "startup")) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import startup_gfx2hlsl_compute_check as C # noqa: E402 + +INVALID = 0xffffffff +SORT_ENABLE = 1 << 31 +RESOURCE_TYPE = 1 << 31 +MASK = 0xffffffff +FLT_MAX = 3.4028234663852886e38 + + +def box(child, depth, x=-8): + return child, (x, -8, depth), (x + 16, 8, depth + 0.5) + + +NODES = { + 0: (box(0x25, 4), box(0x1d, 1), box(0x2d, 2, x=32), box(INVALID, 3)), + 256: (box(0x45, 7), box(0x3d, 5), box(0x35, 3), box(0x0d, 1)), + 384: (box(0x25, 4), box(INVALID, 1), box(0x2d, 2), box(0x35, 3)), +} +ORIGIN = (0.5, -0.5, -1.0) +FORWARD = (0.25, -0.125, 0.5) +RAYS = ( + ("sorted", 0, 19.0, ORIGIN, FORWARD, (0x1d, 0x25, INVALID, INVALID)), + ("clipped", 0, 6.0, ORIGIN, FORWARD, (0x1d, INVALID, INVALID, INVALID)), + ("all_miss", 0, 2.0, ORIGIN, FORWARD, (INVALID,) * 4), + ("all_four", 256, 19.0, ORIGIN, FORWARD, (0x0d, 0x35, 0x3d, 0x45)), + ("reverse", 0, 21.0, (0.0, 0.0, 10.0), (0.25, -0.125, -0.5), (0x25, 0x1d, INVALID, INVALID)), +) +UNSORTED_RAYS = ( + ("unsorted_three_hits", 384, 19.0, ORIGIN, FORWARD, (0x25, 0x2d, 0x35, INVALID)), +) + +failures = [] + + +def check(label, ok, detail=""): + print("%s: %s" % (label, "ok" if ok else "MISMATCH"), flush=True) + if not ok: + failures.append(label) + if detail: + print(" " + detail) + + +def reference(nodes, extent, origin, direction, sort_boxes): + """The fixture reference: slab test, extent clip, compact misses, sort only when asked.""" + hits = [] + for child, lo, hi in nodes: + if child == INVALID: + continue + near, far = 0.0, extent + for lower, upper, start, step in zip(lo, hi, origin, direction, strict=True): + first, second = (lower - start) / step, (upper - start) / step + near, far = max(near, min(first, second)), min(far, max(first, second)) + if near <= far and near < extent: + hits.append((near, child)) + if sort_boxes: + hits.sort() + result = tuple(child for _, child in hits) + return result + (INVALID,) * (4 - len(result)) + + +def model(nodes, extent, origin, direction, sort_boxes): + """The emitted HLSL helper, transcribed: four slabs, keys, five compare-exchange stages.""" + inv = [max(-FLT_MAX, min(1.0 / c, FLT_MAX)) for c in direction] + items = [] + for child, lo, hi in nodes: + if child == INVALID: + items.append([INVALID, FLT_MAX]) + continue + bound0 = [(lo[i] - origin[i]) * inv[i] for i in range(3)] + bound1 = [(hi[i] - origin[i]) * inv[i] for i in range(3)] + tmin = max(min(bound0[i], bound1[i]) for i in range(3)) + tmax = min(max(bound0[i], bound1[i]) for i in range(3)) + hit = not math.isnan(lo[0]) and tmax >= max(0.0, tmin) and tmin < extent + if hit: + items.append([child, tmin if sort_boxes else 0.0]) + else: + items.append([INVALID, FLT_MAX]) + if not sort_boxes: + ordered = [child for child, _key in items if child != INVALID] + return tuple(ordered) + (INVALID,) * (4 - len(ordered)) + for a, b in ((0, 1), (2, 3), (0, 2), (1, 3), (1, 2)): + if items[b][1] < items[a][1]: + items[a], items[b] = items[b], items[a] + return tuple(item[0] for item in items) + + +def translate_program(*, node=0x05, sort_boxes=True, word0=0x00100000, word1=None, word2=0x0b, + word3=RESOURCE_TYPE, loaded_descriptor=False, modifier="", opcode="image_bvh_intersect_ray", + constant_node=True, stage_kind="cs"): + """A straight-line compute program with a constant inline T# and a constant node pointer.""" + if word1 is None: + word1 = SORT_ENABLE if sort_boxes else 0 + if stage_kind != "cs": + class Probe: + kind = stage_kind + try: + G.Stage.op_image_bvh_intersect_ray(Probe(), ("v[32:35]", "v[16:31]", "s[12:15]"), []) + except G.Unsupported as error: + return None, None, [str(error)] + return None, None, ["accepted outside compute"] + decoded = [] + at = 0 + + def add(name, asm, length=8): + nonlocal at + decoded.append((at, length, name, asm)) + at += length + + if loaded_descriptor: + add("s_mov_b32", "s_mov_b32 s10, s6") + add("s_mov_b32", "s_mov_b32 s11, 0") + add("s_load_dwordx4", "s_load_dwordx4 s[12:15], s[10:11], 0x0", 16) + add("s_waitcnt", "s_waitcnt lgkmcnt(0)", 4) + else: + for reg, word in ((12, word0), (13, word1), (14, word2), (15, word3)): + add("s_mov_b32", "s_mov_b32 s%d, 0x%08x" % (reg, word)) + for reg, word in ((16, node), (17, 0x41a00000), (18, 0x3f000000), (19, 0xbf000000), + (20, 0xbf800000), (21, 0x3e800000), (22, 0xbe000000), (23, 0x3f000000), + (24, 0x40800000), (25, 0xc1000000), (26, 0x40000000)): + source = "s4" if reg == 16 and not constant_node else "0x%08x" % word + add("v_mov_b32", "v_mov_b32 v%d, %s" % (reg, source)) + add(opcode, "%s v[32:35], v[16:31], s[12:15]%s" % (opcode, (" " + modifier) if modifier else "")) + add("s_endpgm", "s_endpgm", 4) + refusals = [] + pipe = G.ComputePipeline(b"", C.root_blob(), C.USER7, (1, 1, 1), refusals=refusals, decoded=decoded) + return pipe, pipe.hlsl_cs(), [reason for reason, _kind in refusals] + + +def controls(): + bad = None + for name, offset, extent, origin, direction, expected in RAYS: + actual = reference(NODES[offset], extent, origin, direction, True) + if actual != expected: + bad = (name, actual, expected) + break + check("CPU reference matches the gfx1030 box fixture", bad is None, str(bad)) + + bad = None + for name, offset, extent, origin, direction, expected in RAYS: + actual = model(NODES[offset], extent, origin, direction, True) + if actual != expected: + bad = (name, actual, expected) + break + check("emitted sort network matches the CPU reference", bad is None, str(bad)) + + # Negative control: sort disabled keeps child order. The sorted ray's first word changes. + unsorted = reference(NODES[0], 19.0, ORIGIN, FORWARD, False) + sorted_result = reference(NODES[0], 19.0, ORIGIN, FORWARD, True) + check("sort bit negative control changes word 0", + unsorted[0] == 0x25 and sorted_result[0] == 0x1d, str((unsorted, sorted_result))) + check("model without the sort bit matches the unsorted reference", + model(NODES[0], 19.0, ORIGIN, FORWARD, False) == unsorted, + str((model(NODES[0], 19.0, ORIGIN, FORWARD, False), unsorted))) + for name, offset, extent, origin, direction, expected in UNSORTED_RAYS: + actual = reference(NODES[offset], extent, origin, direction, False) + check("CPU reference keeps child order with the sort bit clear (%s)" % name, actual == expected, + str((actual, expected))) + actual = model(NODES[offset], extent, origin, direction, False) + check("helper keeps child order with the sort bit clear (%s)" % name, actual == expected, + str((actual, expected))) + check("all-miss result is four 0xffffffff words", + reference(NODES[0], 2.0, ORIGIN, FORWARD, True) == (INVALID,) * 4, "") + + pipe, hlsl, refusals = translate_program() + check("constant box32 program translates", pipe is not None and not refusals, str(refusals)) + if pipe is not None: + manifest = pipe.manifest() + check("manifest names the node allocation", "srv 0 bvh base 0x100000 size 0xb" in manifest, manifest) + check("HLSL declares the node buffer", "ByteAddressBuffer r0 : register(t0);" in hlsl, "") + check("HLSL contains the four-result helper", + "uint4 x2w_bvh_intersect_box32" in hlsl and "x2w_bvh_box32_slot" in hlsl, "") + check("the call carries the sort-enabled T# word and four child results", + "0x80000000u" in hlsl and all("v%d = bt" % reg in hlsl for reg in range(32, 36)), + "") + call_line = next(line for line in hlsl.splitlines() if "x2w_bvh_intersect_box32(r0" in line) + check("constant T# passes literals, not descriptor SGPRs", + "s12" not in call_line and "s13" not in call_line, call_line) + + pipe, hlsl, refusals = translate_program(sort_boxes=False) + check("sort-disabled program translates", pipe is not None and not refusals, str(refusals)) + if pipe is not None: + check("sort-disabled call uses a zero sort word", "0x00000000u" in hlsl, "") + + # Every refusal must happen before a helper call or a result VGPR is emitted. + cases = [ + ("triangle node", dict(node=0x00), "triangle node (kind 0)"), + ("16-bit box node", dict(node=0x04), "16-bit box node (kind 4)"), + ("unknown node kind", dict(node=0x06), "node kind 6"), + ("unaligned node", dict(node=0x0d), "not an aligned 128-byte node"), + ("non-constant node", dict(constant_node=False), "non-constant node base"), + ("64-bit form", dict(opcode="image_bvh64_intersect_ray"), "image_bvh64_intersect_ray"), + ("A16", dict(modifier="a16"), "modifier a16"), + ("NSA address", dict(modifier=""), "non-sequential"), + ("loaded descriptor", dict(loaded_descriptor=True), "loaded at run time"), + ("descriptor type", dict(word3=0x60000000), "descriptor type 6 is not 8"), + ("box growing", dict(word1=SORT_ENABLE | (2 << 23)), "box growing amount 2"), + ("base alignment", dict(word0=0x00100008), "not 256-byte aligned"), + ("size zero", dict(word2=0), "does not cover a 128-byte node"), + ("node outside size", dict(node=0x25, word2=3), "outside descriptor size"), + ("absolute base", dict(word0=0, word1=0), "absolute node base"), + ("size high bits", dict(word3=RESOURCE_TYPE | 0x100), "size above 4 GiB"), + ] + for label, kwargs, reason in cases: + if label == "NSA address": + # A non-sequential address is a text form the packed decoder never prints. + pipe, hlsl, refusals = None, None, [] + try: + G.Stage.op_image_bvh_intersect_ray( + type("P", (), {"kind": "cs", "const_u32": lambda self, tok: 5})(), + ("v[32:35]", "[v0, v2, v4, v6, v8, v10, v12, v14, v16, v18, v20]", "s[12:15]"), []) + except G.Unsupported as error: + refusals = [str(error)] + else: + pipe, hlsl, refusals = translate_program(**kwargs) + ok = len(refusals) == 1 and reason in refusals[0] + check("refuses %s" % label, ok, str(refusals)) + if hlsl is not None: + check(" no partial output for %s" % label, + "uint4 bt" not in hlsl and "x2w_bvh_intersect_box32(r" not in hlsl, "") + + pipe, hlsl, refusals = translate_program(stage_kind="ps") + check("refuses a pixel stage", len(refusals) == 1 and "outside a compute stage" in refusals[0], str(refusals)) + + +def find_dxc(): + named = os.environ.get("X2W_DXC") + if named and Path(named).is_file(): + return str(Path(named)) + found = shutil.which("dxc") + if found: + return found + kits = os.environ.get("ProgramFiles(x86)", "") + if kits: + candidates = sorted((Path(kits) / "Windows Kits" / "10" / "bin").glob("*/x64/dxc.exe"), reverse=True) + if candidates: + return str(candidates[0]) + return None + + +def compile_check(hlsl): + dxc = find_dxc() + if dxc is None: + print("dxc compile: skip (no dxc on this host)") + return None + with tempfile.TemporaryDirectory(dir=ROOT / "out" if (ROOT / "out").is_dir() else None) as temporary: + source = Path(temporary) / "bvh_box32.hlsl" + source.write_text(hlsl, encoding="ascii") + result = subprocess.run([dxc, "-T", "cs_6_0", "-E", "main", "-Fo", str(source.with_suffix(".cso")), str(source)], + capture_output=True, text=True) + if result.returncode or result.stderr: + check("dxc compiles the translated helper", False, result.stderr or "exit %d" % result.returncode) + return False + print("dxc compile: ok (%s)" % dxc) + return True + + + + +def ffloat(value): + return "asfloat(0x%08xu)" % struct.unpack("> 3) | 5, sort_word, ffloat(extent), ffloat(origin[0]), ffloat(origin[1]), + ffloat(origin[2]), ffloat(inv[0]), ffloat(inv[1]), ffloat(inv[2]))) + for word in range(4): + lines.append(" data.Store(%du, r%d.%s);" % (512 + 16 * case + 4 * word, case, "xyzw"[word])) + lines.append("}") + return "\n".join(lines) + "\n" + + +def run_dispatch(dxc, runner, adapter, directory, mutate=False): + name = "bvh_dispatch_mut" if mutate else "bvh_dispatch" + source = directory / (name + ".hlsl") + cso = directory / (name + ".cso") + output = directory / (name + ".bin") + source.write_text(dispatch_hlsl(mutate), encoding="ascii") + compiled = subprocess.run([dxc, "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(source)], + capture_output=True, text=True) + if compiled.returncode or compiled.stderr: + raise AssertionError(compiled.stderr or "dxc exited with %d" % compiled.returncode) + result = subprocess.run([runner, adapter, "--raw-uav-dump", str(cso), "1", "608", str(output)], + capture_output=True, text=True) + print(result.stdout, end="") + if result.returncode == 77: + return 77, None + if result.returncode or result.stderr: + raise AssertionError(result.stderr or "offscreen_check exited with %d" % result.returncode) + data = output.read_bytes() + return 0, struct.unpack("<%dI" % (len(data) // 4), data) + + +def check_dispatch(dxc, runner, adapter): + controls() + if not dxc or not runner: + print("dispatch: skip (no dxc or offscreen_check)") + return 77 + out = ROOT / "out" + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=out) as temporary: + directory = Path(temporary) + status, words = run_dispatch(dxc, runner, adapter, directory) + if status == 77: + print("dispatch: skip (adapter unavailable)") + return 77 + for case, (_name, _offset, _extent, _origin, _direction, expected) in enumerate(RAYS): + got = tuple(words[128 + 4 * case:132 + 4 * case]) + check("dispatch case %d %s" % (case, _name), got == expected, + "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in expected])) + for extra, (_name, _offset, _extent, _origin, _direction, expected) in enumerate(UNSORTED_RAYS): + case = len(RAYS) + extra + got = tuple(words[128 + 4 * case:132 + 4 * case]) + check("dispatch case %d %s" % (case, _name), got == expected, + "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in expected])) + status, mutant = run_dispatch(dxc, runner, adapter, directory, mutate=True) + if status == 77: + print("dispatch control: skip (adapter unavailable)") + return 77 + changed = mutant[136:140] + check("dispatch miss-fill control decays case 2", tuple(changed) != (INVALID,) * 4, + "got %s" % ["%08x" % w for w in changed]) + if failures: + print("FAILED: %s" % ", ".join(failures)) + return 1 + print("dispatch: all ok on %s" % adapter) + return 0 + +def main(): + if len(sys.argv) == 5 and sys.argv[1] == "dispatch": + return check_dispatch(sys.argv[2], sys.argv[3], sys.argv[4]) + if len(sys.argv) != 1: + sys.exit(__doc__) + controls() + pipe, hlsl, refusals = translate_program() + assert not refusals, refusals + compile_check(hlsl) + if failures: + print("FAILED: %s" % ", ".join(failures)) + return 1 + print("startup gfx2hlsl bvh box32: all ok") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/startup_gfx2hlsl_cselect_descnum_check.py b/tests/startup_gfx2hlsl_cselect_descnum_check.py new file mode 100644 index 0000000000..40cedf16c5 --- /dev/null +++ b/tests/startup_gfx2hlsl_cselect_descnum_check.py @@ -0,0 +1,363 @@ +"""s_cselect_b32 on descriptor-derived data in the compute stage of tools/startup/gfx2hlsl.py (#2618, C500 rows). + +usage: startup_gfx2hlsl_cselect_descnum_check.py [controls] + startup_gfx2hlsl_cselect_descnum_check.py dispatch + +The C500 compute rows stop at `s_cselect_b32 sX, 0, sX` where sX holds a number computed from a buffer descriptor +(descnum). Such a select can zero a buffer's size, which disables the buffer, so a translation that drops the zero +arm would read real data where the console reads zeros. The select now records both arms and its own offset (the +SCC it read) as an opaque symbol, and every later use that would need its value refuses. + +The fixture is case A of startup_gfx2hlsl_compute_check.py (a descriptor table load s[12:19], a buffer load +through s[12:15], a buffer store through s[16:19]) with synthetic instructions spliced in. Their bytes come from +the RDNA 2 SOP1/SOP2/SOPC/VOP1/VOPC layouts, and the decoder must print the expected text for each. + +Checked (controls): +- accepted: the select with its result dead, in both arm orders, with a literal arm, and on an extracted stride; + the HLSL differs from case A only by the compare's scc line, and sX holds both arms and the select's offset; +- refused, each with its reason: numeric reads (v_mov, s_cmp, v_cmp, m0), scalar ALU on the result, the + structured-to-raw conversion with the selected stride, a copy into the load descriptor's word 1, 2 or 3 (also + through a second copy), a copy into the store descriptor, SCC from an ALU on descriptor data, a read after a + forward join or at a loop head that a path brings the select to, a load whose word 2 is joined after a select on + one path or on a loop back edge, and a select in the high word of a 64-bit ALU source (the same joins and loop + without the select translate); +- still refused as before: s_cselect_b64, m0 and vcc_lo destinations, a raw descriptor word, a pointer or run-time + register arm, and the vertex and pixel stages. +Negative controls, each a mutated translator that must fail a named check: +- zero-arm-dropped: the select keeps only its descnum arm, so the conversion with the selected stride translates; +- load-check-removed: Stage.select_word finds nothing, so a load through a copied select translates; +- alu-check-removed: Stage.refuse_select_source accepts everything, so an ALU copy into word 2 reaches the load; +- join-check-removed: Stage.joined_word finds nothing, so a load after a join with a select on one path translates; +- high-word-unchecked: refuse_select_source sees only the low word of each source, so s_or_b64 of a pair whose high + word holds the select translates. +The dispatch mode runs case A with the dead select on D3D12 and compares all 320 words with case A's reference. +""" +import struct +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 gfx2hlsl as G # noqa: E402 +import startup_gfx2hlsl_compute_check as C # noqa: E402 +import startup_gfx2hlsl_scalar_m0_check as M # noqa: E402 + +ZERO, LIT = 128, 255 + + +def sop1(op, d, a): + return struct.pack(' [libLLVM] + reassemble the fixture sources and compare with the words below; + with a library the extraction runs against it as well + controls the same full run with the extraction driven through the + given LLVM 15 library (LLVM-21 is accepted for a local run; + a recorded CI run should use an LLVM 15 build) + +The fixture builds one gfx1013 pixel program in three variants, all with the same per-pixel arithmetic +and the same two exports: a uniform root-constant compare selects an early path or a normal path, and +the early path transfers to a pure terminating continuation (NOPs, then the program's final s_endpgm): + + - short: the transfer is a plain s_branch onto the continuation; + - calculated: the documented far-transfer chain s_getpc_b64 / s_add_u32 displacement / + s_addc_u32 sign extension / s_setpc_b64 over a short distance; + - far: the same chain over a distance the SOPP branch word cannot encode (>= 32768 reachable + NOP DWORDs sit in the normal path, and the displacement measured from the actual assembled + offsets exceeds the 131068-byte positive s_branch range). + +Every variant is checked three ways: the startup Stage must translate it (its blocks show the jump), +the emitted dispatcher must reproduce the independent per-lane arithmetic oracle for both selector +values, and the bounded FSSM v0x101 extraction of pixel_aot must return the original code exactly. +The negative matrix refuses a register-derived displacement, a missing ADDC, a wrong sign extension, +a signed ADD, a competing entry into the chain, pair clobbering, an address escape, an SCC escape, a +stale scratch pair, an effectful continuation (export, store, barrier, EXEC write), a continuation +ending at the first rather than the final s_endpgm, a target off an +instruction boundary and a target outside the program, each with a named diagnostic. +""" +import re +import struct +import subprocess +import ctypes.util +import sys +import tempfile +import zlib +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent +sys.path.insert(0, str(ROOT / 'tools')) +sys.path.insert(0, str(ROOT / 'tools' / 'startup')) + +import gfx2hlsl as G # noqa: E402 +import pixel_aot # noqa: E402 +import disasm_rdna2 as D # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + + +def resolve_libllvm(): + """The LLVM 15 shared library for the extraction check, or None when this host has none. + + The binary mode takes the library as an optional argument; the plain mode searches the common + install paths, following the discovery order tests/rdna2_tools_check.py uses. + """ + candidates = ['/usr/lib64/llvm15/lib/libLLVM-15.so', 'libLLVM-15.so.1', 'libLLVM-15.so', + 'libLLVM.so.15'] + for candidate in candidates: + path = Path(candidate) + if path.is_file(): + return str(path) + found = ctypes.util.find_library(candidate) + if found and Path(found).is_file(): + return found + for directory in ('/usr/lib/x86_64-linux-gnu', '/usr/lib64/llvm15/lib', '/usr/lib64', + '/usr/lib', '/usr/local/lib'): + option = Path(directory) / candidate + if option.is_file(): + return str(option) + return None + + +LIBRARY = resolve_libllvm() + + +class Pipe: + root = {'params': [{'type': 1, 'count': 1}], 'flags': 0} + + def ud(self, key): + return 0 + + def mrt_kind(self, index): + assert index == 0 + return 'uint' + +# The shared per-pixel arithmetic: p = (x & 0xffff) | (y << 16) over the entry I/J words, then the +# early export (p, p+3, p^0x80000000, p+3) and the normal export (p, p+19, p^0x80000000, p+19), +# all modulo 2^32 (R32G32B32A32_UINT). +PREFIX = ( + ('v_mov_b32_e32 v4, v0', '0003087e'), + ('v_and_b32_e32 v4, 0xffff, v4', 'ff080836ffff0000'), + ('v_lshlrev_b32_e32 v5, 16, v1', '90020a34'), + ('v_or_b32_e32 v4, v4, v5', '040b0838'), + ('v_mov_b32_e32 v1, v4', '0403027e'), + ('v_add_nc_u32_e32 v6, 3, v4', '83080c4a'), + ('v_xor_b32_e32 v7, 0x80000000, v4', 'ff080e3a00000080'), + ('v_add_nc_u32_e32 v8, 19, v4', '9308104a'), +) +COMPARE = ('s_cmp_eq_u32 s8, 0', '088006bf') +EXP_A = ('exp mrt0 v4, v6, v7, v6 done vm', '0f1800f804060706') +EXP_B = ('exp mrt0 v4, v8, v7, v8 done vm', '0f1800f804080708') +END = ('s_endpgm', '000081bf') +NOP = ('s_nop 0', '000080bf') +GETPC = ('s_getpc_b64 s[20:21]', '001f94be') +ADDC_0 = ('s_addc_u32 s21, s21, 0', '15801582') +SETPC = ('s_setpc_b64 s[20:21]', '142080be') +# The SOPP branch word is a signed 16-bit count of DWORDs from the instruction after the branch, so +# 131068 bytes is the largest forward distance one s_branch can encode. +SOPP_LIMIT = 131068 +# The far variant's normal path holds this many reachable NOP DWORDs. +FAR_NOP_DWORDS = 32768 + + +def sopp(name, opcode, dwords): + return ('%s %d' % (name, dwords), struct.pack(' bytes: + encoder = zlib.compressobj(wbits=-15) + payload = encoder.compress(blob) + encoder.flush() + return (bytes([len(name) + 1]) + name + b'\0\0' + + struct.pack('<4I', len(payload), 0, len(payload), len(blob)) + payload) + + +def envelope(code: bytes, name: bytes = b'fixture') -> bytes: + program_start = 288 + base = program_start - 40 + pad = (-(40 + len(code)) % 16) or 16 + body = code + b'\x00\x00\x9f\xbf' * (pad // 4) + extent = 40 + len(body) + image = bytearray(program_start) + body + image[:4] = b'FSSM' + struct.pack_into(' bytes: + archive = directory / 'far-early-out.rpf' + archive.write_bytes(envelope(code)) + return pixel_aot.native_program(archive, 'fixture', llvm=library)[1] + + +# ---- checks --------------------------------------------------------------------------------------- +def check_variant(name, rows, code, offsets, continuation, directory, *, displacement=None, + library=LIBRARY): + stage = G.Stage(Pipe(), 'ps', code) + body = stage.body() + # The emitted CFG: the entry branches on the root constant; the transfer is a jump block. + terms = [term for _off, _lines, term in stage.blocks if term] + assert terms[0][0] == 'branch', (name, stage.blocks) + jumps = [term for term in terms if term[0] == 'jump'] + assert jumps and jumps[-1][1] == offsets[continuation], (name, stage.blocks) + # Both selector values reproduce the independent arithmetic oracle on several entry words. + for ud0 in (0, 1): + for x, y in ((0, 0), (5, 9), (0x1234, 0x5678), (0xffff, 0xffff)): + got = run_dispatcher(body, ud0, x, y) + assert got == oracle(ud0, x, y), (name, ud0, x, y, got) + # The bounded FSSM v0x101 extraction returns the original code exactly; without an LLVM 15 + # library on this host it is skipped, and the binary mode of a machine that has one covers it. + extracted = 'extraction skipped (no LLVM 15 library found)' if library is None else ( + 'extracted exactly' if extract(directory, code, library) == code else 'MISMATCH') + assert extracted in ('extracted exactly', 'extraction skipped (no LLVM 15 library found)'), \ + (name, extracted) + if displacement is not None: + assert displacement > SOPP_LIMIT, (name, displacement) + print('%s: translated, dispatcher oracle matched both selectors, %s (%d bytes)' + % (name, extracted, len(code))) + + +def negative(name, code, expected, extractor): + """A refusal with the named diagnostic, from the startup Stage and the pixel_aot extraction.""" + try: + G.Stage(Pipe(), 'ps', code) + except G.Unsupported as reason: + assert expected in str(reason), (name, str(reason)) + else: + raise AssertionError('%s: the startup translator accepted a refused program' % name) + if extractor is None: + print('%s: refused by the translator (%s); extraction skipped (no LLVM 15 library found)' + % (name, expected)) + return + try: + extractor(code) + except ValueError as reason: + assert expected in str(reason), (name, str(reason)) + else: + raise AssertionError('%s: the extractor accepted a refused program' % name) + print('%s: refused (%s)' % (name, expected)) + + +def replace_row(rows, index, row): + out = list(rows) + out[index] = row + return out + + +def drop_row(rows, index): + return rows[:index] + rows[index + 1:] + + +def check_negatives(directory, rows, code, far_rows, far_code, library=LIBRARY): + ins = decode_all(code) + index_of = {off: i for i, (off, _n, _name, _asm) in enumerate(ins)} + asm_of = {i: asm for i, (_off, _n, _name, asm) in enumerate(ins)} + getpc = next(off for off, _n, name, _asm in ins if name == 's_getpc_b64') + add = index_of[getpc + 4] + addc = next(i for i, (off, _n, name, _asm) in enumerate(ins) if name == 's_addc_u32') + setpc = next(i for i, (off, _n, name, _asm) in enumerate(ins) if name == 's_setpc_b64') + entry = next(i for i, (off, _n, name, _asm) in enumerate(ins) if name == 's_cbranch_scc0') + continuation = len(rows) - 2 + displacement = int(asm_of[add].split(', ')[-1], 0) + + def stage_and_extract(built): + if library is None: + return None + def run(_code): + return extract(directory, built, library) + return run + + # A register-derived displacement: the ADD reads s8, so the target is not a constant. + rows_reg = replace_row(rows, add, ('s_add_u32 s20, s20, s8', '14081480')) + negative('register-derived displacement', words_of(rows_reg), + 's_setpc_b64: unsupported arithmetic on calculated PC words', + stage_and_extract(words_of(rows_reg))) + + # A missing ADDC: an equally long no-op sits where the high-word addition belonged, so the SETPC + # consumes the incomplete low-word pair and every other offset stays as it was. + rows_missing = replace_row(rows, addc, NOP) + negative('missing ADDC', words_of(rows_missing), + 's_setpc_b64: incomplete calculated target (missing high-word addition with carry)', + stage_and_extract(words_of(rows_missing))) + + # A wrong high sign extension: the ADDC adds 1 while the displacement is positive. + rows_wrong = replace_row(rows, addc, ('s_addc_u32 s21, s21, 1', sop2_inline(4, 21, 21, 1))) + negative('wrong sign extension', words_of(rows_wrong), + 's_setpc_b64: calculated PC high word is not the signed displacement extension', + stage_and_extract(words_of(rows_wrong))) + + # A signed ADD in the low word: SOP2 s_add_i32 instead of s_add_u32. + rows_signed = replace_row(rows, add, add_i32(displacement)) + negative('signed low-word ADD', words_of(rows_signed), + 's_setpc_b64: calculated PC word escapes into s_add_i32', + stage_and_extract(words_of(rows_signed))) + + # A competing entry: the entry branch targets the ADD, entering the chain without its GETPC base. + branch_dwords = (ins[add][0] - ins[entry][0] - 4) // 4 + rows_competing = replace_row(rows, entry, cbranch_scc0(branch_dwords)) + negative('competing entry into the chain', words_of(rows_competing), + 's_setpc_b64: unknown or ambiguous input pair for calculated PC low-word addition', + stage_and_extract(words_of(rows_competing))) + + # Pair clobbering: an s_mov_b32 of the high word between the ADDC and the SETPC. + rows_clobber = rows[:addc + 1] + [('s_mov_b32 s21, 0', '800395be')] + rows[addc + 1:] + negative('pair clobbering', words_of(rows_clobber), + 's_setpc_b64: unknown or ambiguous calculated target', + stage_and_extract(words_of(rows_clobber))) + + # An address escape: the early block reads the low word as data between the ADDC and the SETPC. + rows_escape = rows[:setpc] + [('v_mov_b32_e32 v9, s20', '1402127e')] + rows[setpc:] + negative('address escape', words_of(rows_escape), + 's_setpc_b64: calculated PC word escapes into v_mov_b32_e32', + stage_and_extract(words_of(rows_escape))) + + # An SCC escape: an SCC-reading branch sits between the ADDC and the SETPC. + rows_scc = rows[:setpc] + [('s_cbranch_scc1 0', '000085bf')] + rows[setpc:] + negative('SCC escape', words_of(rows_scc), + 's_setpc_b64: calculated PC SCC escapes into s_cbranch_scc1', + stage_and_extract(words_of(rows_scc))) + + # A stale scratch pair: the program writes s21 before the chain, so the pair is not fresh. + rows_stale = replace_row(rows, 0, ('s_mov_b32 s21, 5', '850395be')) + negative('stale scratch pair', words_of(rows_stale), + 'far early-out: the scratch pair s[20:21] is not fresh', + stage_and_extract(words_of(rows_stale))) + + # Effectful continuations: an export, a store, a barrier and an EXEC write each refuse. + for row, label in ((('exp mrt0 v4, v4, v4, v4 done vm', '0f1800f804040404'), 'an export'), + (('buffer_store_dword v5, v6, s[16:19], 0 offen', '001070e006050480'), 'a store'), + (('s_barrier', '00008abf'), 'a barrier'), + (('s_mov_b32 exec_lo, 0', '8003febe'), 'an EXEC write')): + rows_effect = replace_row(rows, continuation, row) + negative('effectful continuation (%s)' % label, words_of(rows_effect), + 'far early-out: the continuation instruction', stage_and_extract(words_of(rows_effect))) + + # A continuation ending at the first rather than the final s_endpgm: one s_nop is inserted + # before the first exit and the ADD re-aimed four bytes earlier onto it, so the transfer is + # proven and its continuation is pure, but it terminates before the program's final exit. + first_end = next(i for i, row in enumerate(rows) if row == END) + rows_first = rows[:first_end] + [NOP] + rows[first_end:] + rows_first = replace_row(rows_first, add, add_u32(displacement - 4)) + negative('continuation ends before the final exit', words_of(rows_first), + "far early-out: the continuation ends at", + stage_and_extract(words_of(rows_first))) + + # A target off an instruction boundary: one byte past the continuation start is unaligned. + rows_boundary = replace_row(rows, add, add_u32(displacement + 1)) + negative('target off an instruction boundary', words_of(rows_boundary), + 's_setpc_b64: unaligned calculated branch target', + stage_and_extract(words_of(rows_boundary))) + + # A target outside the program: the displacement points past the final exit. The far rows hold + # the same shape with an already-literal ADD, so the wider displacement moves no instruction. + far_ins = decode_all(far_code) + far_add = next(i for i, (off, n, name, asm) in enumerate(far_ins) if name == 's_add_u32') + far_displacement = int(far_ins[far_add][3].split(', ')[-1], 0) + rows_outside = replace_row(far_rows, far_add, add_u32(far_displacement + 4096)) + negative('target outside the program', words_of(rows_outside), + 's_setpc_b64: target', + stage_and_extract(words_of(rows_outside))) + + +def main(): + args = sys.argv[1:] + if args and args[0] == 'binary': + if len(args) not in (2, 3): + raise SystemExit(__doc__) + return check_binary(args[1], args[2] if len(args) == 3 else None) + library = LIBRARY + if args and args[0] == 'controls': + # The explicit selection drives the extraction half of every control below; it is not + # captured globally, so check_binary and the no-argument auto-discovery keep their own. + if len(args) != 2 or not Path(args[1]).is_file(): + raise SystemExit(__doc__) + library = args[1] + elif args: + raise SystemExit(__doc__) + + short_rows, short_code, short_offsets = variant(BRANCH) + calc_rows, calc_code, calc_offsets = variant(CHAIN) + far_rows, far_code, far_offsets = variant(CHAIN, FAR_NOP_DWORDS) + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + check_variant('short s_branch', short_rows, short_code, short_offsets, len(short_rows) - 2, directory, + library=library) + check_variant('short calculated', calc_rows, calc_code, calc_offsets, len(calc_rows) - 2, directory, + library=library) + # The far variant: the displacement measured from the actual assembled offsets must exceed + # the positive SOPP s_branch range, and its NOP run must be reachable in the normal path. + continuation = len(far_rows) - 2 + ins = decode_all(far_code) + getpc = next(off for off, _n, name, _asm in ins if name == 's_getpc_b64') + displacement = far_offsets[continuation] - (getpc + 4) + nops = sum(1 for _off, _n, name, _asm in ins if name == 's_nop') + assert nops >= FAR_NOP_DWORDS, (nops, FAR_NOP_DWORDS) + check_variant('far calculated', far_rows, far_code, far_offsets, continuation, directory, + displacement=displacement, library=library) + print('far displacement %#x exceeds the SOPP positive range %d' % (displacement, SOPP_LIMIT)) + check_negatives(directory, calc_rows, calc_code, far_rows, far_code, library=library) + print('Far early-out: three variants, dispatcher oracle and refusal controls passed') + + +def assemble(llvm_mc, source): + run = subprocess.run([llvm_mc, '-arch=amdgcn', '-mcpu=gfx1013', '-show-encoding'], input=source, + capture_output=True, text=True, check=True) + words = bytearray() + for line in run.stdout.splitlines(): + m = re.search(r'encoding: \[([^\]]*)\]', line) + if m: + words += bytes(int(b, 16) for b in m.group(1).replace(' ', '').split(',')) + return bytes(words) + + +def check_binary(llvm_mc, library=None): + for name, (rows, code, _offsets) in (('short s_branch', variant(BRANCH)), + ('short calculated', variant(CHAIN)), + ('far calculated', variant(CHAIN, FAR_NOP_DWORDS))): + built = assemble(llvm_mc, source_of(rows)) + assert built == code, (name, built[:80].hex(), code[:80].hex(), len(built), len(code)) + if library is not None: + with tempfile.TemporaryDirectory() as tmp: + assert extract(Path(tmp), code, library) == code, name + if library is not None: + print('fixture words match llvm-mc, and the extraction of each variant through %s is exact' % library) + else: + print('fixture words match llvm-mc') + return 0 + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_fract_check.py b/tests/startup_gfx2hlsl_fract_check.py index 8d9c2de357..b14174be6c 100644 --- a/tests/startup_gfx2hlsl_fract_check.py +++ b/tests/startup_gfx2hlsl_fract_check.py @@ -170,8 +170,8 @@ def float_capped(word): repr((seed and seed.group(1), literal and literal.group(1)))) check('the two literals are identical', seed and literal and seed.group(1) == literal.group(1), repr((seed and seed.group(1), literal and literal.group(1)))) -check('the revision is x2w-startup-shader-28, after the precise v_fma_mix lowering', - bool(seed and seed.group(1) == 'x2w-startup-shader-28'), repr(seed and seed.group(1))) +check('the revision is x2w-startup-shader-29, after the vcc_hi may-write of the mad64 carry-out', + bool(seed and seed.group(1) == 'x2w-startup-shader-29'), repr(seed and seed.group(1))) def key_from_seed(word): diff --git a/tests/startup_gfx2hlsl_image_get_lod_check.py b/tests/startup_gfx2hlsl_image_get_lod_check.py index f0508e5ad1..c6a13633dc 100644 --- a/tests/startup_gfx2hlsl_image_get_lod_check.py +++ b/tests/startup_gfx2hlsl_image_get_lod_check.py @@ -1,4 +1,4 @@ -"""image_get_lod on a 2D texture in tools/startup/gfx2hlsl.py (M200-01 L). +"""image_get_lod on a 2D texture and a 2D array in tools/startup/gfx2hlsl.py (M200-01 L). image_get_lod returns [0] the LOD a sample would use, clamped, and [1] the computed LOD before the clamp (Mesa nir_texop_lod, emitted by ACO as image_get_lod; GLSL textureQueryLod x/y). It is lowered to HLSL @@ -8,14 +8,23 @@ the read does. The clamped value depends on the sampler's LOD limits and bias, so the sampler must be a constant descriptor under the validation of image_sample_b. +The 2D-array form (dim:SQ_RSRC_IMG_2D_ARRAY) takes a third address dword, the slice, which the decoder reads +back. DXIL CalculateLOD uses two active coordinates (c0, c1) for Texture2DArray -- the slice is not part of the +LOD -- and HLSL's Texture2DArray CalculateLevelOfDetail takes float2, so the slice register is consumed but +dropped from the call: Texture2DArray r0 queried at float2(u, v), exactly the two-component coordinate of +glslang's hlsl.calculatelod.dx10.frag ("LOD queries do not pass array level in coordinate"). + Fixture (synthetic): the recorded c_lz stage of startup_image_sample_c_check with the MIMG opcode set to 0x60 -(image_get_lod; the decoder reads it back with a 2-register address), sampler word 2 loaded from a literal (mip -filter point), and for the second form dmask 0x3. -Checks: dmask 0x1, 0x2 and 0x3 lower to the two calls on the sampler, which carries its LOD limits. A uniform join -before the read is accepted. Controls (refused): dmask 0x4, a 2D array, s_cbranch_vccz/execz before -the read, a sampler LOD bias, a sampler with mipmapping disabled, and the stage without op_image_get_lod -(negative control: refused as on main). - draw [fxc]: also compile the dmask 0x3 stage with dxc ps_6_0 (and fxc ps_5_1). +(image_get_lod; the decoder reads it back with a 2-register, or 3-register for the array, address), sampler +word 2 loaded from a literal (mip filter point), and for the second form dmask 0x3. The array fixture keeps the +original v2 = 1.0 as its slice dword; a variant swaps the slice register pair so the consumed dword is proven +to come from the address position, not the register number. +Checks: dmask 0x1, 0x2 and 0x3 lower to the two calls on the sampler, which carries its LOD limits, on a 2D +texture and a 2D array (Texture2DArray r0, srv tex2da, slice dropped). A uniform join before the read is +accepted on both. Controls (refused): dmask 0x4, a 3D image, s_cbranch_vccz/execz before the read (2D and +array), a sampler LOD bias, a sampler with mipmapping disabled, an array decoded with two address registers, +and the stage without op_image_get_lod (negative control: refused as on main). + draw [fxc]: also compile the dmask 0x3 2D and 2D-array stages with dxc ps_6_0 (and fxc ps_5_1). """ import struct import subprocess @@ -41,15 +50,20 @@ def sopp(op, simm): return struct.pack(' right after the read, back to it (a divergent back edge spanning the read) code = code[:AT + 8] + sopp(back_op, -3) + code[AT + 8:] @@ -97,7 +111,43 @@ def controls(): _, text = ps(stage(join=True)) assert call in text and 'v4 = U(t.x);' in text, text refused(stage(dmask=4), 'image_get_lod form') - refused(stage(dim=5), 'image_get_lod form') # SQ_RSRC_IMG_2D_ARRAY + refused(stage(dim=2), 'image_get_lod form') # SQ_RSRC_IMG_3D + # The 2D-array form: Texture2DArray, the slice consumed and dropped from the float2 coordinate. + array_call = ('t = float4(r0.CalculateLevelOfDetail(q0, float2(F(v0), F(v1))), ' + 'r0.CalculateLevelOfDetailUnclamped(q0, float2(F(v0), F(v1))), 0.0, 0.0);') + listing = [a for _, _, _, a in G.decode(stage(dim=5))] + assert 'image_get_lod v4, v[0:2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D_ARRAY' in listing, listing + array_pipe, text = ps(stage(dim=5)) + assert array_call in text and 'v4 = U(t.x);' in text, text + assert 'Texture2DArray r0 : register(t0);' in text and 'Texture2D<' not in text, text + assert 'srv 0 tex2da table 0 0' in array_pipe.manifest(), array_pipe.manifest() + assert 'smpl 0 0x8001012 0x0 0x4000000 0x0' in array_pipe.manifest(), array_pipe.manifest() + _, text = ps(stage(dmask=3, dim=5)) + assert array_call in text and 'v4 = U(t.x);' in text and 'v5 = U(t.y);' in text, text + _, text = ps(stage(dmask=2, dim=5)) + assert array_call in text and 'v4 = U(t.y);' in text and 'U(t.x)' not in text, text + code = stage(dmask=3, dim=5, nsa=[1, 3, 0, 0]) + listing = [a for _, _, _, a in G.decode(code)] + assert 'image_get_lod v[4:5], [v0, v1, v3], s[16:23], s[24:27] dmask:0x3 dim:SQ_RSRC_IMG_2D_ARRAY' in listing, listing + _, text = ps(code) + assert array_call in text and 'F(v2)' not in text and 'F(v3)' not in text, text + _, text = ps(stage(branch=True, dim=5)) + assert array_call in text and 'v4 = U(t.x);' in text, text + _, text = ps(stage(join=True, dim=5)) + assert array_call in text and 'v4 = U(t.x);' in text, text + for op in (7, 9): # vccnz, execnz back edge after the array read + refused(stage(dim=5, back_op=op), 'image_get_lod needs implicit derivatives') + for op in (6, 7, 8, 9): # vccz, vccnz, execz, execnz + refused(stage(dim=5, cf_op=op), 'image_get_lod needs implicit derivatives') + refused(stage(dim=5, word2=MIP_POINT | 1), 'image_get_lod with a sampler LOD bias') + refused(stage(dim=5, word2=0), 'image_get_lod with mipmapping disabled') + # An array decoded with two address registers is refused (the slice dword would be unread). + original = G.D.MIMG_DIMS[5] + G.D.MIMG_DIMS[5] = (original[0], 2, original[2]) + try: + refused(stage(dim=5), 'image_get_lod form') + finally: + G.D.MIMG_DIMS[5] = original _, text = ps(stage(divergent=True)) # a cleared EXEC is an exact per-lane write: the quad program keeps the proof assert call in text, text for op in (7, 9): # vccnz, execnz back edge after the read @@ -112,26 +162,30 @@ def controls(): refused(stage(), 'image_get_lod') finally: G.Stage.op_image_get_lod = saved - print('image_get_lod: CalculateLevelOfDetail / Unclamped for dmask 0x1, 0x2 and 0x3; uniform join/branch before ' - 'the read accepted, also after a cleared EXEC; dmask 0x4, a 2D array, vcc/exec branches, a sampler bias and a ' - 'sampler without mipmapping refused; refused without the handler') + print('image_get_lod: CalculateLevelOfDetail / Unclamped for dmask 0x1, 0x2 and 0x3 on a 2D texture and a 2D ' + 'array (Texture2DArray, slice consumed and dropped from the float2 coordinate, manifest srv tex2da, NSA ' + 'address); uniform join/branch before the read accepted on both, also after a cleared EXEC; dmask 0x4, a ' + '3D image, vcc/exec branches, a sampler bias and a sampler without mipmapping refused on both, an array ' + 'with two address registers refused; refused without the handler') return pipe def compile_check(dxc, fxc=None): - _, text = ps(stage(dmask=3)) with tempfile.TemporaryDirectory() as tmp: - path = Path(tmp) / 'ps.hlsl' - path.write_text(text) - runs = [('dxc', [dxc, '-T', 'ps_6_0', '-E', 'main', '-Fo', str(Path(tmp) / 'a.cso'), str(path)])] - if fxc: - runs.append(('fxc', [fxc, '/nologo', '/T', 'ps_5_1', '/E', 'main', '/Fo', str(Path(tmp) / 'b.cso'), - str(path)])) - for kind, args in runs: - r = subprocess.run(args, capture_output=True, text=True, timeout=60) - if r.returncode: - raise AssertionError('%s: %s' % (kind, r.stderr[-1500:])) - print('%s compiles the dmask 0x3 stage' % kind) + for name, text in (('2D', ps(stage(dmask=3))[1]), ('2D array', ps(stage(dmask=3, dim=5))[1])): + slug = name.replace(' ', '_') + path = Path(tmp) / ('ps_%s.hlsl' % slug) + path.write_text(text) + runs = [('dxc', [dxc, '-T', 'ps_6_0', '-E', 'main', '-Fo', str(Path(tmp) / ('%s.cso' % slug)), + str(path)])] + if fxc: + runs.append(('fxc', [fxc, '/nologo', '/T', 'ps_5_1', '/E', 'main', '/Fo', + str(Path(tmp) / ('%s_fxc.cso' % slug)), str(path)])) + for kind, args in runs: + r = subprocess.run(args, capture_output=True, text=True, timeout=60) + if r.returncode: + raise AssertionError('%s (%s): %s' % (kind, name, r.stderr[-1500:])) + print('%s compiles the dmask 0x3 %s stage' % (kind, name)) def main(): diff --git a/tests/startup_gfx2hlsl_image_store_3d1d_check.py b/tests/startup_gfx2hlsl_image_store_3d1d_check.py new file mode 100644 index 0000000000..9d892e749a --- /dev/null +++ b/tests/startup_gfx2hlsl_image_store_3d1d_check.py @@ -0,0 +1,88 @@ +"""Check full compute image stores to 1D and 3D texture UAVs.""" +import argparse + +import startup_compute_image_store_check as A +from startup_gfx2hlsl_compute_check import G, assemble, refused, root_blob +from startup_pixel_image_store_check import WORDS as PIXEL_WORDS, translate as pixel_pipeline + + +FORMS = { + 'volume': ('3D', 'v[2:4]', 's[16:23]', '101f20f002080400', 'uint3(v2, v3, v4)'), + 'volume-nsa': ('3D', '[v2, v3, v5]', 's[16:23]', '121f20f00208040003050000', 'uint3(v2, v3, v5)'), + 'line': ('1D', 'v0', 's[8:15]', '001f20f000080200', 'uint(v0)'), +} +VALUES = A.ARRAY_VALUES +DATA = bytes.fromhex( + 'ff02107e0000403f' # v_mov_b32_e32 v8, 0x3f400000 + 'ff02127e0000803e' # v_mov_b32_e32 v9, 0x3e800000 + 'ff02147e00008140' # v_mov_b32_e32 v10, 0x40810000 + 'ff02167e010081bf' # v_mov_b32_e32 v11, 0xbf810001 +) + + +def group(form): + return (4, 1, 1) if form == 'line' else A.fixture.GROUP + + +def program(form, store=None): + # s[12:13] is the fixed table pointer. Compute the global X before the 1D descriptor overwrites s10. + prefix = bytes.fromhex('07038cbe80038dbe') # s_mov_b32 s12, s7; s_mov_b32 s13, 0 + if form == 'line': + address = bytes.fromhex( + '000046d70a040104' # v_lshl_add_u32 v0, s10, 2, v0 + '06020cf4400000fa' # s_load_dwordx8 s[8:15], s[12:13], 0x40 + ) + else: + address = bytes.fromhex( + '06040cf4400000fa' # s_load_dwordx8 s[16:23], s[12:13], 0x40 + '020046d70a040104' # v_lshl_add_u32 v2, s10, 2, v0 + '030046d70b020504' # v_lshl_add_u32 v3, s11, 1, v1 + ) + address += bytes.fromhex('81020a7e' if form == 'volume-nsa' else '8102087e') # z = 1 + instruction = bytes.fromhex(FORMS[form][3]) if store is None else store + return prefix + address + bytes.fromhex('7fc08cbf') + DATA + instruction + A.ARRAY_END + + +def pipeline(form, store=None): + return G.ComputePipeline(program(form, store), root_blob(3), A.RSRC2, group(form)) + + +def controls(llvm_mc): + ps = pixel_pipeline(PIXEL_WORDS).ps + for form, (dim, address, descriptor, words, index) in FORMS.items(): + dim_mod = f'dim:SQ_RSRC_IMG_{dim}' + asm = f'image_store v[8:11], {address}, {descriptor} dmask:0xf {dim_mod} unorm' + store = bytes.fromhex(words) + assert G.D.decode_instruction(store, 0)[2] == asm + if llvm_mc: + assert assemble(llvm_mc, asm + '\n') == store, asm + pipe = pipeline(form) + hlsl, manifest = pipe.hlsl_cs(), pipe.manifest() + # Manual mutants: dropping the third coordinate or mapping 1D to 2D must fail these assertions. + assert f'RWTexture{dim} w0 : register(u0);' in hlsl, hlsl + assert f'w0[{index}] = asfloat(uint4(v8, v9, v10, v11));' in hlsl, hlsl + assert f'uav 0 tex{dim.lower()} float table 1 64 channels 4' in manifest.splitlines(), manifest + mods = ['dmask:0xf', dim_mod, 'unorm'] + refused('only 2D images', lambda: ps.op_image_store(['v[8:11]', address, descriptor], mods)) + wrong_width = 'v[0:1]' + refused('with 2 address registers', lambda: pipe.cs.op_image_store(['v[8:11]', wrong_width, descriptor], mods)) + for d16 in (False, True): + partial = bytearray(store) + partial[1] = (partial[1] & 0xf0) | 0x3 + if d16: + partial[7] |= 0x80 + refused('typed UAV store writes all four channels', lambda: pipeline(form, bytes(partial))) + # d16 with the full mask takes the same packed-half path as 2D: two data VGPRs unpacked low half first. + # Manual mutant: dropping the f16tof32 unpack for these kinds must fail this assertion. + packed = bytearray(store) + packed[7] |= 0x80 + d16_hlsl = pipeline(form, bytes(packed)).hlsl_cs() + d16_store = f'w0[{index}] = float4(f16tof32(v8 & 0xffffu), f16tof32(v8 >> 16), f16tof32(v9 & 0xffffu), f16tof32(v9 >> 16));' + assert d16_store in d16_hlsl, d16_hlsl + print('Compute 1D, 3D and 3D NSA stores, d16 full-mask stores, manifest and refusal checks passed') + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--llvm-mc') + controls(parser.parse_args().llvm_mc) diff --git a/tests/startup_gfx2hlsl_ldexp_check.py b/tests/startup_gfx2hlsl_ldexp_check.py new file mode 100644 index 0000000000..4381fd0052 --- /dev/null +++ b/tests/startup_gfx2hlsl_ldexp_check.py @@ -0,0 +1,322 @@ +"""Verify that v_ldexp_f32 lowers to ldexp32 with valid float/integer operands and refuses invalid modifiers. + +Refs #2618. +""" +from pathlib import Path +import re +import struct +import sys + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) + +import gfx2hlsl as G # noqa: E402 +import startup_gfx2hlsl_compute_check as C # noqa: E402 + + +def vop3a(op, vdst, src0, src1, src2=0, *, abs_bits=0, clamp=0, omod=0, neg=0, lit=None): + """Encode one synthetic gfx1013 VOP3A instruction.""" + w0 = 0xd4000000 | (op << 16) | (clamp << 15) | (abs_bits << 8) | vdst + w1 = (neg << 29) | (omod << 27) | (src2 << 18) | (src1 << 9) | src0 + out = struct.pack('<2I', w0, w1) + if lit is not None: + out += struct.pack('> 23) & 0xff + mant = bits & 0x7fffff + if exp == 0xff or (exp == 0 and mant == 0): + return bits + e = exp + if exp == 0: + shift = 23 - (mant.bit_length() - 1) + mant = (mant << shift) & 0x7fffff + e = 1 - shift + e += max(-512, min(512, delta)) + if e >= 255: + return sign | 0x7f800000 + if e <= 0: + if e < -23: + return sign + full = mant | 0x800000 + shift = 1 - e + half_bit = 1 << (shift - 1) + mask = (1 << shift) - 1 + rem = full & mask + q = full >> shift + if rem > half_bit or (rem == half_bit and (q & 1) != 0): + q += 1 + return sign | q + return sign | (e << 23) | mant + + def f2u(f): return struct.unpack(' rounds to 0) + assert ldexp32_sim(f2u(1.0), -150) == 0 + # Subnormal 1.5 * 2^-150 rounds up to 1 ULP + assert ldexp32_sim(f2u(1.5), -150) == 1 + + +def main(): + check_helper_parity() + check_translations() + check_refusals() + check_negative_controls() + check_decode_and_lower() + print('gfx2hlsl v_ldexp_f32 lowering and refusal checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_lerp_u8_check.py b/tests/startup_gfx2hlsl_lerp_u8_check.py new file mode 100644 index 0000000000..7b50654c52 --- /dev/null +++ b/tests/startup_gfx2hlsl_lerp_u8_check.py @@ -0,0 +1,186 @@ +"""Unsigned per-byte average with rounding (v_lerp_u8) in tools/startup/gfx2hlsl.py. + + (no arguments) translation, on-demand helper, value-evaluation, refusal and mutation + controls, pure Python + draw [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input triples and compare the four result words + +AMD RDNA 2 ISA V_LERP_U8 (VOP3A opcode 0x14d): + D.u[7:0] = (S0.u[7:0] + S1.u[7:0] + S2.u[0]) >> 1 + D.u[15:8] = (S0.u[15:8] + S1.u[15:8] + S2.u[8]) >> 1 + D.u[23:16] = (S0.u[23:16] + S1.u[23:16] + S2.u[16]) >> 1 + D.u[31:24] = (S0.u[31:24] + S1.u[31:24] + S2.u[24]) >> 1 +""" +import re +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + refused, + vs_words, + words_text, +) +from startup_gfx2hlsl_sad_check import HlslExpr, vop3a # noqa: E402 + +OPCODE = 0x14d +BODY_WORDS = b''.join(vop3a(OPCODE, 12 + lane, 256 + lane, 256 + 4 + lane, 256 + 8 + lane) for lane in range(4)) +PS_WORDS = PRE_WORDS + BODY_WORDS + POST_WORDS + + +def ref_lerp_u8(a, b, c): + a, b, c = a & MASK, b & MASK, c & MASK + out = 0 + for shift in (0, 8, 16, 24): + out |= ((((a >> shift) & 0xff) + ((b >> shift) & 0xff) + ((c >> shift) & 1)) >> 1) << shift + return out + + +U8_WORDS = ( + 0x00000000, 0x01020304, 0x04030201, 0x7f80ff00, 0x807f00ff, + 0xfefdfcfb, 0x01010101, 0x7fffffff, 0x80000000, 0xffffffff, +) +ROUND_WORDS = ( + 0x00000000, 0x01000100, 0x00010001, 0xfe02fe00, 0xff01ff01, 0xffffffff, +) + +DRAW_SETS = ( + ( + (0x01020304, 0x04030201, 0xfe02fe00), # upper S2 byte bits set, all LSBs 0 + (0x01020304, 0x04030201, 0x01010101), # all S2 byte LSBs 1 + (0x7f80ff00, 0x807f00ff, 0x01000100), # alternating LSBs + boundary sums + (0xffffffff, 0xffffffff, 0xffffffff), # max sum 511 >> 1 == 255 in every byte + ), + ( + (0x00000000, 0x01010101, 0xfe00fe00), # 0+1+0 >> 1 == 0 vs upper bits ignored + (0x00000000, 0x01010101, 0x01010101), # 0+1+1 >> 1 == 1 + (0xfefdfcfb, 0x01020304, 0x00010001), # sum 255 + carry -> 256 >> 1 == 128 + (0x12345678, 0x9abcdef0, 0xab01cd00), # mixed bytes and S2 upper bits + ), +) + + +def extract_helper(hlsl): + m = re.search(r'uint lerp_u8\(uint a, uint b, uint c\)\s*\{\s*return\s+(.+?);\s*\}', hlsl) + assert m, 'lerp_u8 helper missing from HLSL' + return m.group(1) + + +def controls(): + pipe = G.Pipeline(vs_words(DRAW_SETS[0]), PS_WORDS, root_blob()) + ps = pipe.hlsl_ps() + check('lerp_u8 helper emitted on demand', 'uint lerp_u8(uint a, uint b, uint c)' in ps) + for lane in range(4): + expected_line = f'v{12 + lane} = lerp_u8(v{lane}, v{4 + lane}, v{8 + lane});' + check(f'lane {lane} assignment emitted', expected_line in ps) + + # On-demand check: a pixel shader without v_lerp_u8 must not emit lerp_u8(). + plain_ps = G.Pipeline(vs_words(DRAW_SETS[0]), PRE_WORDS + POST_WORDS, root_blob()).hlsl_ps() + check('lerp_u8 omitted when unused', 'lerp_u8(' not in plain_ps) + + # Evaluate the exact emitted helper body over 600 edge triples. + evaluator = HlslExpr(extract_helper(ps)) + for a in U8_WORDS: + for b in U8_WORDS: + for c in ROUND_WORDS: + got = evaluator.run({'a': a, 'b': b, 'c': c})[0] + want = ref_lerp_u8(a, b, c) + assert got == want, (hex(a), hex(b), hex(c), hex(got), hex(want)) + print(f'v_lerp_u8: emitted helper matches reference on {len(U8_WORDS) * len(U8_WORDS) * len(ROUND_WORDS)} cases: ok') + + # Accepted operand forms (VGPR, SGPR, inline constants, literal) and exec-masked emission. + for asm in ( + 'v_lerp_u8 v12, v0, v4, v8', + 'v_lerp_u8 v12, s4, v4, v8', + 'v_lerp_u8 v12, 1, v4, 0', + 'v_lerp_u8 v12, 0x01020304, v4, v8', + ): + probe = Probe() + probe.lower('v_lerp_u8', asm, [o.strip() for o in asm.split(None, 1)[1].split(',')], []) + assert probe.lines and 'lerp_u8(' in probe.lines[0], (asm, probe.lines) + probe_masked = Probe() + probe_masked.exec_known = False + probe_masked.lower('v_lerp_u8', 'v_lerp_u8 v12, v0, v4, v8', ['v12', 'v0', 'v4', 'v8'], []) + check('exec-masked v_lerp_u8 guards assignment', + probe_masked.lines == ['if (exec & 1) v12 = lerp_u8(v0, v4, v8);']) + print('accepted operand forms translate: ok') + + # Refusals: VOP3A encoding neg/abs/clamp/omod/op_sel, plus wrong operand counts. + def must_refuse(fn, label, needle=''): + try: + fn() + except G.Unsupported as error: + check(f'{label} refused', needle in str(error) if needle else bool(str(error))) + else: + raise AssertionError(f'{label} was accepted') + + for label, bad, needle in ( + ('abs0', vop3a(OPCODE, 12, 256, 260, 264, abs_bits=1), 'with neg/abs'), + ('neg2', vop3a(OPCODE, 12, 256, 260, 264, neg=4), 'with neg/abs'), + ('neg_inline0', vop3a(OPCODE, 12, 129, 260, 264, neg=1), 'with neg/abs'), + ('abs_inline0', vop3a(OPCODE, 12, 129, 260, 264, abs_bits=1), 'with neg/abs'), + ('clamp', vop3a(OPCODE, 12, 256, 260, 264, clamp=1), ''), + ('omod', vop3a(OPCODE, 12, 256, 260, 264, omod=1), ''), + ('op_sel', vop3a(OPCODE, 12, 256, 260, 264, op_sel=1), ''), + ): + must_refuse(lambda b=bad: G.Pipeline(vs_words(DRAW_SETS[0]), PRE_WORDS + b + POST_WORDS, root_blob()), label, needle) + for bad_ops in (['v12', 'v0', 'v4'], ['v12', 'v0', 'v4', 'v8', 'v9']): + must_refuse(lambda ops=bad_ops: Probe().lower('v_lerp_u8', 'v_lerp_u8', ops, []), f'arity {len(bad_ops)}') + print('modifiers and wrong operand counts refused: ok') + + +def check_draw(dxc, renderer, adapter, fxc=None): + controls() + compilers = [('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else [] + compilers.append(('dxc', dxc, 'vs_6_0', 'ps_6_0')) + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for tag, compiler, vs_profile, ps_profile in compilers: + for idx, triples in enumerate(DRAW_SETS): + pipe = G.Pipeline(vs_words(triples), PS_WORDS, root_blob()) + vs_bin = compile_hlsl(compiler, tag, pipe.hlsl_vs(), f'{tag}_vs_{idx}', vs_profile, directory) + ps_text = pipe.hlsl_ps() + ps_bin = compile_hlsl(compiler, tag, ps_text, f'{tag}_ps_{idx}', ps_profile, directory) + want = words_text(ref_lerp_u8(*t) for t in triples) + run = draw(renderer, adapter, vs_bin, ps_bin, want) + sys.stdout.write(run.stdout) + if run.returncode == 77: + sys.exit(77) + assert run.returncode == 0, f'{tag} set {idx} failed:\n{run.stdout}\n{run.stderr}' + print(f'{tag} v_lerp_u8 draw {idx}: {want}') + if idx == 0: + # Mutation 1: drop `& 1u` so upper S2 byte bits leak into the byte average. + mut1 = ps_text.replace('(c & 1u)', '(c & 0xffu)').replace('((c >> 8) & 1u)', '((c >> 8) & 0xffu)') + assert mut1 != ps_text + mut1_bin = compile_hlsl(compiler, tag, mut1, f'{tag}_ps_mut_mask', ps_profile, directory) + run_m1 = draw(renderer, adapter, vs_bin, mut1_bin, want) + assert run_m1.returncode != 0, f'{tag} upper-bit mask mutation escaped' + print(f'{tag} v_lerp_u8 mask mutation: fails as expected (rc={run_m1.returncode})') + # Mutation 2: drop rounding bits (S2 = 0). + mut2 = ps_text.replace('lerp_u8(v0, v4, v8)', 'lerp_u8(v0, v4, 0u)').replace( + 'lerp_u8(v1, v5, v9)', 'lerp_u8(v1, v5, 0u)') + assert mut2 != ps_text + mut2_bin = compile_hlsl(compiler, tag, mut2, f'{tag}_ps_mut_round', ps_profile, directory) + run_m2 = draw(renderer, adapter, vs_bin, mut2_bin, want) + assert run_m2.returncode != 0, f'{tag} drop-rounding mutation escaped' + print(f'{tag} v_lerp_u8 round mutation: fails as expected (rc={run_m2.returncode})') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + controls() + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + check_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + else: + raise SystemExit(__doc__) diff --git a/tests/startup_gfx2hlsl_mad64_check.py b/tests/startup_gfx2hlsl_mad64_check.py index f19d832197..475ba6bc93 100644 --- a/tests/startup_gfx2hlsl_mad64_check.py +++ b/tests/startup_gfx2hlsl_mad64_check.py @@ -189,6 +189,25 @@ def controls(): 'v_mad_u64_u32 v[12:13], vcc_lo, v18, v19, v20'): check('refused: %s' % asm, refused(asm)) + # Discarded carry destinations have no VCC effect, even on forms the translator refuses. + for name, asm, may in ( + ('v_mad_u64_u32', 'v_mad_u64_u32 v[12:13], vcc_lo, v18, v19, v[20:21]', {'vcc', 'vcc_hi'}), + ('v_mad_u64_u32', 'v_mad_u64_u32 v[12:13], null, v18, v19, v[20:21]', set()), + ('v_mad_i64_i32', 'v_mad_i64_i32 v[12:13], null, v18, v19, v[20:21]', set()), + ('v_add_co_u32', 'v_add_co_u32 v4, vcc_lo, v5, v6', {'vcc', 'vcc_hi'}), + ('v_cmp_gt_u32_e64', 'v_cmp_gt_u32_e64 vcc_lo, v1, v2', {'vcc', 'vcc_hi'})): + _, writes, may_write = G.scalar_effects(name, asm) + check('%s may-writes %s' % (asm, ' and '.join(sorted(may)) or 'no VCC half'), + (writes | may_write) & G.VCC_KEYS == may and 'vcc_hi' not in writes) + # A skipped-block join must not retain a stale high-half clear fact. + start = {('exec', 0), ('exec_hi', 1), ('vcc_hi', 0)} + mad = 'v_mad_u64_u32 v[12:13], vcc_lo, v18, v19, v[20:21]' + after = G.clear_after('v_mad_u64_u32', mad, G.scalar_effects('v_mad_u64_u32', mad)[2], start) + check('a clear vcc_hi fact does not survive the unsigned mad', after == start - {('vcc_hi', 0)}) + null_mad = 'v_mad_u64_u32 v[12:13], null, v18, v19, v[20:21]' + after_null = G.clear_after('v_mad_u64_u32', null_mad, G.scalar_effects('v_mad_u64_u32', null_mad)[2], start) + check('a discarded null carry keeps the vcc_hi fact', after_null == start) + def pack_draw(a, b, c): return [(a, 0, 0), (b, 0, 0), (c & MASK, 0, 0), (c >> 32, 0, 0)] diff --git a/tests/startup_gfx2hlsl_perm_b32_check.py b/tests/startup_gfx2hlsl_perm_b32_check.py new file mode 100644 index 0000000000..3192aa3a8a --- /dev/null +++ b/tests/startup_gfx2hlsl_perm_b32_check.py @@ -0,0 +1,211 @@ +"""Byte permutation (v_perm_b32) in tools/startup/gfx2hlsl.py. + + (no arguments) translation, on-demand helper, exhaustive selector 0..255 evaluation, + refusal and mutation controls, pure Python + draw [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input triples and compare the four result words + +AMD RDNA 2 ISA V_PERM_B32 (VOP3A opcode 0x344): + Input bytes in[0..3] = S1 bytes 0..3, in[4..7] = S0 bytes 0..3. + For each output byte i in 0..3, sel = (S2 >> (8*i)) & 0xff: + 0..7 -> in[sel] + 8 -> in[1][7] ? 0xff : 0x00 + 9 -> in[3][7] ? 0xff : 0x00 + 10 -> in[5][7] ? 0xff : 0x00 + 11 -> in[7][7] ? 0xff : 0x00 + 12 -> 0x00 + >= 13 -> 0xff +""" +import re +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + vs_words, + words_text, +) +from startup_gfx2hlsl_sad_check import HlslExpr, vop3a # noqa: E402 + +OPCODE = 0x344 +BODY_WORDS = b''.join(vop3a(OPCODE, 12 + lane, 256 + lane, 256 + 4 + lane, 256 + 8 + lane) for lane in range(4)) +PS_WORDS = PRE_WORDS + BODY_WORDS + POST_WORDS + + +def ref_perm_byte(hi, lo, sel): + sel &= 0xff + if sel >= 13: + return 0xff + if sel == 12: + return 0x00 + if sel >= 8: + word = hi if sel >= 10 else lo + bit = 31 if (sel & 1) else 15 + return 0xff if ((word >> bit) & 1) else 0x00 + word = hi if sel >= 4 else lo + return (word >> ((sel & 3) * 8)) & 0xff + + +def ref_perm_b32(hi, lo, sel): + hi, lo, sel = hi & MASK, lo & MASK, sel & MASK + out = 0 + for shift in (0, 8, 16, 24): + out |= ref_perm_byte(hi, lo, (sel >> shift) & 0xff) << shift + return out + + +# Pairs that distinguish odd-byte sign bits (bytes 1, 3, 5, 7) from even-byte sign bits (bytes 0, 2, 4, 6). +WORD_PAIRS = ( + (0x81020384, 0x05868708), + (0x01828304, 0x85060788), + (0x00800080, 0x80008000), + (0x80008000, 0x00800080), + (0x7f7f7f7f, 0x80808080), + (0x11223344, 0x55667788), +) + +DRAW_SETS = ( + ( + (0x11223344, 0x55667788, 0x07040300), # bytes from S0 and S1 + (0x81020384, 0x05868708, 0x0b0a0908), # sign-ext selectors 8,9,10,11 (even vs odd sign bits differ) + (0x01828304, 0x85060788, 0x0b0a0908), # sign-ext selectors 8,9,10,11 (flipped signs) + (0x11223344, 0x55667788, 0xfe0d0c05), # 0xfe (>=13 -> 0xff), 13 (-> 0xff), 12 (-> 0x00), 5 (S0 byte 1) + ), + ( + (0xdeadbeef, 0xcafebabe, 0x00010203), # reverse bytes of S1 + (0xdeadbeef, 0xcafebabe, 0x04050607), # reverse bytes of S0 + (0x00800080, 0x80008000, 0x08090a0b), # reverse sign-ext selectors + (0x01234567, 0x89abcdef, 0x0c0c0d0f), # constant 0x00 and 0xff selectors + ), +) + + +def extract_helper(hlsl, name): + m = re.search(rf'uint {name}\(uint hi, uint lo, uint sel\)\s*\{{\s*return\s+(.+?);\s*\}}', hlsl) + assert m, f'{name} helper missing from HLSL' + return m.group(1) + + +def controls(): + pipe = G.Pipeline(vs_words(DRAW_SETS[0]), PS_WORDS, root_blob()) + ps = pipe.hlsl_ps() + check('perm_byte helper emitted on demand', 'uint perm_byte(uint hi, uint lo, uint sel)' in ps) + check('perm_b32 helper emitted on demand', 'uint perm_b32(uint hi, uint lo, uint sel)' in ps) + for lane in range(4): + expected_line = f'v{12 + lane} = perm_b32(v{lane}, v{4 + lane}, v{8 + lane});' + check(f'lane {lane} assignment emitted', expected_line in ps) + + plain_ps = G.Pipeline(vs_words(DRAW_SETS[0]), PRE_WORDS + POST_WORDS, root_blob()).hlsl_ps() + check('perm_b32 omitted when unused', 'perm_b32(' not in plain_ps and 'perm_byte(' not in plain_ps) + + # Exhaustively evaluate the emitted perm_byte helper over all 256 selectors x 6 word pairs, plus perm_b32. + byte_eval = HlslExpr(extract_helper(ps, 'perm_byte')) + b32_eval = HlslExpr(extract_helper(ps, 'perm_b32'), + helpers={'perm_byte': lambda hi, lo, s: byte_eval.run({'hi': hi, 'lo': lo, 'sel': s})[0]}) + for hi, lo in WORD_PAIRS: + for sel in range(256): + got = byte_eval.run({'hi': hi, 'lo': lo, 'sel': sel})[0] + want = ref_perm_byte(hi, lo, sel) + assert got == want, (hex(hi), hex(lo), sel, hex(got), hex(want)) + for triples in DRAW_SETS: + for hi, lo, sel in triples: + got = b32_eval.run({'hi': hi, 'lo': lo, 'sel': sel})[0] + want = ref_perm_b32(hi, lo, sel) + assert got == want, (hex(hi), hex(lo), hex(sel), hex(got), hex(want)) + print(f'v_perm_b32: emitted helpers match reference on {len(WORD_PAIRS) * 256} selector cases + draw sets: ok') + + # Accepted operand forms and exec-masked emission. + for asm in ( + 'v_perm_b32 v12, v0, v4, v8', + 'v_perm_b32 v12, s4, v4, v8', + 'v_perm_b32 v12, 1, v4, 0', + 'v_perm_b32 v12, 0x11223344, v4, v8', + ): + probe = Probe() + probe.lower('v_perm_b32', asm, [o.strip() for o in asm.split(None, 1)[1].split(',')], []) + assert probe.lines and 'perm_b32(' in probe.lines[0], (asm, probe.lines) + probe_masked = Probe() + probe_masked.exec_known = False + probe_masked.lower('v_perm_b32', 'v_perm_b32 v12, v0, v4, v8', ['v12', 'v0', 'v4', 'v8'], []) + check('exec-masked v_perm_b32 guards assignment', + probe_masked.lines == ['if (exec & 1) v12 = perm_b32(v0, v4, v8);']) + print('accepted operand forms translate: ok') + + # Refusals: VOP3A neg/abs on VGPR and inline constants, clamp, omod, op_sel, wrong operand counts. + def must_refuse(fn, label, needle=''): + try: + fn() + except G.Unsupported as error: + check(f'{label} refused', needle in str(error) if needle else bool(str(error))) + else: + raise AssertionError(f'{label} was accepted') + + for label, bad, needle in ( + ('abs0', vop3a(OPCODE, 12, 256, 260, 264, abs_bits=1), 'with neg/abs'), + ('neg2', vop3a(OPCODE, 12, 256, 260, 264, neg=4), 'with neg/abs'), + ('neg_inline0', vop3a(OPCODE, 12, 129, 260, 264, neg=1), 'with neg/abs'), + ('abs_inline0', vop3a(OPCODE, 12, 129, 260, 264, abs_bits=1), 'with neg/abs'), + ('clamp', vop3a(OPCODE, 12, 256, 260, 264, clamp=1), ''), + ('omod', vop3a(OPCODE, 12, 256, 260, 264, omod=1), ''), + ('op_sel', vop3a(OPCODE, 12, 256, 260, 264, op_sel=1), ''), + ): + must_refuse(lambda b=bad: G.Pipeline(vs_words(DRAW_SETS[0]), PRE_WORDS + b + POST_WORDS, root_blob()), label, needle) + for bad_ops in (['v12', 'v0', 'v4'], ['v12', 'v0', 'v4', 'v8', 'v9']): + must_refuse(lambda ops=bad_ops: Probe().lower('v_perm_b32', 'v_perm_b32', ops, []), f'arity {len(bad_ops)}') + print('modifiers and wrong operand counts refused: ok') + + +def check_draw(dxc, renderer, adapter, fxc=None): + controls() + compilers = [('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else [] + compilers.append(('dxc', dxc, 'vs_6_0', 'ps_6_0')) + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for tag, compiler, vs_profile, ps_profile in compilers: + for idx, triples in enumerate(DRAW_SETS): + pipe = G.Pipeline(vs_words(triples), PS_WORDS, root_blob()) + vs_bin = compile_hlsl(compiler, tag, pipe.hlsl_vs(), f'{tag}_vs_{idx}', vs_profile, directory) + ps_text = pipe.hlsl_ps() + ps_bin = compile_hlsl(compiler, tag, ps_text, f'{tag}_ps_{idx}', ps_profile, directory) + want = words_text(ref_perm_b32(*t) for t in triples) + run = draw(renderer, adapter, vs_bin, ps_bin, want) + sys.stdout.write(run.stdout) + if run.returncode == 77: + sys.exit(77) + assert run.returncode == 0, f'{tag} set {idx} failed:\n{run.stdout}\n{run.stderr}' + print(f'{tag} v_perm_b32 draw {idx}: {want}') + if idx == 0: + # Mutation 1: swap S0 and S1. + mut1 = ps_text.replace('perm_b32(v0, v4, v8)', 'perm_b32(v4, v0, v8)') + assert mut1 != ps_text + mut1_bin = compile_hlsl(compiler, tag, mut1, f'{tag}_ps_mut_swap', ps_profile, directory) + run_m1 = draw(renderer, adapter, vs_bin, mut1_bin, want) + assert run_m1.returncode != 0, f'{tag} S0/S1 swap mutation escaped' + print(f'{tag} v_perm_b32 swap mutation: fails as expected (rc={run_m1.returncode})') + # Mutation 2: use byte 0/4 sign bit (bit 7) instead of byte 1/5 sign bit (bit 15). + mut2 = ps_text.replace('31u : 15u', '31u : 7u') + assert mut2 != ps_text + mut2_bin = compile_hlsl(compiler, tag, mut2, f'{tag}_ps_mut_sign', ps_profile, directory) + run_m2 = draw(renderer, adapter, vs_bin, mut2_bin, want) + assert run_m2.returncode != 0, f'{tag} sign-bit mutation escaped' + print(f'{tag} v_perm_b32 sign-bit mutation: fails as expected (rc={run_m2.returncode})') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + controls() + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + check_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + else: + raise SystemExit(__doc__) diff --git a/tests/startup_gfx2hlsl_pk_minmax_check.py b/tests/startup_gfx2hlsl_pk_minmax_check.py new file mode 100644 index 0000000000..c9a12ef49c --- /dev/null +++ b/tests/startup_gfx2hlsl_pk_minmax_check.py @@ -0,0 +1,168 @@ +"""Packed binary16 min/max translation and D3D12 readback (#2022). + +Run without arguments for translation controls, or use +draw to compare both halves with the CPU reference. +""" +import math +import re +import struct +import sys +import tempfile +from pathlib import Path + +from startup_gfx2hlsl_bit_alu_check import G, POST_WORDS, PRE_WORDS, vs_words, words_text +from startup_flat_param_check import compile_hlsl, draw, root_blob + + +OPS = {'min': 'false', 'max': 'true'} +DEFAULT_LO, DEFAULT_HI = (0, 0), (1, 1) +LITERAL = 0x4400c000 # high +4, low -2 +TAG = 0x40000000 + + +def lower(asm, sym=None, masks=()): + stage = G.Stage.__new__(G.Stage) + stage.lines, stage.sym, stage.masks = [], sym or {}, set(masks) + stage.used_s, stage.used_v, stage.exec_known = set(), set(), True + stage.one(asm.split()[0], asm) + return stage.lines + + +def controls(): + for op, flag in OPS.items(): + mnemonic = f'v_pk_{op}_f16' + for operands, words in ( + ('v0, v1', ('v0', 'v1')), + ('v0, 0', ('v0', '0x00000000u')), + ('0x4400c000, v1', ('0x4400c000u', 'v1')), + ('v0, s20', ('v0', 's20')), + ): + for low, high, modifiers in ( + (DEFAULT_LO, DEFAULT_HI, ''), + ((1, 1), (0, 0), ' op_sel:[1,1] op_sel_hi:[0,0]'), + ((1, 0), (0, 1), ' op_sel:[1,0] op_sel_hi:[0,1]'), + ): + expected = [] + for picks in (low, high): + args = [f'({w} >> 16) & 0xffffu' if h else f'{w} & 0xffffu' for w, h in zip(words, picks)] + expected.append(f'minmax16_bits({", ".join(args)}, {flag})') + asm = f'{mnemonic} v3, {operands}{modifiers}' + got = lower(asm) + assert got == [f'v3 = {expected[0]} | ({expected[1]} << 16);'], (asm, got) + print(f'{asm}: packed HLSL matches') + + for tail in ('v0, v1 neg_lo:[1,0]', 'v0, v1 neg_hi:[0,1]', 'v0, v1 clamp', 'v0, v1 mul:2', + 'v0, v1 op_sel:[1]', 'v0, v1 op_sel_hi:[0,2]'): + refuses(f'{mnemonic} v3, {tail}', tail.split()[-1]) + for source in ('1', '-1', '0.0', '1.0', 'vcc', 'exec', 'm0', 'null', 'src_scc', 'v[0:1]', + 's[20:20]', 'v256', 's106', '-v0', '0x100000000'): + refuses(f'{mnemonic} v3, {source}, v1', f'source {source} requires') + refuses(f'{mnemonic} v256, v0, v1', 'destination v256 is out of range') + refuses(f'{mnemonic} v3, v0, s20', 'numeric use of s20 holding root', sym={20: ('root',)}) + refuses(f'{mnemonic} v3, v0, s20', 'is a lane mask', masks=(20,)) + + for op, tail in (('add', ''), ('mul', ''), ('fma', ', v2')): + refuses(f'v_pk_{op}_f16 v3, v0, 0x4000{tail}', 'is not a single VGPR') + + +def refuses(asm, reason, **kwargs): + try: + lower(asm, **kwargs) + except G.Unsupported as error: + assert reason in str(error), (asm, error) + else: + raise AssertionError(f'accepted {asm}') + print(f'{asm}: refused') + + +def half_reference(op, a, b): + x, y = (struct.unpack('= y) else b + + +def reference(op, a, b, low, high): + lo, hi = (half_reference(op, (a >> (16 * i)) & 0xffff, (b >> (16 * j)) & 0xffff) + for i, j in (low, high)) + return lo | (hi << 16) + + +# Four output channels per group. Each row holds two source words, optional special source, and low/high picks. +# Manual mutants that must fail the draws: swap op_sel/op_sel_hi, use max for min, and replace the NaN tests +# with float isnan() folded to false (model that fold by replacing both tests with false). +GROUPS = { + 'zeros': ( + (0x80000000, 0x00008000, '', DEFAULT_LO, DEFAULT_HI), + (0x00008000, 0x80000000, '', DEFAULT_LO, DEFAULT_HI), + (0x80000000, 0x80000000, '', DEFAULT_LO, DEFAULT_HI), + (0x00008000, 0x00008000, '', DEFAULT_LO, DEFAULT_HI), + ), + 'nan_and_range': ( + (0xfe017d01, 0x40003c00, '', DEFAULT_LO, DEFAULT_HI), + (0x40003c00, 0x7e02fd02, '', DEFAULT_LO, DEFAULT_HI), + (0xfe017d01, 0x7e02fd02, '', DEFAULT_LO, DEFAULT_HI), + (0x7c008001, 0xfc000001, '', DEFAULT_LO, DEFAULT_HI), + ), + 'selectors': ( + (LITERAL, 0x42003c00, 'literal', (1, 0), (0, 1)), + (0x42003c00, LITERAL, 'sgpr', (0, 1), (1, 0)), + (0x4200bc00, 0, 'zero', DEFAULT_LO, (1, 0)), + (0x42003c00, 0x4400c000, '', DEFAULT_LO, DEFAULT_HI), + ), +} + + +def pixel_words(op, cases): + """Encode the source-built fixture using the two-source gfx1013 VOP3P fields.""" + body = bytearray() + if any(kind == 'sgpr' for _, _, kind, _, _ in cases): + body += struct.pack('<2I', 0xbe9403ff, LITERAL) # s_mov_b32 s20, literal + opcode = 0x11 if op == 'min' else 0x12 + for channel, (_, _, kind, low, high) in enumerate(cases): + src0 = 256 + channel if kind != 'literal' else 255 + src1 = {'sgpr': 20, 'zero': 128}.get(kind, 260 + channel) + w0 = 0xcc004000 | (opcode << 16) | (12 + channel) | (low[0] << 11) | (low[1] << 12) + w1 = src0 | (src1 << 9) | (high[0] << 27) | (high[1] << 28) + body += struct.pack('<2I', w0, w1) + if kind == 'literal': + body += struct.pack('> {shift}) & 0xffffu) | 0x{TAG:x}u)', packed_ps) + assert count == 4, packed_ps + ps = compile_hlsl(dxc, 'dxc', ps_text, f'ps_{name}_{shift}', 'ps_6_0', directory) + expected = words_text(TAG | ((reference(op, a, b, low, high) >> shift) & 0xffff) + for a, b, _, low, high in cases) + result = draw(renderer, adapter, vs, ps, expected) + assert result.returncode == 0, (name, shift, expected, result.stderr) + print(f'{name}, shift {shift}: {expected}') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + controls() + elif len(sys.argv) == 5 and sys.argv[1] == 'draw' and sys.argv[4] in ('warp', 'hardware'): + check_draw(*sys.argv[2:]) + else: + sys.exit(__doc__) diff --git a/tests/startup_gfx2hlsl_s_bitcmp64_check.py b/tests/startup_gfx2hlsl_s_bitcmp64_check.py new file mode 100644 index 0000000000..f311b995be --- /dev/null +++ b/tests/startup_gfx2hlsl_s_bitcmp64_check.py @@ -0,0 +1,403 @@ +"""64-bit scalar bit-compare (s_bitcmp0_b64, s_bitcmp1_b64) in tools/startup/gfx2hlsl.py. + + (no arguments) SOPC decode, value evaluation, uniformity, refusal and mutation + controls, pure Python + draw [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per (lo, hi, index) triple and compare the four result words + +RDNA 2 ISA, SOPC: + S_BITCMP0_B64 S0, S1: SCC = (S0.u64[S1.u[5:0]] == 0) + S_BITCMP1_B64 S0, S1: SCC = (S0.u64[S1.u[5:0]] == 1) + +The pixel fixture decodes synthetic gfx1013 bytes via G.decode() ONLY (no game data). It loads (lo, hi, index) +into s4..s6 with SOP1 literal moves, executes s_bitcmp0_b64 / s_bitcmp1_b64 (register index, immediate index 37, +and sign-extended inline -1 source), materializes each SCC via s_cselect_b32, XORs with 0x3f800000 for normal +IEEE-754 transport into v12..v15, and exports mrt0. +""" +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + vs_words, + words_text, +) + +SOPC_OPCODES = { + 's_bitcmp0_b64': 0x0e, + 's_bitcmp1_b64': 0x0f, +} + + +def sopc(op, ssrc0, ssrc1, lit=None): + """Encode one synthetic gfx1013 SOPC 32-bit (or 64-bit with literal) instruction.""" + w0 = 0xbf000000 | (op << 16) | (ssrc1 << 8) | ssrc0 + out = struct.pack(', <32-bit literal> (op 0x03, ssrc0=255).""" + return struct.pack('<2I', (0b101111101 << 23) | (sdst << 16) | (0x03 << 8) | 255, val & MASK) + + +def s_cselect_b32(sdst, ssrc0, ssrc1): + """Encode SOP2 s_cselect_b32 s, ssrc0, ssrc1 (op 0x0a).""" + return struct.pack(', s, <32-bit literal> (op 0x12, ssrc1=255).""" + return struct.pack('<2I', 0x80000000 | (0x12 << 23) | (sdst << 16) | (255 << 8) | ssrc0, lit & MASK) + + +def v_mov_b32_from_sgpr(vdst, ssrc): + """Encode VOP1 v_mov_b32_e32 v, s (op 0x01).""" + return struct.pack(' 128, 1 -> 129, 37 -> 128+37=165, -1 -> 193. + body = b''.join([ + sop1_mov_lit(4, lo), # s4 = lo + sop1_mov_lit(5, hi), # s5 = hi + sop1_mov_lit(6, idx), # s6 = bit index + sopc(0x0e, 4, 6), # s_bitcmp0_b64 s[4:5], s6 + s_cselect_b32(8, 129, 128), # s8 = scc ? 1 : 0 + s_xor_lit(8, 8, DRAW_TRANSPORT_XOR), + v_mov_b32_from_sgpr(12, 8), # v12 = s8 ^ 0x3f800000 + sopc(0x0f, 4, 6), # s_bitcmp1_b64 s[4:5], s6 + s_cselect_b32(9, 129, 128), # s9 = scc ? 1 : 0 + s_xor_lit(9, 9, DRAW_TRANSPORT_XOR), + v_mov_b32_from_sgpr(13, 9), # v13 = s9 ^ 0x3f800000 + sopc(0x0f, 4, 128 + 37), # s_bitcmp1_b64 s[4:5], 37 + s_cselect_b32(10, 129, 128), # s10 = scc ? 1 : 0 + s_xor_lit(10, 10, DRAW_TRANSPORT_XOR), + v_mov_b32_from_sgpr(14, 10), # v14 = s10 ^ 0x3f800000 + sopc(0x0f, 193, 6), # s_bitcmp1_b64 -1, s6 + s_cselect_b32(11, 129, 128), # s11 = scc ? 1 : 0 + s_xor_lit(11, 11, DRAW_TRANSPORT_XOR), + v_mov_b32_from_sgpr(15, 11), # v15 = s11 ^ 0x3f800000 + ]) + return PRE_WORDS + body + POST_WORDS + + +def translate_ps(lo=0x00000001, hi=0x00000020, idx=37): + zero = [(0, 0, 0)] * 4 + pipe = G.Pipeline(vs_words(zero), ps_words(lo, hi, idx), root_blob()) + return pipe.hlsl_vs(), pipe.hlsl_ps() + + +def ref_bitcmp64(want, lo, hi, idx): + """Independent bit-string reference for S_BITCMP{0,1}_B64.""" + bits = format((hi & MASK) << 32 | (lo & MASK), '064b')[::-1] + return int(bits[idx & 63]) == want + + +def eval_scc_expr(expr, env): + """Evaluate a translated HLSL boolean SCC expression in Python.""" + text = re.sub(r'\b(0x[0-9a-fA-F]+|\d+)u\b', r'\1', expr) + # Convert C ternary (cond ? a : b) handling arbitrary balanced parens inside cond/a/b. + while '?' in text: + q = text.index('?') + depth = 0 + start = q - 1 + while start >= 0: + if text[start] == ')': + depth += 1 + elif text[start] == '(': + if depth == 0: + break + depth -= 1 + start -= 1 + depth = 0 + colon = -1 + end = q + 1 + while end < len(text): + if text[end] == '(': + depth += 1 + elif text[end] == ')': + if depth == 0: + break + depth -= 1 + elif text[end] == ':' and depth == 0 and colon == -1: + colon = end + end += 1 + cond = text[start + 1:q].strip() + yes = text[q + 1:colon].strip() + no = text[colon + 1:end].strip() + text = text[:start] + ('((%s) if (%s) else (%s))' % (yes, cond, no)) + text[end + 1:] + return bool(eval(text, {'__builtins__': {}}, env)) + + +def run_one(line, env, *, sym=None, scc_verified=False): + stage = Probe() + if sym: + stage.sym.update(sym) + stage.scc_verified = scc_verified + stage.one(line.split(' ', 1)[0], line) + assert len(stage.lines) == 1, stage.lines + target, _, expr = stage.lines[0].rstrip(';').partition(' = ') + assert target == 'scc', stage.lines + return eval_scc_expr(expr, env), stage + + +def stage_refused(stage, mnemonic, line, needle=''): + try: + stage.one(mnemonic, line) + except G.Unsupported as exc: + return (not needle or needle in str(exc)) and not stage.lines + return False + + +PAIRS = ( + (0x00000000, 0x00000000), + (0xffffffff, 0xffffffff), + (0x00000001, 0x80000000), + (0x80000000, 0x00000001), + (0xffffffff, 0x00000000), + (0x00000000, 0xffffffff), + (0x55555555, 0xaaaaaaaa), + (0xaaaaaaaa, 0x55555555), + (0x00010020, 0x00000020), +) +INDEXES = (0, 1, 5, 31, 32, 33, 37, 63, 64, 65, 96, 127, 0xffffffe5) + + +def run_controls(): + # 1. Decode verification from synthetic gfx1013 SOPC bytes via G.decode(). + decoded = [ + G.decode(sopc(0x0e, 4, 6))[0][3], + G.decode(sopc(0x0f, 4, 128 + 37))[0][3], + G.decode(sopc(0x0f, 193, 6))[0][3], + G.decode(sopc(0x0e, 255, 6, lit=0x80000001))[0][3], + G.decode(sopc(0x0f, 125, 128))[0][3], + ] + check('decode s_bitcmp0_b64 reg/reg', decoded[0] == 's_bitcmp0_b64 s[4:5], s6') + check('decode s_bitcmp1_b64 reg/imm37', decoded[1] == 's_bitcmp1_b64 s[4:5], 37') + check('decode s_bitcmp1_b64 inline -1', decoded[2] == 's_bitcmp1_b64 -1, s6') + check('decode s_bitcmp0_b64 literal', decoded[3] == 's_bitcmp0_b64 0x80000001, s6') + check('decode s_bitcmp1_b64 null', decoded[4] == 's_bitcmp1_b64 null, 0') + + # 2. Exhaustive SGPR pair + register/immediate index grid. + grid_ok = True + for mnemonic, want in (('s_bitcmp0_b64', 0), ('s_bitcmp1_b64', 1)): + for lo, hi in PAIRS: + for idx in INDEXES: + expected = ref_bitcmp64(want, lo, hi, idx) + for line, env in ( + ('%s s[4:5], s6' % mnemonic, {'s4': lo, 's5': hi, 's6': idx}), + ('%s s[4:5], %d' % (mnemonic, idx), {'s4': lo, 's5': hi}), + ): + got, _ = run_one(line, env) + if got != expected: + grid_ok = False + print('MISMATCH %s lo=%#x hi=%#x idx=%#x got=%s want=%s' % ( + line, lo, hi, idx, got, expected)) + check('SGPR pair grid (%d cases)' % (2 * len(PAIRS) * len(INDEXES) * 2), grid_ok) + + # 3. Inline integer 64-bit S0 (including negative sign-extension to 64 bits). + inline_ok = True + for mnemonic, want in (('s_bitcmp0_b64', 0), ('s_bitcmp1_b64', 1)): + for val in (0, 1, 64, -1, -16): + lo, hi = val & MASK, (val >> 32) & MASK + for idx in (0, 3, 4, 6, 31, 32, 37, 63, 64): + got, _ = run_one('%s %d, s6' % (mnemonic, val), {'s6': idx}) + if got != ref_bitcmp64(want, lo, hi, idx): + inline_ok = False + check('inline integer S0 sign-extends negative values to 64 bits', inline_ok) + + # 4. 32-bit hex literal S0 zero-extends to 64 bits (hi == 0 even when bit 31 is set). + lit_ok = True + for mnemonic, want in (('s_bitcmp0_b64', 0), ('s_bitcmp1_b64', 1)): + for idx in (0, 1, 31, 32, 33, 63): + got, _ = run_one('%s 0x80000001, s6' % mnemonic, {'s6': idx}) + if got != ref_bitcmp64(want, 0x80000001, 0, idx): + lit_ok = False + check('32-bit hex literal S0 zero-extends to 64 bits', lit_ok) + + # 5. null as S0 and S1, src_scc as S1, and const-tracked SGPR pair. + for mnemonic, want in (('s_bitcmp0_b64', 0), ('s_bitcmp1_b64', 1)): + for idx in (0, 31, 32, 63): + got, _ = run_one('%s null, s6' % mnemonic, {'s6': idx}) + check('%s null, s6 (idx=%d)' % (mnemonic, idx), got == (want == 0)) + got_null_idx, _ = run_one('%s s[4:5], null' % mnemonic, {'s4': 1, 's5': 0}) + check('%s s[4:5], null reads bit 0' % mnemonic, got_null_idx == (want == 1)) + for scc_val in (False, True): + got_scc, _ = run_one('%s s[4:5], src_scc' % mnemonic, + {'s4': 0x2, 's5': 0x0, 'scc': scc_val}, scc_verified=True) + check('%s src_scc=%s' % (mnemonic, scc_val), + got_scc == ref_bitcmp64(want, 0x2, 0x0, 1 if scc_val else 0)) + got_const, _ = run_one('%s s[4:5], s6' % mnemonic, {'s5': 0x20, 's6': 37}, + sym={4: ('const', 0)}) + check('%s const-tracked lo + runtime hi' % mnemonic, got_const == (want == 1)) + + # 6. Uniformity tracking on lo, hi, and bit index. + for mnemonic in ('s_bitcmp0_b64', 's_bitcmp1_b64'): + s = Probe() + s.varying_s = set() + s.scc_uniform = False + s.one(mnemonic, '%s s[4:5], s6' % mnemonic) + check('%s uniform inputs -> scc_uniform=True' % mnemonic, s.scc_uniform is True) + for bad_reg in (4, 5, 6): + s = Probe() + s.varying_s = {bad_reg} + s.scc_uniform = True + s.one(mnemonic, '%s s[4:5], s6' % mnemonic) + check('%s varying s%d -> scc_uniform=False' % (mnemonic, bad_reg), s.scc_uniform is False) + + # 7. Refusals (arity, modifiers, lane masks, mask_high, invalid register classes/alignment). + for mnemonic in ('s_bitcmp0_b64', 's_bitcmp1_b64'): + check('%s 1 operand refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5]' % mnemonic, 'two unmodified operands')) + check('%s 3 operands refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5], s6, s7' % mnemonic, 'two unmodified operands')) + check('%s modifier refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5], s6 clamp' % mnemonic, 'two unmodified operands')) + for operands in ( + 'exec, 1', 'exec_lo, 1', 'vcc, 1', 'vcc_lo, 1', + 's[4:5], exec_lo', 's[4:5], vcc_lo', 's[4:5], exec', 's[4:5], vcc', + ): + check('%s %s lane mask refused' % (mnemonic, operands), + stage_refused(Probe(), mnemonic, '%s %s' % (mnemonic, operands), 'lane mask')) + for mask_reg, high_reg, operands in ( + (12, None, 's[12:13], 1'), + (13, None, 's[12:13], 1'), + (None, 13, 's[12:13], 1'), + (12, None, 's[4:5], s12'), + (None, 13, 's[4:5], s13'), + ): + p = Probe() + if mask_reg is not None: + p.masks = {mask_reg} + if high_reg is not None: + p.mask_high = {high_reg} + check('%s %s tracked mask refused' % (mnemonic, operands), + stage_refused(p, mnemonic, '%s %s' % (mnemonic, operands), 'lane mask')) + for bad_s0 in ('v[0:1]', 's4', 's[5:6]', 's[106:107]', '1.0', 'm0', 'src_scc'): + check('%s bad S0 %s refused' % (mnemonic, bad_s0), + stage_refused(Probe(), mnemonic, '%s %s, s6' % (mnemonic, bad_s0))) + for bad_s1 in ('v0', 's[6:7]', 's106', '1.0'): + check('%s bad S1 %s refused' % (mnemonic, bad_s1), + stage_refused(Probe(), mnemonic, '%s s[4:5], %s' % (mnemonic, bad_s1), 'bit index')) + p_unv = Probe() + p_unv.scc_verified = False + check('%s unverified src_scc refused' % mnemonic, + stage_refused(p_unv, mnemonic, '%s s[4:5], src_scc' % mnemonic, 'unverified SCC')) + + # 8. Full synthetic pixel pipeline translates cleanly through G.Pipeline(). + _, ps_hlsl = translate_ps() + check('synthetic pixel pipeline translates', '& 32u' in ps_hlsl and '& 31u' in ps_hlsl) + + # 9. Unlowered control: removing handlers from Stage restores refusals. + saved = {name: getattr(G.Stage, name) for name in ('op_s_bitcmp0_b64', 'op_s_bitcmp1_b64')} + try: + for name in saved: + delattr(G.Stage, name) + for mnemonic in ('s_bitcmp0_b64', 's_bitcmp1_b64'): + check('unlowered %s refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5], s6' % mnemonic)) + try: + translate_ps() + except G.Unsupported: + check('unlowered synthetic pipeline refused', True) + else: + check('unlowered synthetic pipeline refused', False) + finally: + for name, fn in saved.items(): + setattr(G.Stage, name, fn) + + # 10. Mutation / negative controls: prove our test inputs distinguish common bugs. + check('mutation: dropping bit 5 diverges on bit 37', + ref_bitcmp64(1, 0x0, 0x20, 37) != ref_bitcmp64(1, 0x0, 0x20, 37 & 31)) + check('mutation: swapping lo/hi diverges on bit 0', + ref_bitcmp64(1, 0x1, 0x0, 0) != ref_bitcmp64(1, 0x0, 0x1, 0)) + check('mutation: inverting bit0/bit1 diverges', + ref_bitcmp64(0, 0x0, 0x20, 37) != ref_bitcmp64(1, 0x0, 0x20, 37)) + check('mutation: zero-extending -1 diverges on bit 37', + ref_bitcmp64(1, 0xffffffff, 0xffffffff, 37) != ref_bitcmp64(1, 0xffffffff, 0x0, 37)) + check('mutation: sign-extending 0x80000001 diverges on bit 63', + ref_bitcmp64(1, 0x80000001, 0x0, 63) != ref_bitcmp64(1, 0x80000001, 0xffffffff, 63)) + + +GPU_VECTORS = ( + # (label, lo, hi, idx) + ('lo_bit0_set', 0x00000001, 0x00000000, 0), + ('lo_bit31_clear', 0x7fffffff, 0xffffffff, 31), + ('hi_bit32_set', 0x00000000, 0x00000001, 32), + ('hi_bit37_set', 0x00000000, 0x00000020, 37), + ('hi_bit63_set', 0x00000000, 0x80000000, 63), + ('wrapped_101', 0x00000000, 0x00000020, 101), # 101 & 63 == 37 + ('wrapped_64', 0x00000001, 0x00000000, 64), # 64 & 63 == 0 +) + + +def run_draw(dxc, renderer, adapter, fxc=None): + run_controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory(prefix='x2w_s_bitcmp64_') as tmp: + td = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + first_vs = None + first_ps = None + first_exp = None + for label, lo, hi, idx in GPU_VECTORS: + vs_hlsl, ps_hlsl = translate_ps(lo, hi, idx) + vs_bin = compile_hlsl(compiler, kind, vs_hlsl, 'vs_%s_%s' % (label, kind), vs_profile, td) + ps_bin = compile_hlsl(compiler, kind, ps_hlsl, 'ps_%s_%s' % (label, kind), ps_profile, td) + raw_exp = ( + (1 if ref_bitcmp64(0, lo, hi, idx) else 0) ^ DRAW_TRANSPORT_XOR, + (1 if ref_bitcmp64(1, lo, hi, idx) else 0) ^ DRAW_TRANSPORT_XOR, + (1 if ref_bitcmp64(1, lo, hi, 37) else 0) ^ DRAW_TRANSPORT_XOR, + (1 if ref_bitcmp64(1, 0xffffffff, 0xffffffff, idx) else 0) ^ DRAW_TRANSPORT_XOR, + ) + expected = words_text(raw_exp) + res = draw(renderer, adapter, vs_bin, ps_bin, expected) + if res.returncode == 77: + print('SKIP (%s): %s' % (adapter, res.stdout.strip() or res.stderr.strip())) + sys.exit(77) + if res.returncode != 0: + raise AssertionError('%s %s %s expected=%s\n%s\n%s' % ( + kind, adapter, label, expected, res.stdout, res.stderr)) + print('%s %s %s: %s' % (kind, adapter, label, expected), flush=True) + if first_vs is None: + first_vs, first_ps, first_exp = vs_bin, ps_bin, raw_exp + + # Negative control: deliberately wrong expected word must fail draw(). + bad = words_text((first_exp[0] ^ 1, first_exp[1], first_exp[2], first_exp[3])) + neg = draw(renderer, adapter, first_vs, first_ps, bad) + check('draw %s %s negative control rejects wrong expectation' % (kind, adapter), + neg.returncode != 0) + + +if __name__ == '__main__': + if len(sys.argv) == 1: + run_controls() + print('s_bitcmp64 controls: ok') + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + run_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + print('s_bitcmp64 draw (%s): ok' % sys.argv[4]) + else: + print('usage: startup_gfx2hlsl_s_bitcmp64_check.py [draw [fxc]]', + file=sys.stderr) + sys.exit(2) diff --git a/tests/startup_gfx2hlsl_s_bitset64_check.py b/tests/startup_gfx2hlsl_s_bitset64_check.py new file mode 100644 index 0000000000..59df39b6c4 --- /dev/null +++ b/tests/startup_gfx2hlsl_s_bitset64_check.py @@ -0,0 +1,383 @@ +"""64-bit scalar bit set/clear (s_bitset0_b64, s_bitset1_b64) in tools/startup/gfx2hlsl.py. + + (no arguments) SOP1 decode, value evaluation, aliasing, constant folding, uniformity, + refusal and mutation controls, pure Python + draw [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per (lo, hi, index) triple and compare the four result words + +RDNA 2 ISA, SOP1: + S_BITSET0_B64 s[D:D+1], S0: D.u64[S0.u[5:0]] = 0; SCC unchanged. + S_BITSET1_B64 s[D:D+1], S0: D.u64[S0.u[5:0]] = 1; SCC unchanged. + +The pixel fixture decodes synthetic gfx1013 bytes via G.decode() ONLY (no game data). It loads (lo, hi, index) +into s[4:5]/s6 and s[8:9]/s6 with SOP1 literal moves, runs s_bitset0_b64 on s[4:5] and s_bitset1_b64 on s[8:9], +XORs the resulting four 32-bit words with 0x3f800000 for normal IEEE-754 transport into v12..v15, and exports mrt0. +""" +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + vs_words, + words_text, +) + +SOP1_OPCODES = { + 's_bitset0_b64': 0x1c, + 's_bitset1_b64': 0x1e, +} + +# Keep exported lanes away from NaN/subnormal bit patterns on float render targets. +DRAW_TRANSPORT_XOR = 0x3f800000 + + +def sop1(op, sdst, ssrc0, lit=None): + """Encode one synthetic gfx1013 SOP1 32-bit (or 64-bit with literal) instruction.""" + w0 = (0b101111101 << 23) | (sdst << 16) | (op << 8) | ssrc0 + out = struct.pack('> 32) & MASK + + +def eval_u32_expr(expr, env): + """Evaluate a translated HLSL uint expression (with optional ternaries) in Python.""" + text = re.sub(r'\b(0x[0-9a-fA-F]+|\d+)u\b', r'\1', expr) + while '?' in text: + q = text.index('?') + depth = 0 + start = q - 1 + while start >= 0: + if text[start] == ')': + depth += 1 + elif text[start] == '(': + if depth == 0: + break + depth -= 1 + start -= 1 + depth = 0 + colon = -1 + end = q + 1 + while end < len(text): + if text[end] == '(': + depth += 1 + elif text[end] == ')': + if depth == 0: + break + depth -= 1 + elif text[end] == ':' and depth == 0 and colon == -1: + colon = end + end += 1 + cond = text[start + 1:q].strip() + yes = text[q + 1:colon].strip() + no = text[colon + 1:end].strip() + text = text[:start] + ('((%s) if (%s) else (%s))' % (yes, cond, no)) + text[end + 1:] + return eval(text, {'__builtins__': {}}, env) & MASK + + +def run_lines(line, env, *, sym=None): + stage = Probe() + if sym: + stage.sym.update(sym) + stage.one(line.split(' ', 1)[0], line) + out = dict(env) + for stmt in stage.lines: + m = re.fullmatch(r'(\w+) = (.*);', stmt) + assert m, stmt + assert m.group(1) != 'scc', 'SCC must remain unchanged: %s' % stmt + out[m.group(1)] = eval_u32_expr(m.group(2), out) + return out, stage + + +def stage_refused(stage, mnemonic, line, needle=''): + try: + stage.one(mnemonic, line) + except G.Unsupported as exc: + return (not needle or needle in str(exc)) and not stage.lines + return False + + +PAIRS = ( + (0x00000000, 0x00000000), + (0xffffffff, 0xffffffff), + (0x00000001, 0x80000000), + (0x80000000, 0x00000001), + (0xffffffff, 0x00000000), + (0x00000000, 0xffffffff), + (0x55555555, 0xaaaaaaaa), + (0x12345678, 0x9abcdef0), +) +INDEXES = (0, 1, 5, 31, 32, 33, 37, 63, 64, 65, 96, 127, 0xffffffe5) + + +def run_controls(): + # 1. Decode verification from synthetic gfx1013 SOP1 bytes via G.decode(). + decoded = [ + G.decode(sop1(0x1c, 4, 6))[0][3], + G.decode(sop1(0x1e, 4, 128 + 37))[0][3], + G.decode(sop1(0x1c, 4, 255, lit=0x25))[0][3], + G.decode(sop1(0x1e, 4, 125))[0][3], + ] + check('decode s_bitset0_b64 reg/reg', decoded[0] == 's_bitset0_b64 s[4:5], s6') + check('decode s_bitset1_b64 reg/imm37', decoded[1] == 's_bitset1_b64 s[4:5], 37') + check('decode s_bitset0_b64 literal', decoded[2] == 's_bitset0_b64 s[4:5], 0x25') + check('decode s_bitset1_b64 null', decoded[3] == 's_bitset1_b64 s[4:5], null') + + # 2. Exhaustive SGPR pair + register/immediate index grid (SCC untouched). + grid_ok = True + for mnemonic, clear in (('s_bitset0_b64', True), ('s_bitset1_b64', False)): + for lo, hi in PAIRS: + for idx in INDEXES: + want_lo, want_hi = ref_bitset64(clear, lo, hi, idx) + for line, env in ( + ('%s s[4:5], s6' % mnemonic, {'s4': lo, 's5': hi, 's6': idx}), + ('%s s[4:5], %d' % (mnemonic, idx), {'s4': lo, 's5': hi}), + ): + out, _ = run_lines(line, env) + if (out['s4'], out['s5']) != (want_lo, want_hi): + grid_ok = False + print('MISMATCH %s lo=%#x hi=%#x idx=%#x got=(%#x,%#x) want=(%#x,%#x)' % ( + line, lo, hi, idx, out['s4'], out['s5'], want_lo, want_hi)) + check('SGPR pair grid (%d cases)' % (2 * len(PAIRS) * len(INDEXES) * 2), grid_ok) + + # 3. Aliasing: S0 == s4 (low word of destination pair) and S0 == s5 (high word of destination pair). + alias_ok = True + for mnemonic, clear in (('s_bitset0_b64', True), ('s_bitset1_b64', False)): + for lo, hi in ((0, 0), (35, 0), (35, 0xffffffff), (5, 0x12345678), (63, 0x80000000), (0, 37), (0xffffffff, 5)): + out_lo, _ = run_lines('%s s[4:5], s4' % mnemonic, {'s4': lo, 's5': hi}) + if (out_lo['s4'], out_lo['s5']) != ref_bitset64(clear, lo, hi, lo): + alias_ok = False + out_hi, _ = run_lines('%s s[4:5], s5' % mnemonic, {'s4': lo, 's5': hi}) + if (out_hi['s4'], out_hi['s5']) != ref_bitset64(clear, lo, hi, hi): + alias_ok = False + check('aliasing s[4:5], s4 and s[4:5], s5 preserve original index', alias_ok) + + # 4. Constant folding (imm, null, and const-tracked SGPR index) leaves the untouched half's sym intact. + for mnemonic, clear in (('s_bitset0_b64', True), ('s_bitset1_b64', False)): + out_lo, st_lo = run_lines('%s s[4:5], 5' % mnemonic, {'s4': 0x20, 's5': 0x77}, + sym={4: ('const', 0x20), 5: ('const', 0x77)}) + want_lo, want_hi = ref_bitset64(clear, 0x20, 0x77, 5) + check('%s folds const low word (bit 5)' % mnemonic, + st_lo.sym.get(4) == ('const', want_lo) and st_lo.sym.get(5) == ('const', 0x77) + and out_lo['s4'] == want_lo and len(st_lo.lines) == 1) + out_hi, st_hi = run_lines('%s s[4:5], 37' % mnemonic, {'s4': 0x77, 's5': 0x20}, + sym={4: ('const', 0x77), 5: ('const', 0x20)}) + want_lo, want_hi = ref_bitset64(clear, 0x77, 0x20, 37) + check('%s folds const high word (bit 37)' % mnemonic, + st_hi.sym.get(4) == ('const', 0x77) and st_hi.sym.get(5) == ('const', want_hi) + and out_hi['s5'] == want_hi and len(st_hi.lines) == 1) + out_null, _ = run_lines('%s s[4:5], null' % mnemonic, {'s4': 1, 's5': 0x10}) + check('%s null targets bit 0' % mnemonic, (out_null['s4'], out_null['s5']) == ref_bitset64(clear, 1, 0x10, 0)) + out_cs, st_cs = run_lines('%s s[4:5], s6' % mnemonic, {'s4': 0, 's5': 0}, + sym={4: ('const', 0), 5: ('const', 0), 6: ('const', 63)}) + want_lo, want_hi = ref_bitset64(clear, 0, 0, 63) + check('%s folds const SGPR index 63' % mnemonic, + st_cs.sym.get(5) == ('const', want_hi) and out_cs['s5'] == want_hi) + + # 5. Uniformity tracking (varying index taints both halves; varying half stays varying). + for mnemonic in ('s_bitset0_b64', 's_bitset1_b64'): + s = Probe() + s.varying_s = {6} + s.scc_uniform = True + s.one(mnemonic, '%s s[4:5], s6' % mnemonic) + check('%s varying index taints s4 and s5' % mnemonic, 4 in s.varying_s and 5 in s.varying_s) + s = Probe() + s.varying_s = {4} + s.scc_uniform = True + s.one(mnemonic, '%s s[4:5], 37' % mnemonic) + check('%s immediate bit 37 keeps s5 uniform when only s4 varies' % mnemonic, + 4 in s.varying_s and 5 not in s.varying_s) + + # 6. Refusals (arity, modifiers, lane masks, mask_high, descriptors, invalid register classes/alignment). + for mnemonic in ('s_bitset0_b64', 's_bitset1_b64'): + check('%s 1 operand refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5]' % mnemonic, 'expected 2 unmodified')) + check('%s 3 operands refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5], s6, s7' % mnemonic, 'expected 2 unmodified')) + check('%s modifier refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5], s6 clamp' % mnemonic, 'expected 2 unmodified')) + for operands in ('exec, 1', 'vcc, 1', 's[4:5], exec_lo', 's[4:5], vcc_lo'): + check('%s %s lane mask refused' % (mnemonic, operands), + stage_refused(Probe(), mnemonic, '%s %s' % (mnemonic, operands))) + for mask_reg, high_reg, operands in ( + (12, None, 's[12:13], 1'), + (13, None, 's[12:13], 1'), + (None, 13, 's[12:13], 1'), + (12, None, 's[4:5], s12'), + (None, 13, 's[4:5], s13'), + ): + p = Probe() + if mask_reg is not None: + p.masks = {mask_reg} + if high_reg is not None: + p.mask_high = {high_reg} + check('%s %s tracked mask refused' % (mnemonic, operands), + stage_refused(p, mnemonic, '%s %s' % (mnemonic, operands), 'lane mask')) + for bad_dst in ('v[0:1]', 's4', 's[5:6]', 's[106:107]', 'm0'): + check('%s bad dst %s refused' % (mnemonic, bad_dst), + stage_refused(Probe(), mnemonic, '%s %s, s6' % (mnemonic, bad_dst), 'destination')) + for bad_src in ('v0', 's[6:7]', 's106', '1.0', 'm0', 'src_scc'): + check('%s bad src %s refused' % (mnemonic, bad_src), + stage_refused(Probe(), mnemonic, '%s s[4:5], %s' % (mnemonic, bad_src), 'source')) + for sym_reg, operands in ((4, 's[4:5], 1'), (5, 's[4:5], 1'), (6, 's[4:5], s6')): + p = Probe() + p.sym[sym_reg] = ('descriptor', 0) + check('%s descriptor sym on s%d refused' % (mnemonic, sym_reg), + stage_refused(p, mnemonic, '%s %s' % (mnemonic, operands), 'descriptor data')) + + # 7. Full synthetic pixel pipeline translates cleanly through G.Pipeline(). + _, ps_hlsl = translate_ps() + check('synthetic pixel pipeline translates', '& 32u' in ps_hlsl and '& 31u' in ps_hlsl) + + # 8. Unlowered control: removing handlers from Stage restores refusals. + saved = {name: getattr(G.Stage, name) for name in ('op_s_bitset0_b64', 'op_s_bitset1_b64')} + try: + for name in saved: + delattr(G.Stage, name) + for mnemonic in ('s_bitset0_b64', 's_bitset1_b64'): + check('unlowered %s refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5], s6' % mnemonic)) + try: + translate_ps() + except G.Unsupported: + check('unlowered synthetic pipeline refused', True) + else: + check('unlowered synthetic pipeline refused', False) + finally: + for name, fn in saved.items(): + setattr(G.Stage, name, fn) + + # 9. Mutation / negative controls. + check('mutation: dropping bit 5 diverges on bit 37', + ref_bitset64(False, 0, 0, 37) != ref_bitset64(False, 0, 0, 37 & 31)) + check('mutation: swapping clear/set diverges', + ref_bitset64(True, 0, 0x20, 37) != ref_bitset64(False, 0, 0x20, 37)) + + +GPU_VECTORS = ( + # Use small low/high patterns whose XOR with 0x3f800000 stays a normal IEEE-754 float (exponent 0x7f). + # (label, lo, hi, idx) + ('lo_bit0', 0x00000001, 0x00000000, 0), + ('lo_bit20', 0x00100000, 0x00000000, 20), + ('hi_bit32', 0x00000000, 0x00000001, 32), + ('hi_bit37', 0x00000000, 0x00000020, 37), + ('hi_bit52', 0x00000000, 0x00100000, 52), + ('wrap_101', 0x00000000, 0x00000020, 101), # 101 & 63 == 37 + ('wrap_64', 0x00000001, 0x00000000, 64), # 64 & 63 == 0 +) + + +def run_draw(dxc, renderer, adapter, fxc=None): + run_controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory(prefix='x2w_s_bitset64_') as tmp: + td = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + first_vs = None + first_ps = None + first_exp = None + for label, lo, hi, idx in GPU_VECTORS: + vs_hlsl, ps_hlsl = translate_ps(lo, hi, idx) + vs_bin = compile_hlsl(compiler, kind, vs_hlsl, 'vs_%s_%s' % (label, kind), vs_profile, td) + ps_bin = compile_hlsl(compiler, kind, ps_hlsl, 'ps_%s_%s' % (label, kind), ps_profile, td) + c0, c1 = ref_bitset64(True, lo, hi, idx) + s0, s1 = ref_bitset64(False, lo, hi, idx) + raw_exp = ( + c0 ^ DRAW_TRANSPORT_XOR, + c1 ^ DRAW_TRANSPORT_XOR, + s0 ^ DRAW_TRANSPORT_XOR, + s1 ^ DRAW_TRANSPORT_XOR, + ) + expected = words_text(raw_exp) + res = draw(renderer, adapter, vs_bin, ps_bin, expected) + if res.returncode == 77: + print('SKIP (%s): %s' % (adapter, res.stdout.strip() or res.stderr.strip())) + sys.exit(77) + if res.returncode != 0: + raise AssertionError('%s %s %s expected=%s\n%s\n%s' % ( + kind, adapter, label, expected, res.stdout, res.stderr)) + print('%s %s %s: %s' % (kind, adapter, label, expected), flush=True) + if first_vs is None: + first_vs, first_ps, first_exp = vs_bin, ps_bin, raw_exp + + # Negative control: deliberately wrong expected word must fail draw(). + bad = words_text((first_exp[0] ^ 1, first_exp[1], first_exp[2], first_exp[3])) + neg = draw(renderer, adapter, first_vs, first_ps, bad) + check('draw %s %s negative control rejects wrong expectation' % (kind, adapter), + neg.returncode != 0) + + +if __name__ == '__main__': + if len(sys.argv) == 1: + run_controls() + print('s_bitset64 controls: ok') + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + run_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + print('s_bitset64 draw (%s): ok' % sys.argv[4]) + else: + print('usage: startup_gfx2hlsl_s_bitset64_check.py [draw [fxc]]', + file=sys.stderr) + sys.exit(2) diff --git a/tests/startup_gfx2hlsl_s_cmp64_check.py b/tests/startup_gfx2hlsl_s_cmp64_check.py new file mode 100644 index 0000000000..5a48dbd648 --- /dev/null +++ b/tests/startup_gfx2hlsl_s_cmp64_check.py @@ -0,0 +1,368 @@ +"""64-bit scalar equality comparisons (s_cmp_eq_u64, s_cmp_lg_u64) in tools/startup/gfx2hlsl.py. + + (no arguments) SOPC decode, value evaluation, uniformity, refusal and mutation + controls, pure Python + draw [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per 64-bit pair and compare the four result words + +RDNA 2 ISA, SOPC: + S_CMP_EQ_U64 S0, S1: SCC = (S0.u64 == S1.u64) + S_CMP_LG_U64 S0, S1: SCC = (S0.u64 != S1.u64) + +The pixel fixture decodes synthetic gfx1013 bytes via G.decode() ONLY (no game data). It loads two 64-bit +values into s[4:5] and s[6:7] with SOP1 literal moves, executes s_cmp_eq_u64 / s_cmp_lg_u64 (pair vs pair, +pair vs sign-extended inline -1, and pair vs zero-extended 32-bit hex literal 0x80000001), materializes each +SCC via s_cselect_b32, XORs with 0x3f800000 for normal IEEE-754 transport into v12..v15, and exports mrt0. +""" +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + vs_words, + words_text, +) + +SOPC_OPCODES = { + 's_cmp_eq_u64': 0x12, + 's_cmp_lg_u64': 0x13, +} + +# XOR 0/1 with 0x3f800000 so exported lanes are normal IEEE-754 floats (1.0 / 1.0 + 1 ULP), never subnormals. +DRAW_TRANSPORT_XOR = 0x3f800000 + + +def sopc(op, ssrc0, ssrc1, lit=None): + """Encode one synthetic gfx1013 SOPC 32-bit (or 64-bit with literal) instruction.""" + w0 = 0xbf000000 | (op << 16) | (ssrc1 << 8) | ssrc0 + out = struct.pack(', <32-bit literal> (op 0x03, ssrc0=255).""" + return struct.pack('<2I', (0b101111101 << 23) | (sdst << 16) | (0x03 << 8) | 255, val & MASK) + + +def s_cselect_b32(sdst, ssrc0, ssrc1): + """Encode SOP2 s_cselect_b32 s, ssrc0, ssrc1 (op 0x0a).""" + return struct.pack(', s, <32-bit literal> (op 0x12, ssrc1=255).""" + return struct.pack('<2I', 0x80000000 | (0x12 << 23) | (sdst << 16) | (255 << 8) | ssrc0, lit & MASK) + + +def v_mov_b32_from_sgpr(vdst, ssrc): + """Encode VOP1 v_mov_b32_e32 v, s (op 0x01).""" + return struct.pack(' 128, 1 -> 129, -1 -> 193, literal -> 255. + body = b''.join([ + sop1_mov_lit(4, a0), # s4 = a0 + sop1_mov_lit(5, a1), # s5 = a1 + sop1_mov_lit(6, b0), # s6 = b0 + sop1_mov_lit(7, b1), # s7 = b1 + sopc(0x12, 4, 6), # s_cmp_eq_u64 s[4:5], s[6:7] + s_cselect_b32(8, 129, 128), # s8 = scc ? 1 : 0 + s_xor_lit(8, 8, DRAW_TRANSPORT_XOR), + v_mov_b32_from_sgpr(12, 8), # v12 = (a == b) ^ 0x3f800000 + sopc(0x13, 4, 6), # s_cmp_lg_u64 s[4:5], s[6:7] + s_cselect_b32(9, 129, 128), # s9 = scc ? 1 : 0 + s_xor_lit(9, 9, DRAW_TRANSPORT_XOR), + v_mov_b32_from_sgpr(13, 9), # v13 = (a != b) ^ 0x3f800000 + sopc(0x12, 4, 193), # s_cmp_eq_u64 s[4:5], -1 + s_cselect_b32(10, 129, 128), # s10 = scc ? 1 : 0 + s_xor_lit(10, 10, DRAW_TRANSPORT_XOR), + v_mov_b32_from_sgpr(14, 10), # v14 = (a == 0xffffffff_ffffffff) ^ 0x3f800000 + sopc(0x12, 4, 255, lit=0x80000001), # s_cmp_eq_u64 s[4:5], 0x80000001 + s_cselect_b32(11, 129, 128), # s11 = scc ? 1 : 0 + s_xor_lit(11, 11, DRAW_TRANSPORT_XOR), + v_mov_b32_from_sgpr(15, 11), # v15 = (a == 0x00000000_80000001) ^ 0x3f800000 + ]) + return PRE_WORDS + body + POST_WORDS + + +def translate_ps(a0=0x00000001, a1=0x00000002, b0=0x00000001, b1=0x00000002): + zero = [(0, 0, 0)] * 4 + pipe = G.Pipeline(vs_words(zero), ps_words(a0, a1, b0, b1), root_blob()) + return pipe.hlsl_vs(), pipe.hlsl_ps() + + +def ref_cmp64(eq, a0, a1, b0, b1): + """Independent 64-bit integer reference for S_CMP_EQ_U64 / S_CMP_LG_U64.""" + a = ((a1 & MASK) << 32) | (a0 & MASK) + b = ((b1 & MASK) << 32) | (b0 & MASK) + return (a == b) if eq else (a != b) + + +def eval_scc_expr(expr, env): + """Evaluate a translated HLSL boolean SCC expression in Python.""" + text = re.sub(r'\b(0x[0-9a-fA-F]+|\d+)u\b', r'\1', expr) + text = text.replace('&&', ' and ').replace('||', ' or ') + return bool(eval(text, {'__builtins__': {}}, env)) + + +def run_one(line, env, *, sym=None): + stage = Probe() + if sym: + stage.sym.update(sym) + stage.one(line.split(' ', 1)[0], line) + assert len(stage.lines) == 1, stage.lines + target, _, expr = stage.lines[0].rstrip(';').partition(' = ') + assert target == 'scc', stage.lines + return eval_scc_expr(expr, env), stage + + +def stage_refused(stage, mnemonic, line, needle=''): + try: + stage.one(mnemonic, line) + except G.Unsupported as exc: + return (not needle or needle in str(exc)) and not stage.lines + return False + + +WORDS64 = ( + (0x00000000, 0x00000000), + (0x00000001, 0x00000000), + (0x00000000, 0x00000001), + (0xffffffff, 0x00000000), + (0x00000000, 0xffffffff), + (0xffffffff, 0xffffffff), + (0x80000001, 0x00000000), + (0x80000001, 0xffffffff), + (0x12345678, 0x9abcdef0), + (0x12345678, 0x9abcdef1), + (0x12345679, 0x9abcdef0), +) + + +def run_controls(): + # 1. Decode verification from synthetic gfx1013 SOPC bytes via G.decode(). + decoded = [ + G.decode(sopc(0x12, 4, 6))[0][3], + G.decode(sopc(0x13, 4, 6))[0][3], + G.decode(sopc(0x12, 4, 193))[0][3], + G.decode(sopc(0x13, 255, 6, lit=0x80000001))[0][3], + G.decode(sopc(0x12, 125, 128))[0][3], + ] + check('decode s_cmp_eq_u64 pair/pair', decoded[0] == 's_cmp_eq_u64 s[4:5], s[6:7]') + check('decode s_cmp_lg_u64 pair/pair', decoded[1] == 's_cmp_lg_u64 s[4:5], s[6:7]') + check('decode s_cmp_eq_u64 inline -1', decoded[2] == 's_cmp_eq_u64 s[4:5], -1') + check('decode s_cmp_lg_u64 literal', decoded[3] == 's_cmp_lg_u64 0x80000001, s[6:7]') + check('decode s_cmp_eq_u64 null/0', decoded[4] == 's_cmp_eq_u64 null, 0') + + # 2. Exhaustive SGPR pair x SGPR pair grid (including low-only and high-only mismatches). + grid_ok = True + for mnemonic, eq in (('s_cmp_eq_u64', True), ('s_cmp_lg_u64', False)): + for a0, a1 in WORDS64: + for b0, b1 in WORDS64: + expected = ref_cmp64(eq, a0, a1, b0, b1) + got, _ = run_one('%s s[4:5], s[6:7]' % mnemonic, + {'s4': a0, 's5': a1, 's6': b0, 's7': b1}) + if got != expected: + grid_ok = False + print('MISMATCH %s a=(%#x,%#x) b=(%#x,%#x) got=%s want=%s' % ( + mnemonic, a0, a1, b0, b1, got, expected)) + check('SGPR pair grid (%d cases)' % (2 * len(WORDS64) * len(WORDS64)), grid_ok) + + # 3. Inline integer 64-bit operands (negative values sign-extend to 64 bits). + inline_ok = True + for mnemonic, eq in (('s_cmp_eq_u64', True), ('s_cmp_lg_u64', False)): + for val in (0, 1, 64, -1, -16): + v0, v1 = val & MASK, (val >> 32) & MASK + for a0, a1 in ((v0, v1), (v0, 0), (v0, 0xffffffff), (0, v1)): + got_r, _ = run_one('%s s[4:5], %d' % (mnemonic, val), {'s4': a0, 's5': a1}) + got_l, _ = run_one('%s %d, s[4:5]' % (mnemonic, val), {'s4': a0, 's5': a1}) + want = ref_cmp64(eq, a0, a1, v0, v1) + if got_r != want or got_l != want: + inline_ok = False + check('inline integers sign-extend negative values to 64 bits', inline_ok) + + # 4. 32-bit hex literal zero-extends to 64 bits (hi == 0 even when bit 31 is set). + lit_ok = True + for mnemonic, eq in (('s_cmp_eq_u64', True), ('s_cmp_lg_u64', False)): + for a0, a1 in ((0x80000001, 0), (0x80000001, 0xffffffff), (0x80000000, 0)): + got_r, _ = run_one('%s s[4:5], 0x80000001' % mnemonic, {'s4': a0, 's5': a1}) + got_l, _ = run_one('%s 0x80000001, s[4:5]' % mnemonic, {'s4': a0, 's5': a1}) + want = ref_cmp64(eq, a0, a1, 0x80000001, 0) + if got_r != want or got_l != want: + lit_ok = False + check('32-bit hex literal zero-extends to 64 bits', lit_ok) + + # 5. null operand and const-tracked SGPR pair. + for mnemonic, eq in (('s_cmp_eq_u64', True), ('s_cmp_lg_u64', False)): + got_zero, _ = run_one('%s s[4:5], null' % mnemonic, {'s4': 0, 's5': 0}) + got_hi, _ = run_one('%s null, s[4:5]' % mnemonic, {'s4': 0, 's5': 1}) + check('%s null == 0' % mnemonic, got_zero == eq) + check('%s null != (0, 1)' % mnemonic, got_hi == (not eq)) + got_const, _ = run_one('%s s[4:5], s[6:7]' % mnemonic, {'s5': 0x99, 's6': 0x42, 's7': 0x99}, + sym={4: ('const', 0x42)}) + check('%s const-tracked lo + runtime hi' % mnemonic, got_const == eq) + + # 6. Uniformity tracking across all four registers s4, s5, s6, s7. + for mnemonic in ('s_cmp_eq_u64', 's_cmp_lg_u64'): + s = Probe() + s.varying_s = set() + s.scc_uniform = False + s.one(mnemonic, '%s s[4:5], s[6:7]' % mnemonic) + check('%s uniform inputs -> scc_uniform=True' % mnemonic, s.scc_uniform is True) + for bad_reg in (4, 5, 6, 7): + s = Probe() + s.varying_s = {bad_reg} + s.scc_uniform = True + s.one(mnemonic, '%s s[4:5], s[6:7]' % mnemonic) + check('%s varying s%d -> scc_uniform=False' % (mnemonic, bad_reg), s.scc_uniform is False) + + # 7. Refusals (arity, modifiers, lane masks, mask_high, invalid register classes/alignment). + for mnemonic in ('s_cmp_eq_u64', 's_cmp_lg_u64'): + check('%s 1 operand refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5]' % mnemonic, 'two unmodified operands')) + check('%s 3 operands refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5], s[6:7], s[8:9]' % mnemonic, 'two unmodified operands')) + check('%s modifier refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5], s[6:7] clamp' % mnemonic, 'two unmodified operands')) + for operands in ( + 'exec, s[6:7]', 'exec_lo, s[6:7]', 'vcc, s[6:7]', 'vcc_lo, s[6:7]', + 's[4:5], exec', 's[4:5], exec_lo', 's[4:5], vcc', 's[4:5], vcc_lo', + ): + check('%s %s lane mask refused' % (mnemonic, operands), + stage_refused(Probe(), mnemonic, '%s %s' % (mnemonic, operands), 'lane mask')) + for mask_reg, high_reg, operands in ( + (12, None, 's[12:13], s[6:7]'), + (13, None, 's[12:13], s[6:7]'), + (None, 13, 's[12:13], s[6:7]'), + (12, None, 's[4:5], s[12:13]'), + (13, None, 's[4:5], s[12:13]'), + (None, 13, 's[4:5], s[12:13]'), + ): + p = Probe() + if mask_reg is not None: + p.masks = {mask_reg} + if high_reg is not None: + p.mask_high = {high_reg} + check('%s %s tracked mask refused' % (mnemonic, operands), + stage_refused(p, mnemonic, '%s %s' % (mnemonic, operands), 'lane mask')) + for bad_op in ('v[0:1]', 's4', 's[5:6]', 's[106:107]', '1.0', 'm0', 'src_scc'): + check('%s bad S0 %s refused' % (mnemonic, bad_op), + stage_refused(Probe(), mnemonic, '%s %s, s[6:7]' % (mnemonic, bad_op))) + check('%s bad S1 %s refused' % (mnemonic, bad_op), + stage_refused(Probe(), mnemonic, '%s s[4:5], %s' % (mnemonic, bad_op))) + + # 8. Full synthetic pixel pipeline translates cleanly through G.Pipeline(). + _, ps_hlsl = translate_ps() + check('synthetic pixel pipeline translates', '&&' in ps_hlsl and '||' in ps_hlsl) + + # 9. Unlowered control: removing handlers from Stage restores refusals. + saved = {name: getattr(G.Stage, name) for name in ('op_s_cmp_eq_u64', 'op_s_cmp_lg_u64')} + try: + for name in saved: + delattr(G.Stage, name) + for mnemonic in ('s_cmp_eq_u64', 's_cmp_lg_u64'): + check('unlowered %s refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5], s[6:7]' % mnemonic)) + try: + translate_ps() + except G.Unsupported: + check('unlowered synthetic pipeline refused', True) + else: + check('unlowered synthetic pipeline refused', False) + finally: + for name, fn in saved.items(): + setattr(G.Stage, name, fn) + + # 10. Mutation / negative controls: prove our inputs distinguish common bugs. + check('mutation: ignoring high word diverges on (1,0) vs (1,1)', + ref_cmp64(True, 1, 0, 1, 1) != (1 == 1)) + check('mutation: ignoring low word diverges on (0,1) vs (1,1)', + ref_cmp64(True, 0, 1, 1, 1) != (1 == 1)) + check('mutation: using && instead of || for lg diverges on high-only mismatch', + ref_cmp64(False, 1, 0, 1, 1) != ((1 != 1) and (0 != 1))) + check('mutation: zero-extending -1 diverges on (0xffffffff, 0xffffffff)', + ref_cmp64(True, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff) + != ref_cmp64(True, 0xffffffff, 0xffffffff, 0xffffffff, 0)) + check('mutation: sign-extending 0x80000001 diverges on (0x80000001, 0)', + ref_cmp64(True, 0x80000001, 0, 0x80000001, 0) + != ref_cmp64(True, 0x80000001, 0, 0x80000001, 0xffffffff)) + + +GPU_VECTORS = ( + # (label, a0, a1, b0, b1) + ('equal_pair', 0x12345678, 0x9abcdef0, 0x12345678, 0x9abcdef0), + ('diff_lo_only', 0x12345678, 0x9abcdef0, 0x12345679, 0x9abcdef0), + ('diff_hi_only', 0x12345678, 0x9abcdef0, 0x12345678, 0x9abcdef1), + ('match_inline_m1', 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000), + ('m1_hi_zero_only', 0xffffffff, 0x00000000, 0xffffffff, 0x00000000), + ('match_lit_zext', 0x80000001, 0x00000000, 0x00000000, 0x00000000), + ('lit_hi_all_ones', 0x80000001, 0xffffffff, 0x80000001, 0xffffffff), +) + + +def run_draw(dxc, renderer, adapter, fxc=None): + run_controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory(prefix='x2w_s_cmp64_') as tmp: + td = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + first_vs = None + first_ps = None + first_exp = None + for label, a0, a1, b0, b1 in GPU_VECTORS: + vs_hlsl, ps_hlsl = translate_ps(a0, a1, b0, b1) + vs_bin = compile_hlsl(compiler, kind, vs_hlsl, 'vs_%s_%s' % (label, kind), vs_profile, td) + ps_bin = compile_hlsl(compiler, kind, ps_hlsl, 'ps_%s_%s' % (label, kind), ps_profile, td) + raw_exp = ( + (1 if ref_cmp64(True, a0, a1, b0, b1) else 0) ^ DRAW_TRANSPORT_XOR, + (1 if ref_cmp64(False, a0, a1, b0, b1) else 0) ^ DRAW_TRANSPORT_XOR, + (1 if ref_cmp64(True, a0, a1, 0xffffffff, 0xffffffff) else 0) ^ DRAW_TRANSPORT_XOR, + (1 if ref_cmp64(True, a0, a1, 0x80000001, 0x00000000) else 0) ^ DRAW_TRANSPORT_XOR, + ) + expected = words_text(raw_exp) + res = draw(renderer, adapter, vs_bin, ps_bin, expected) + if res.returncode == 77: + print('SKIP (%s): %s' % (adapter, res.stdout.strip() or res.stderr.strip())) + sys.exit(77) + if res.returncode != 0: + raise AssertionError('%s %s %s expected=%s\n%s\n%s' % ( + kind, adapter, label, expected, res.stdout, res.stderr)) + print('%s %s %s: %s' % (kind, adapter, label, expected), flush=True) + if first_vs is None: + first_vs, first_ps, first_exp = vs_bin, ps_bin, raw_exp + + # Negative control: deliberately wrong expected word must fail draw(). + bad = words_text((first_exp[0] ^ 1, first_exp[1], first_exp[2], first_exp[3])) + neg = draw(renderer, adapter, first_vs, first_ps, bad) + check('draw %s %s negative control rejects wrong expectation' % (kind, adapter), + neg.returncode != 0) + + +if __name__ == '__main__': + if len(sys.argv) == 1: + run_controls() + print('s_cmp64 controls: ok') + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + run_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + print('s_cmp64 draw (%s): ok' % sys.argv[4]) + else: + print('usage: startup_gfx2hlsl_s_cmp64_check.py [draw [fxc]]', + file=sys.stderr) + sys.exit(2) diff --git a/tests/startup_image_3d.cpp b/tests/startup_image_3d.cpp index 8305017fdf..60dede5d87 100644 --- a/tests/startup_image_3d.cpp +++ b/tests/startup_image_3d.cpp @@ -64,7 +64,7 @@ ComPtr create_root(ID3D12Device* device, const x2w_startup: // array: the same eight texels as two slices of a 2D array (dim:SQ_RSRC_IMG_2D_ARRAY); the default // view of a two-slice texture is a Texture2DArray over both. Multi-mip fixtures use a 4x4 base. -// A nonzero view_levels selects an explicit 2D SRV starting at first_mip. When sampler_line is a +// A nonzero view_levels selects an explicit 2D or 2D-array SRV starting at first_mip. When sampler_line is a // comparison sampler (smpc), the texture uses DXGI_FORMAT_R32_FLOAT holding the red channel as depth. 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, UINT levels, bool one_dimensional, @@ -72,14 +72,30 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const { if (levels < 1 || levels > max_levels || (levels > 1 && !array && !two_dimensional && !one_dimensional)) throw std::runtime_error("Unsupported image mip level count"); - if (view_levels && (!two_dimensional || first_mip >= levels || view_levels > levels - first_mip)) + if (view_levels && ((!two_dimensional && !array) || first_mip >= levels || view_levels > levels - first_mip)) throw std::runtime_error("2D mip window exceeds the resource"); const UINT base = levels > 1 ? mip_base : side; const auto vs = read_blob(vertex_path); const auto ps = read_blob(pixel_path); x2w_startup::TranslatedSamplers samplers; - if (!samplers.read_manifest_line(sampler_line) || samplers.statics.size() != 1) - throw std::runtime_error("Expected one inline sampler in the image 3D draw"); + const char* newline = std::strchr(sampler_line, '\n'); + if (!newline) { + if (!samplers.read_manifest_line(sampler_line) || samplers.statics.size() != 1) + throw std::runtime_error("Expected one inline sampler in the image 3D draw"); + } else { + const std::string first(sampler_line, newline); + const char* second = newline + 1; + int first_index = -1, second_index = -1; + if (!two_dimensional || !view_levels || std::strchr(second, '\n') || + (std::sscanf(first.c_str(), "smp %d", &first_index) != 1 && + std::sscanf(first.c_str(), "smpl %d", &first_index) != 1) || + (std::sscanf(second, "smp %d", &second_index) != 1 && + std::sscanf(second, "smpl %d", &second_index) != 1) || + first_index != 0 || second_index != 1 || + !samplers.read_manifest_line(first.c_str()) || !samplers.read_manifest_line(second) || + samplers.statics.size() != 2 || samplers.heap || samplers.comparison[0] || samplers.comparison[1]) + throw std::runtime_error("Expected two ordered noncomparison inline samplers in the 2D view draw"); + } const bool comparison = !samplers.comparison.empty() && samplers.comparison[0]; const auto root = create_root(device, samplers); @@ -161,10 +177,16 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const D3D12_SHADER_RESOURCE_VIEW_DESC view{}; if (view_levels) { view.Format = td.Format; - view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + view.ViewDimension = array ? D3D12_SRV_DIMENSION_TEXTURE2DARRAY : D3D12_SRV_DIMENSION_TEXTURE2D; view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - view.Texture2D.MostDetailedMip = first_mip; - view.Texture2D.MipLevels = view_levels; + if (array) { + view.Texture2DArray.MostDetailedMip = first_mip; + view.Texture2DArray.MipLevels = view_levels; + view.Texture2DArray.ArraySize = td.DepthOrArraySize; + } else { + view.Texture2D.MostDetailedMip = first_mip; + view.Texture2D.MipLevels = view_levels; + } } device->CreateShaderResourceView(texture.Get(), view_levels ? &view : nullptr, views->GetCPUDescriptorHandleForHeapStart()); hd = {D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}; diff --git a/tests/startup_image_get_lod_view_check.py b/tests/startup_image_get_lod_view_check.py index 9dd9652e8a..133ea3a516 100644 --- a/tests/startup_image_get_lod_view_check.py +++ b/tests/startup_image_get_lod_view_check.py @@ -1,4 +1,4 @@ -"""Draw gfx1013 image_get_lod through the translated static sampler and four views of a 4x4 texture.""" +"""Draw gfx1013 image_get_lod through translated static samplers and 2D/array mip views.""" import re import struct import subprocess @@ -28,6 +28,31 @@ return float4(clamped, raw, clamped, raw); } """ +SLICE_LIT = bytes.fromhex('ff02047e') # v_mov_b32 v2, (VOP1 literal): the slice dword of the array address +DIRECT_ARRAY_PS = DIRECT_PS.replace('Texture2D<', 'Texture2DArray<', 1) + + +def patch_sampler(code, low, high): + # s_mov_b32 s25, literal: sampler word 1 carries the two unsigned 4.8 LOD limits. + at = fixture.W2_AT - 4 + assert code[at:at + 4] == bytes.fromhex('800399be') + limits = int(low * 256) | (int(high * 256) << 12) + return code[:at] + struct.pack(': reassemble every recorded fixture. +draw : actual translated shader and manifest readback. +""" +import math +import re +import struct +import sys +import subprocess +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob +from startup_image_sample_b_flow_check import PS_INPUTS, assemble +from startup_image_get_lod_view_check import read_pixel + +CLAMP_XY = 2 | (2 << 3) +PRE = '''s_load_dwordx8 s[16:23], s[8:9], 0x0 +s_mov_b32 s24, 0 +s_mov_b32 s25, 0 +s_mov_b32 s26, 0x4000000 +s_mov_b32 s27, 0 +v_mov_b32_e32 v0, 0x3f900000 +v_mov_b32_e32 v1, 0x3ec00000 +v_mov_b32_e32 v2, 1.0 +''' +POST = '''s_waitcnt vmcnt(0) +exp mrt0 v4, v5, v6, v7 done vm +s_endpgm +''' + + +def arm(w0, w1=0x200000): + return (f's_mov_b32 s24, {w0:#x}\ns_mov_b32 s25, {w1:#x}\n' + 's_mov_b32 s26, 0x4000000\ns_mov_b32 s27, 0\n') + + +def source(name): + form = 'lz' if name == 'lz' else 'b' if name == 'implicit bias' else 'l' + pre = PRE + cond = 's_cmp_lg_u32 s9, 0\ns_cbranch_scc1 BB1\n' + if name == 'nonuniform': + pre = 'v_mov_b32_e32 v8, v0\n' + pre + cond = 'v_cmp_eq_u32_e32 vcc, 0, v8\ns_cbranch_vccz BB1\n' + taken = arm(CLAMP_XY | 0x8000 if name == 'invalid mode' else CLAMP_XY) + if name == 'l_word1': + taken = arm(0, 0) + if name == 'high word1': + # Bit 24 of word1 sits above the translator's whole-word1 mask; a sampler keeping it must be refused. + taken = arm(CLAMP_XY, 0x200000 | (1 << 24)) + if name == 'partial': + taken = f's_mov_b32 s24, {CLAMP_XY:#x}\n' + tail = 's_mov_b32 s24, s9\n' if name == 'overwrite' else '' + if name == 'extra branch': + tail = 's_cbranch_scc1 BB3\nBB3:\n' + addr = 'v[0:1]' if form == 'lz' else 'v[0:2]' + return (pre + cond + arm(0) + 's_branch BB2\nBB1:\n' + taken + 'BB2:\n' + tail + + 's_waitcnt lgkmcnt(0)\n' + + f'image_sample_{form} v[4:7], {addr}, s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D\n' + + POST) + + +WORDS = { + 'l': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', + 'lz': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe7fc08cbf080f9cf00004c400703f8cbf0f1800f804050607000081bf', + 'l_word1': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe050082bf800398be800399beff039abe0000000480039bbe7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', + 'nonuniform': '0003107e04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e8010847d070086bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', + 'partial': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe010082bf920398be7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', + 'overwrite': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe090398be7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', + 'invalid mode': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe070082bfff0398be12800000ff0399be00002000ff039abe0000000480039bbe7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', + 'high word1': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002001ff039abe0000000480039bbe7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', + 'implicit bias': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe7fc08cbf080f94f00004c400703f8cbf0f1800f804050607000081bf', + 'extra branch': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe000085bf7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', +} +REFUSALS = { + 'nonuniform': 'descriptor operand s[24:27]', + 'partial': 'descriptor operand s[24:27]', + 'overwrite': 'descriptor operand s[24:27]', + 'invalid mode': 'unsupported joined sampler words', + 'high word1': 'unsupported joined sampler words', + 'implicit bias': 'image_sample_b with a sampler that is not constant', + 'extra branch': 'descriptor operand s[24:27]', +} + + +def pipeline(name): + return G.Pipeline(VS_WORDS, bytes.fromhex(WORDS[name]), root_blob(), ps_hw_inputs=PS_INPUTS) + + +def texel(mip, x, y): + return struct.pack('>4f', (1 + x + 4 * y + 32 * mip) / 128, x, y, 2 * mip) + + +# u=1.125 wraps to x=0 or clamps to the final column; v=0.375 is interior. +EXPECTED = { + 'l': (texel(1, 0, 0), texel(1, 1, 0)), + 'lz': (texel(0, 0, 1), texel(0, 3, 1)), + 'l_word1': (texel(1, 0, 0), texel(0, 0, 1)), +} + + +def sampler_manifest(pipe, name): + lines = [line for line in pipe.manifest().splitlines() if line.startswith('smpl ')] + assert len(lines) == 2, lines + fields = [line.split() for line in lines] + assert [int(f[1]) for f in fields] == [0, 1], lines + samplers = [tuple(int(w, 0) for w in f[2:]) for f in fields] + expected = ({(0, 0, 1 << 26, 0), (0, 0x200000, 1 << 26, 0)} if name == 'l_word1' + else {(0, 0x200000, 1 << 26, 0), (CLAMP_XY, 0x200000, 1 << 26, 0)}) + assert set(samplers) == expected, samplers + return lines, samplers + + +def selected_texel(text, samplers, selector): + """Execute this authored dispatcher subset and evaluate its selected point sample independently.""" + regs = {} + pc, scc = 0, False + call = re.compile(r't = \(s(\d+) == (0x[0-9a-f]+)u \? r0\.SampleLevel\(q(\d+), ' + r'float2\(F\(v0\), F\(v1\)\), (F\(v2\)|0)\) : r0\.SampleLevel\(q(\d+), ' + r'float2\(F\(v0\), F\(v1\)\), \4\)\);') + for block in re.finditer(r'^\s*if \(pc == (\d+)\) \{\n(.*?)^\s*\}', text, re.M | re.S): + if int(block[1]) != pc: + continue + for line in block[2].splitlines(): + line = line.strip() + m = re.fullmatch(r'([sv]\d+) = (0x[0-9a-f]+)u;', line) + if m: + regs[m[1]] = int(m[2], 16) + continue + m = re.fullmatch(r'scc = ud1 != (0x[0-9a-f]+)u;', line) + if m: + scc = selector != int(m[1], 16) + continue + m = re.fullmatch(r'pc = \(scc\) \? (\d+) : (\d+);', line) + if m: + pc = int(m[1 if scc else 2]) + continue + m = re.fullmatch(r'pc = (\d+);', line) + if m: + pc = int(m[1]) + continue + m = call.fullmatch(line) + if m: + q = int(m[3] if regs['s' + m[1]] == int(m[2], 16) else m[5]) + def f32(reg): + return struct.unpack('> 12) & 0xfff) // 256) + size = 4 >> mip + def address(coord, mode): + index = math.floor(coord * size) + return index % size if mode == 0 else min(max(index, 0), size - 1) + return texel(mip, address(f32('v0'), w0 & 7), address(f32('v1'), (w0 >> 3) & 7)) + raise AssertionError(f'unmodelled dispatcher statement: {line}') + raise AssertionError('dispatcher never sampled') + + +def controls(): + for name, expected in EXPECTED.items(): + pipe = pipeline(name) + text = pipe.hlsl_ps() + _, samplers = sampler_manifest(pipe, name) + assert 'udsrc 1 rootconst 1 0' in pipe.manifest() + assert expected[0] != expected[1] + for selector, want in zip((0, 0x3f800000), expected): + assert selected_texel(text, samplers, selector) == want, (name, selector) + assert selected_texel(text, samplers[::-1], selector) != want, (name, selector, 'swapped') + for name, reason in REFUSALS.items(): + try: + pipeline(name).hlsl_ps() + except G.Unsupported as error: + assert reason in str(error), (name, reason, str(error)) + else: + raise AssertionError(f'{name} unexpectedly accepted') + print(f'uniform sampler diamond: {len(EXPECTED)} forms, both selector outcomes, ' + f'swapped bindings and {len(REFUSALS)} refusal controls passed') + + +def binary(llvm_mc): + for name, encoded in WORDS.items(): + assert assemble(llvm_mc, source(name)) == bytes.fromhex(encoded), name + print(f'all {len(WORDS)} authored fixtures reassemble exactly') + + +def draw(dxc, renderer, adapter): + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + vs = compile_hlsl(dxc, 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', directory) + for name, expected in EXPECTED.items(): + pipe = pipeline(name) + ps = compile_hlsl(dxc, 'dxc', pipe.hlsl_ps(), f'joined_{name}', 'ps_6_0', directory) + lines, _ = sampler_manifest(pipe, name) + manifest = '\n'.join(lines) + for selector, want in enumerate(expected): + got = read_pixel(renderer, adapter, vs, ps, manifest, '0/3', selector=selector) + assert got == want, (name, selector, got.hex(), want.hex()) + swapped = '\n'.join(f'smpl {i} ' + ' '.join(line.split()[2:]) for i, line in enumerate(reversed(lines))) + got = read_pixel(renderer, adapter, vs, ps, swapped, '0/3', selector=0) + assert got == expected[1] and got != expected[0], (name, 'swapped', got.hex()) + print(f'{name}: actual uniform root selector and swapped binding readback matched') + + +if __name__ == '__main__': + args = sys.argv[1:] + if not args: + controls() + elif args[0] == 'binary' and len(args) == 2: + binary(args[1]) + elif args[0] == 'draw' and len(args) == 4: + draw(*args[1:]) + else: + raise SystemExit(__doc__) diff --git a/tests/startup_image_store.cpp b/tests/startup_image_store.cpp index a428055be9..d6e7ff9f57 100644 --- a/tests/startup_image_store.cpp +++ b/tests/startup_image_store.cpp @@ -1,11 +1,13 @@ // Desktop readback for tools/startup/gfx2hlsl.py's pixel-stage image_store (#1996 item F). // // The translated pixel shader stores to w0 : register(u0), a RWTexture2D, and reads its entry -// constants from cbuffer entry : register(b0). This draws one pixel with that shader and a source-built -// full-screen vertex shader into a 4x4 R32G32B32A32_FLOAT texture whose texels all start as -1.0, then -// reads every texel back. The caller names the one texel it expects the store to change and its value; -// every other texel must still hold -1.0. +// constants from cbuffer entry : register(b0). This draws one or two pixels (coverage) with that shader +// and a source-built full-screen vertex shader into a 4x4 R32G32B32A32_FLOAT texture whose texels all +// start as -1.0, then reads every texel back. The caller names the one texel it expects the store to +// change and its value; every other texel must still hold -1.0. Coverage 2 uses a 2x1 viewport so two +// invocations run in one draw. #include "desktop_gpu.h" +#include "startup_stubs/typed_uav_load.h" #include #include @@ -54,8 +56,9 @@ ComPtr store_root(ID3D12Device* device) // Returns 0 when texel (x, y) holds expected and every other texel holds -1.0; otherwise prints the first // differing texel as "texel_mismatch x=.. y=.. expected=.. actual=.." and returns 1. int check_startup_image_store(ID3D12Device* device, const char* vertex_path, const char* pixel_path, UINT x, UINT y, - const std::uint32_t expected[4]) + const std::uint32_t expected[4], unsigned coverage) { + if (coverage != 1 && coverage != 2) throw std::runtime_error("Image store coverage is not 1 or 2"); if (x >= side || y >= side) throw std::runtime_error("Expected a texel inside the 4x4 image"); const auto vs = read_shader(vertex_path); const auto ps = read_shader(pixel_path); @@ -102,7 +105,8 @@ int check_startup_image_store(ID3D12Device* device, const char* vertex_path, con upload->Unmap(0, nullptr); D3D12_RESOURCE_DESC rd = td; - rd.Width = rd.Height = 1; + rd.Width = coverage; + rd.Height = 1; rd.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; const D3D12_CLEAR_VALUE clear{DXGI_FORMAT_R32G32B32A32_FLOAT, {0.0f, 0.0f, 0.0f, 0.0f}}; const auto target = resource(device, rd, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_RENDER_TARGET, &clear); @@ -130,8 +134,8 @@ int check_startup_image_store(ID3D12Device* device, const char* vertex_path, con const std::uint32_t constants[entry_constants] = {0, 0, 0, 0}; // ud0 = 0: plain triangles list->SetGraphicsRoot32BitConstants(0, entry_constants, constants, 0); list->SetGraphicsRootDescriptorTable(1, views->GetGPUDescriptorHandleForHeapStart()); - const D3D12_VIEWPORT viewport{0, 0, 1, 1, 0, 1}; - const D3D12_RECT scissor{0, 0, 1, 1}; + const D3D12_VIEWPORT viewport{0, 0, static_cast(coverage), 1, 0, 1}; + const D3D12_RECT scissor{0, 0, static_cast(coverage), 1}; list->RSSetViewports(1, &viewport); list->RSSetScissorRects(1, &scissor); list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); @@ -164,3 +168,34 @@ int check_startup_image_store(ID3D12Device* device, const char* vertex_path, con if (!result) std::printf("image store: texel (%u, %u) written, %u others untouched\n", x, y, side * side - 1); return result; } + +// Colour formats a pixel UAV may store. None of these is an R32 typed-load format, so a missing +// UAV_TYPED_LOAD bit, or a device without TypedUAVLoadAdditionalFormats, is a real refusal. +// The function does not create a command list and does not draw. +const char* check_startup_image_store_typed_load(ID3D12Device* device) +{ + D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; + const bool options_ok = SUCCEEDED(check_feature(device, D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options))); + const bool additional = options_ok && options.TypedUAVLoadAdditionalFormats; + const DXGI_FORMAT candidates[] = { + DXGI_FORMAT_R11G11B10_FLOAT, DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_R16G16B16A16_UNORM, + DXGI_FORMAT_R16G16B16A16_SNORM, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R32G32_FLOAT, + DXGI_FORMAT_R8G8_UNORM, DXGI_FORMAT_R32G32B32A32_FLOAT, + }; + for (DXGI_FORMAT format : candidates) { + D3D12_FEATURE_DATA_FORMAT_SUPPORT support{format}; + if (FAILED(check_feature(device, D3D12_FEATURE_FORMAT_SUPPORT, &support, sizeof(support)))) continue; + if (typed_uav_load_refusal(format, support.Support2, additional)) { + std::fprintf(stderr, "typed_uav_load_refused format=%d\n", static_cast(format)); + return "typed_uav_load_refused"; + } + } + // Every queried format can load on this device. The same helper must still refuse a cleared + // UAV_TYPED_LOAD bit, and this path still returns before any draw. + if (typed_uav_load_refusal(DXGI_FORMAT_R11G11B10_FLOAT, 0, additional)) { + std::fprintf(stderr, "typed_uav_load_refused format=%d support2=0\n", + static_cast(DXGI_FORMAT_R11G11B10_FLOAT)); + return "typed_uav_load_refused"; + } + return nullptr; +} diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 1641191bd5..8d67f725c7 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -308,7 +308,7 @@ ComPtr translated_pipeline(ID3D12Device* guest, ID3D12RootSignature* r bool needs_start, TableSample sample = TableSample::texture, bool indexed = false, bool rect = false) { // The opaque guest programs identify synthetic cache entries. The actual bound shaders are source-built DXBC. - constexpr char revision[] = "x2w-startup-shader-28"; + constexpr char revision[] = "x2w-startup-shader-29"; static std::uint32_t vertex_ids[]{0xe0000101, 0xe0000102, 0xe0000103}; static std::uint32_t pixel_ids[]{0xe0000202, 0xe0000203, 0xe0000205}; static std::uint32_t indexed_pixel_id = 0xe0000204; diff --git a/tests/startup_manifest_retry_check.cpp b/tests/startup_manifest_retry_check.cpp new file mode 100644 index 0000000000..b3f0acf198 --- /dev/null +++ b/tests/startup_manifest_retry_check.cpp @@ -0,0 +1,75 @@ +// The retry schedule for an absent shader cache manifest (startup_stubs/manifest_retry.h). +// The first look again comes 1 s after the first miss, each further miss doubles the wait, and the wait +// stops growing at 32 s. A found manifest starts the schedule over. +#include "startup_stubs/manifest_retry.h" + +#include + +namespace { + +int failures = 0; + +void expect(bool ok, const char* what) +{ + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +} // namespace + +int main() +{ + using x2w_startup::ManifestRetry; + using x2w_startup::manifest_retry_delay_ms; + + expect(manifest_retry_delay_ms(0) == 1000, "first miss waits 1 s"); + expect(manifest_retry_delay_ms(1) == 2000, "second miss waits 2 s"); + expect(manifest_retry_delay_ms(4) == 16000, "fifth miss waits 16 s"); + expect(manifest_retry_delay_ms(5) == 32000, "sixth miss waits 32 s"); + expect(manifest_retry_delay_ms(6) == 32000, "the wait stops at 32 s"); + expect(manifest_retry_delay_ms(64) == 32000, "a large miss count does not overflow the shift"); + expect(manifest_retry_delay_ms(~0u) == 32000, "the largest miss count stays at 32 s"); + + ManifestRetry retry; + expect(!retry.pending(), "a fresh schedule has no retry pending"); + expect(!retry.due(0) && !retry.due(~0ull), "a fresh schedule is never due"); + + retry.missed(10000); + expect(retry.pending(), "a miss leaves a retry pending"); + expect(!retry.due(10999), "not due before 1 s"); + expect(retry.due(11000), "due at 1 s"); + + retry.missed(11000); + expect(!retry.due(12999) && retry.due(13000), "second miss: due after 2 s"); + + for (int i = 0; i < 20; ++i) retry.missed(100000); + expect(!retry.due(131999) && retry.due(132000), "many misses: due after 32 s"); + + retry.found(); + expect(!retry.pending() && !retry.due(~0ull), "a found manifest clears the retry"); + retry.missed(200000); + expect(!retry.due(200999) && retry.due(201000), "a later miss starts again at 1 s"); + + // One key that never gets a translation: over ten minutes the old fixed 1 s retry looked it up about 600 times; + // the schedule looks it up 23 times (6 lookups in the first 63 s, then one per 32 s). + { + ManifestRetry key; + unsigned lookups = 0; + unsigned long long now = 0; + key.missed(now); + ++lookups; + for (; now <= 600000; now += 50) + if (key.due(now)) { + key.missed(now); + ++lookups; + } + expect(lookups <= 25, "an absent key is looked up at most 25 times in ten minutes"); + expect(lookups >= 20, "an absent key is still looked up at least 20 times in ten minutes"); + } + + if (failures) return 1; + std::printf("startup_manifest_retry: all checks passed\n"); + return 0; +} diff --git a/tests/startup_packed_position_provenance_check.py b/tests/startup_packed_position_provenance_check.py index b68fa1c556..a06abb7b75 100644 --- a/tests/startup_packed_position_provenance_check.py +++ b/tests/startup_packed_position_provenance_check.py @@ -206,7 +206,7 @@ def refused(label, cache, key, reason): cache = Path(tmp) bare = G.pipeline_key(VS_WORDS, ps_words(4), root_blob()) check('without a description the key is unchanged', - bare == G.fnv(root_blob(), G.fnv(ps_words(4), G.fnv(VS_WORDS, G.fnv(b'x2w-startup-shader-28'))))) + bare == G.fnv(root_blob(), G.fnv(ps_words(4), G.fnv(VS_WORDS, G.fnv(b'x2w-startup-shader-29'))))) keys = [put_request(cache, ps_words(4), masks) for masks in (TARGET, SAME_V4, DECOY)] check('same stages, root and layout with three mask pairs: three request identities', len(set(keys)) == 3 and bare not in keys diff --git a/tests/startup_pixel_history.cpp b/tests/startup_pixel_history.cpp index 025cb23fc9..15afa2572d 100644 --- a/tests/startup_pixel_history.cpp +++ b/tests/startup_pixel_history.cpp @@ -114,18 +114,11 @@ Target make_target(IDXGIAdapter* adapter) return target; } -// A fresh target keeps the control independent of the first history: the clear value is the resource's -// initial content, so no extra clear command is needed. -void renew_texture(Target& target) +void clear_target(Target& target, ComputeCommands& commands) { - target.texture.Reset(); - D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; - D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, format, {1, 0}, - D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; - const D3D12_CLEAR_VALUE clear{format, {0, 0, 0, 0}}; - check(target.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_RENDER_TARGET, - &clear, IID_PPV_ARGS(&target.texture)), "renew target"); - target.device->CreateRenderTargetView(target.texture.Get(), nullptr, target.rtv); + check(commands.list->Reset(commands.allocator.Get(), nullptr), "reset clear list"); + commands.list->ClearRenderTargetView(target.rtv, black, 0, nullptr); + commands.submit_and_wait(target.device.Get()); } struct Recorded { @@ -228,6 +221,7 @@ int main(int argc, char** argv) const auto pipeline = make_pipeline(target.device.Get(), root.Get()); ComputeCommands commands(target.device.Get(), pipeline.Get(), D3D12_COMMAND_LIST_TYPE_DIRECT); check(commands.list->Close(), "close initial list"); + clear_target(target, commands); // Three source-built draws: the first and the third only cover the top-left texel, so the second // is the only one that changes the watched texel (1, 1). @@ -257,7 +251,7 @@ int main(int argc, char** argv) bool ok = first_black && second_green && third_green && second_key; // Negative control: without the second draw the watched texel stays black at draw 3. - renew_texture(target); + clear_target(target, commands); std::vector control(2); record_draw(target, commands, root.Get(), pipeline.Get(), red, corner, 1, 0x1111111111111111ull, control[0]); record_draw(target, commands, root.Get(), pipeline.Get(), blue, corner, 3, 0x3333333333333333ull, control[1]); diff --git a/tests/startup_pixel_history_draw_check.py b/tests/startup_pixel_history_draw_check.py index c26e09f79f..71dac37e94 100644 --- a/tests/startup_pixel_history_draw_check.py +++ b/tests/startup_pixel_history_draw_check.py @@ -40,6 +40,8 @@ def check(directory, consumer, backend): base_env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", X2W_SHADER_CACHE=str(cache), X2W_TEST_PIXEL_HISTORY="1") + for name in ("X2W_DRAW_DUMP_PIXEL", "X2W_DRAW_DUMP_FRAME", "X2W_DRAW_DUMP_DIR"): + base_env.pop(name, None) base_env.setdefault("X2W_D3D12_DEBUG", "0") # Publish and translate the green triangle pipeline once, before any draw runs. diff --git a/tests/startup_pixel_image_store_check.py b/tests/startup_pixel_image_store_check.py index d87ead7525..d505024ba2 100644 --- a/tests/startup_pixel_image_store_check.py +++ b/tests/startup_pixel_image_store_check.py @@ -1,14 +1,25 @@ -"""Check gfx2hlsl's pixel-stage image_store on a hand-assembled gfx1013 program (#1996 item F). +"""Check gfx2hlsl's pixel-stage image_store on a hand-assembled gfx1013 program (#1996 item F; M200-01 I). The pixel program loads an image descriptor from descriptor table 0, sets the texel address (1, 2) and four distinct binary32 values, stores them with image_store ... dmask:0xf dim:SQ_RSRC_IMG_2D, and exports the same values to mrt0. The words were assembled by hand from the MIMG layout and are decoded back by tools/disasm_rdna2.py here; --llvm-mc reassembles the source and compares the words. +A full-mask 2D-array program stores the same four values at layer 1. The address is x, y and the +layer, and the manifest line is tex2da. A partial mask on that form is refused. + +A second program uses dmask:0x5 (x and z) so VDATA is two registers. The lowering writes only those +components. It does not read the texel. The UAV starts at -1 in every channel, so y and w stay -1. + +A third program draws two pixels in one pass. Both address texel (1, 2). The pixel at x=0 stores channel +x (dmask:0x1, 1.0) and the pixel at x=1 stores channel z (dmask:0x4, 2.0). Both updates must survive. +Writing the second value into y instead of z is the negative control. + Without arguments: translation controls and refusals. With draw: also compile the translation with DXC and draw it through offscreen_check --startup-image-store, which reads every texel of a 4x4 image back. Negative controls: the translator refuses the program when the lowering is removed, and the translated shader with -its store deleted, or with x and y exchanged, leaves texel (1, 2) at its starting value. +its store deleted, or with x and y exchanged, leaves texel (1, 2) at its starting value. A binding that +asks for a typed UAV load is refused before the draw when the format cannot load. The store runs under the lane's exec bit. Two variants put v_cmpx_eq_u32 before the store, so exec is not known at translation time: with 1 == v0 the lane stays on and the texel is written, with 2 == v0 every lane @@ -45,13 +56,46 @@ s_endpgm """ STORE = bytes.fromhex('080f20f000040400') +# dmask:0x5 → VDATA v[4:5] written to channels x then z (same PREFIX: v4=1.0, v5=2.0). +STORE_XZ = bytes.fromhex('080520f000040400') ARRAY_STORE = bytes.fromhex('280f20f000040400') PREFIX = bytes.fromhex('04040cf4000000fa' '8102007e' '8202027e' 'f202087e' 'f4020a7e' 'ff020c7e00004040' 'f6020e7e' '7fc08cbf') SUFFIX = bytes.fromhex('703f8cbf' '0f1800f804050607' '000081bf') WORDS = PREFIX + STORE + SUFFIX +WORDS_XZ = PREFIX + STORE_XZ + SUFFIX +# Two pixels, one texel. Packed position is v0 (SPI input bit 15). The pixel whose x is 0 stores +# channel x; the pixel whose x is 1 stores channel z. Both write texel (1, 2). +SOURCE_LANES = """\ +v_cmp_eq_u32_e32 0, v0 +v_mov_b32_e32 v2, 1 +v_cndmask_b32_e32 v3, 0, v2 +v_mov_b32_e32 v0, 1 +v_mov_b32_e32 v1, 2 +v_mov_b32_e32 v4, 1.0 +v_mov_b32_e32 v6, 2.0 +s_load_dwordx8 s[16:23], s[8:9], 0x0 +s_waitcnt lgkmcnt(0) +v_cmpx_eq_u32_e32 1, v3 +image_store v4, v[0:1], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D +s_mov_b64 exec, -1 +v_cmpx_eq_u32_e32 0, v3 +image_store v6, v[0:1], s[16:23] dmask:0x4 dim:SQ_RSRC_IMG_2D +s_waitcnt vmcnt(0) +exp mrt0 v4, v4, v6, v6 done vm +s_endpgm +""" +WORDS_LANES = bytes.fromhex( + '8000847d' '8102047e' '80040602' '8102007e' '8202027e' 'f202087e' 'f4020c7e' + '04040cf4000000fa' '7fc08cbf' '8106a47d' '080120f000040400' 'c104febe' '8006a47d' + '080420f000060400' '703f8cbf' '0f1800f804040606' '000081bf') +LANE_X = 'if (exec & 1) w0[uint2(v0, v1)].x = asfloat(v4);' +LANE_Z = 'if (exec & 1) w0[uint2(v0, v1)].z = asfloat(v6);' STORE_LINE = 'w0[uint2(v0, v1)] = asfloat(uint4(v4, v5, v6, v7));' +# Init -1: an xz component store leaves the texel at (1.0, -1.0, 2.0, -1.0). No texel read. +SPARSE_LINE = 'w0[uint2(v0, v1)].xz = float2(asfloat(v4), asfloat(v5));' GUARDED_LINE = 'if (exec & 1) ' + STORE_LINE +SPARSE_BITS = ['3f800000', 'bf800000', '40000000', 'bf800000'] # 1.0, -1.0, 2.0, -1.0 ARRAY_SOURCE = SOURCE.replace( 'image_store v[4:7], v[0:1], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D', 'v_mov_b32 v2, 1\nimage_store v[4:7], v[0:2], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY', @@ -89,6 +133,11 @@ def translate(words): return G.Pipeline(VS_WORDS, words, root_blob()) +def translate_lanes(words): + # SPI_PS_INPUT bit 15 alone: the packed position occupies v0. + return G.Pipeline(VS_WORDS, words, root_blob(), ps_hw_inputs=(0x8000, 0x8000)) + + def refused(words, *needles): try: translate(words) @@ -141,7 +190,7 @@ def controls(): print('array store: %s manifest uav 0 tex2da table 0 0' % ARRAY_STORE_LINE) # Refusals, each by name: packed data or addresses, fault-status returns, a 128-bit descriptor, - # a partial channel mask and other image dimensions. + # and other image dimensions. cases = (('d16', patched(7, 0x80)), ('a16', patched(7, 0x40)), ('tfe', patched(2, 0x01)), ('lwe', patched(2, 0x02)), ('r128', patched(1, 0x80)), ('reserved', patched(1, 0x40)), ('SQ_RSRC_IMG_3D', bytes.fromhex('100f20f000040400')), @@ -152,7 +201,7 @@ def controls(): message = refused(with_store(store), 'image_store') print('refused %-20s %s' % (name + ':', message)) assert decoded.startswith('image_store'), decoded - # 2D-array requires three address registers and still refuses pixel d16. + # 2D-array requires three address registers, a full mask, and still refuses pixel d16. try: array_pipe.ps.op_image_store(['v[4:7]', 'v[0:1]', 's[16:23]'], ['dmask:0xf', 'dim:SQ_RSRC_IMG_2D_ARRAY']) except G.Unsupported as error: @@ -165,23 +214,52 @@ def controls(): assert 'modifier d16' in str(error), error else: raise AssertionError('pixel 2D-array d16 store was accepted') - print('refused 2D-array with two address registers and pixel d16') - # A partial channel mask, encoded: the decoder sizes VDATA from the mask (v[4:6], v4), so each must be - # refused for the mask itself, which the translator checks before the data registers. - for mask, data in ((0x7, 'v[4:6]'), (0x1, 'v4')): + try: + array_pipe.ps.op_image_store(['v[4:5]', 'v[0:2]', 's[16:23]'], ['dmask:0x5', 'dim:SQ_RSRC_IMG_2D_ARRAY']) + except G.Unsupported as error: + assert 'writes all four channels' in str(error), error + else: + raise AssertionError('2D-array sparse dmask was accepted') + print('refused 2D-array with two address registers, pixel d16 and sparse dmask 0x5') + # Sparse DMASK on a pixel 2D store: selected components only, in VDATA order. The UAV starts at + # -1; dmask:0x5 with v[4:5] = (1.0, 2.0) yields (1, -1, 2, -1) without reading the texel. + decoded_xz = D.decode_instruction(STORE_XZ, 0)[2] + assert decoded_xz == 'image_store v[4:5], v[0:1], s[16:23] dmask:0x5 dim:SQ_RSRC_IMG_2D', decoded_xz + sparse_ps = translate(WORDS_XZ).hlsl_ps() + assert ' ' + SPARSE_LINE in sparse_ps, sparse_ps + assert 't = w0[' not in sparse_ps, sparse_ps + assert 'typedload' not in translate(WORDS_XZ).manifest() + print('sparse dmask 0x5: %s' % SPARSE_LINE) + partial = { + 0x7: 'w0[uint2(v0, v1)].xyz = float3(asfloat(v4), asfloat(v5), asfloat(v6));', + 0x1: 'w0[uint2(v0, v1)].x = asfloat(v4);', + 0x3: 'w0[uint2(v0, v1)].xy = float2(asfloat(v4), asfloat(v5));', + } + for mask, data, count in ((0x7, 'v[4:6]', 3), (0x1, 'v4', 1), (0x3, 'v[4:5]', 2)): store = patched(1, 0, mask) decoded = D.decode_instruction(store, 0)[2] assert decoded.startswith('image_store %s, ' % data) and 'dmask:%#x' % mask in decoded, decoded - message = refused(with_store(store), 'dmask %#x' % mask, 'writes all four channels') - print('refused %-20s %s' % ('dmask %#x:' % mask, message)) - # The same partial mask with four data registers, through the handler: only the mask guard can refuse it. + text = translate(with_store(store)).hlsl_ps() + assert ' ' + partial[mask] in text, (mask, text) + assert 't = w0[' not in text, text + print('sparse dmask %#x accepted (%d channel(s))' % (mask, count)) + # Wrong VGPR count for a sparse mask is refused for the data, not the mask. try: - pipe.ps.op_image_store(['v[4:7]', 'v[0:1]', 's[16:23]'], ['dmask:0x7', 'dim:SQ_RSRC_IMG_2D']) + pipe.ps.op_image_store(['v[4:7]', 'v[0:1]', 's[16:23]'], ['dmask:0x5', 'dim:SQ_RSRC_IMG_2D']) except G.Unsupported as error: - assert 'dmask 0x7' in str(error) and 'writes all four channels' in str(error), error + assert '2 VGPRs expected' in str(error), error else: - raise AssertionError('a partial dmask with four data registers was accepted') - print('refused dmask 0x7 with four data registers (v[4:7])') + raise AssertionError('dmask 0x5 with four data registers was accepted') + print('refused dmask 0x5 with four data registers (v[4:7])') + # Empty and out-of-range masks still refuse like a full-channel typed store. + for bad in (0x0, 0x10): + try: + pipe.ps.op_image_store(['v4', 'v[0:1]', 's[16:23]'], ['dmask:%#x' % bad, 'dim:SQ_RSRC_IMG_2D']) + except G.Unsupported as error: + assert 'writes all four channels' in str(error), error + else: + raise AssertionError('dmask %#x was accepted' % bad) + print('refused dmask 0x0 and 0x10') # Four data registers are required for the full mask: three are refused for the data, not the mask. try: pipe.ps.op_image_store(['v[4:6]', 'v[0:1]', 's[16:23]'], ['dmask:0xf', 'dim:SQ_RSRC_IMG_2D']) @@ -190,6 +268,17 @@ def controls(): else: raise AssertionError('dmask 0xf with three data registers was accepted') print('refused dmask 0xf with three data registers (v[4:6])') + # Compute still requires the full mask (shared handler; pixel-only sparse). + try: + pipe.ps.kind = 'cs' + pipe.ps.op_image_store(['v[4:5]', 'v[0:1]', 's[16:23]'], ['dmask:0x5', 'dim:SQ_RSRC_IMG_2D']) + except G.Unsupported as error: + assert 'writes all four channels' in str(error), error + else: + raise AssertionError('compute sparse dmask was accepted') + finally: + pipe.ps.kind = 'ps' + print('refused compute-stage sparse dmask 0x5') # Mask text that is not an integer is a named refusal, not a ValueError. try: pipe.ps.op_image_store(['v[4:7]', 'v[0:1]', 's[16:23]'], ['dmask:0xz', 'dim:SQ_RSRC_IMG_2D']) @@ -233,6 +322,29 @@ def controls(): assert ARRAY_GUARDED_LINE not in array_ps print('exec after v_cmpx: %s' % GUARDED_LINE) + # Same texel, disjoint masks: two invocations write x and z, and neither store reads the texel. + lanes = translate_lanes(WORDS_LANES).hlsl_ps() + assert 'v0 = (uint(i.pos.x) & 0xffffu) | ((uint(i.pos.y) & 0xffffu) << 16);' in lanes, lanes + assert ' ' + LANE_X in lanes and ' ' + LANE_Z in lanes, lanes + assert 't = w0[' not in lanes and 'typedload' not in translate_lanes(WORDS_LANES).manifest(), lanes + swapped = lanes.replace(LANE_Z, LANE_Z.replace('.z = asfloat(v6)', '.y = asfloat(v6)')) + assert swapped != lanes and '.z = asfloat(v6)' not in swapped + print('same texel: %s and %s' % (LANE_X, LANE_Z)) + print('control: swapping the z store onto y changes the lowering') + + # A binding that asks for a typed load is refused in pixel_uav_view, before the view is filled. + # The translator does not emit that request for a component store. + draw_inl = (HERE.parent / 'src/startup_stubs/d3d12_draw.inl').read_text(encoding='utf-8') + view = draw_inl.split('const char* pixel_uav_view', 1)[1].split('\nstruct Translation', 1)[0] + assert 'needs_typed_load' in view and 'typed_uav_load_refusal' in view and 'bool array' in view, view + assert view.find('typed_uav_load_refusal') < view.find('out.Format = format'), view + parser = draw_inl.split('const char* read_pixel_uav_line', 1)[1].split('\nbool float_uav_format', 1)[0] + assert 'typedload' in parser and 'needs_typed_load' in parser and 'tex2da' in parser, parser + store_cpp = (HERE / 'startup_image_store.cpp').read_text(encoding='utf-8') + gate = store_cpp.split('check_startup_image_store_typed_load', 1)[1] + assert 'DrawInstanced' not in gate and 'typed_uav_load_refusal' in gate, gate + print('typed UAV load is refused before the view is filled and before any draw') + # Negative control: without the lowering the program is refused as before. lowering = G.Stage.op_image_store del G.Stage.op_image_store @@ -244,10 +356,13 @@ def controls(): def check_binary(llvm_mc): - for label, src, expected in (('2d', SOURCE, WORDS), ('2d_array', ARRAY_SOURCE, ARRAY_WORDS)): - built = assemble(llvm_mc, src) - if built != expected: - raise AssertionError('%s: assembled %s, recorded %s' % (label, built.hex(), expected.hex())) + for name, source, words in ( + ('full mask', SOURCE, WORDS), + ('2d array', ARRAY_SOURCE, ARRAY_WORDS), + ('same texel', SOURCE_LANES, WORDS_LANES)): + built = assemble(llvm_mc, source) + if built != words: + raise AssertionError('%s fixture: assembled %s, recorded %s' % (name, built.hex(), words.hex())) print('fixture words match llvm-mc') @@ -263,10 +378,12 @@ def check_draw(dxc, renderer, adapter): directory = Path(tmp) vs = compile_hlsl(dxc, 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', directory) - def draw(text, label, want=expected): + def draw(text, label, want=expected, coverage=None): ps = compile_hlsl(dxc, 'dxc', text, label, 'ps_6_0', directory) - return subprocess.run([renderer, adapter, '--startup-image-store', str(vs), str(ps), '1,2', want], - capture_output=True, text=True) + command = [renderer, adapter, '--startup-image-store', str(vs), str(ps), '1,2', want] + if coverage is not None: + command.append(str(coverage)) + return subprocess.run(command, capture_output=True, text=True) run = draw(source, 'store') sys.stdout.write(run.stdout) @@ -302,6 +419,52 @@ def draw(text, label, want=expected): raise AssertionError('control exec guard removed was not detected\n%s\n%s' % (run.stdout, run.stderr)) print('control exec guard removed: fails as expected (%s)' % mismatch_line(run.stderr)) + # Sparse dmask 0x5: only x and z change; y and w stay at the UAV clear (-1.0). + sparse_want = ','.join(SPARSE_BITS) + sparse_source = translate(WORDS_XZ).hlsl_ps() + assert SPARSE_LINE in sparse_source, sparse_source + run = draw(sparse_source, 'store_xz', sparse_want) + if run.returncode: + raise AssertionError('sparse store draw failed\n%s\n%s' % (run.stdout, run.stderr)) + print('draw sparse dmask 0x5: texel (1, 2) = %s' % sparse_want) + # Control: writing all four channels instead of the selected components must mismatch on y and w. + full_instead = sparse_source.replace(SPARSE_LINE, STORE_LINE) + assert full_instead != sparse_source + run = draw(full_instead, 'sparse_as_full', sparse_want) + needle = 'texel_mismatch x=1 y=2 expected=%s actual=%s' % (sparse_want, expected) + if run.returncode == 0 or needle not in run.stderr: + raise AssertionError('control sparse-as-full was not detected\n%s\n%s' % (run.stdout, run.stderr)) + print('control sparse-as-full: fails as expected (%s)' % mismatch_line(run.stderr)) + + # Two invocations, one draw, one texel, disjoint masks. Both component writes must survive. + lanes = translate_lanes(WORDS_LANES).hlsl_ps() + assert LANE_X in lanes and LANE_Z in lanes, lanes + assert 't = w0[' not in lanes, lanes + run = draw(lanes, 'same_texel', sparse_want, coverage=2) + if run.returncode: + raise AssertionError('same-texel draw failed\n%s\n%s' % (run.stdout, run.stderr)) + print('draw same texel disjoint masks: texel (1, 2) = %s' % sparse_want) + # Negative control: the z store written into y must mismatch. + swapped = lanes.replace(LANE_Z, LANE_Z.replace('.z = asfloat(v6)', '.y = asfloat(v6)')) + assert swapped != lanes and '.z = asfloat(v6)' not in swapped + run = draw(swapped, 'same_texel_y', sparse_want, coverage=2) + swapped_actual = '3f800000,40000000,bf800000,bf800000' # (1, 2, -1, -1) + needle = 'texel_mismatch x=1 y=2 expected=%s actual=%s' % (sparse_want, swapped_actual) + if run.returncode == 0 or needle not in run.stderr: + raise AssertionError('control same-texel channel swap was not detected\n%s\n%s' % (run.stdout, run.stderr)) + print('control same-texel channel swap: fails as expected (%s)' % mismatch_line(run.stderr)) + + refused_load = subprocess.run([renderer, adapter, '--startup-image-store-reject-load'], + capture_output=True, text=True) + if refused_load.returncode == 77: + sys.exit(77) + if refused_load.returncode == 0 or 'typed_uav_load_refused' not in refused_load.stderr: + raise AssertionError('typed UAV load was not refused before the draw\n%s\n%s' % ( + refused_load.stdout, refused_load.stderr)) + if 'image store:' in refused_load.stdout: + raise AssertionError('typed UAV load refusal drew\n%s' % refused_load.stdout) + print('typed UAV load refused before the draw') + def main(): controls() diff --git a/tests/startup_present_readback_check.cpp b/tests/startup_present_readback_check.cpp new file mode 100644 index 0000000000..2e18d31939 --- /dev/null +++ b/tests/startup_present_readback_check.cpp @@ -0,0 +1,89 @@ +#include "startup_stubs/present_readback_state.h" + +#include +#include + +namespace { +using x2w_startup::FenceCompletion; +using x2w_startup::PresentReadbackState; +using x2w_startup::fence_completion; + +void require(bool ok, const char* message) +{ + if (!ok) { + std::fprintf(stderr, "%s\n", message); + std::exit(1); + } +} +} + +int main() +{ + PresentReadbackState state; + require(!state.pending() && !state.unusable(), "initial readback not reusable"); + state.submitted(7); + require(state.pending(), "submission not retained"); + require(state.observe(6) == FenceCompletion::pending && state.pending(), + "premature completion would release the submitted surface"); + require(state.observe(7) == FenceCompletion::completed && !state.pending() && !state.unusable(), + "completed submission did not allow reuse"); + state.submitted(8); + require(state.observe(7) == FenceCompletion::pending && state.pending(), + "stale event would publish a later submission"); + require(state.observe(9) == FenceCompletion::completed && !state.pending(), + "past-target completion did not settle submission"); + state.submitted(10); + require(state.observe(UINT64_MAX) == FenceCompletion::removed && state.unusable(), + "device removal would publish or allow reuse"); + + PresentReadbackState failed; + failed.signal_failed(); + require(failed.unusable(), "failed signal would allow reuse"); + require(fence_completion(UINT64_MAX - 1, UINT64_MAX - 1) == FenceCompletion::completed, + "highest usable fence value rejected"); + require(fence_completion(UINT64_MAX, UINT64_MAX) == FenceCompletion::removed, + "reserved fence value accepted as completion"); + + // Ownership disposition: retire() must release the held references exactly once, only for a + // confirmed completion, never while pending or removed, and a drain registered for one + // submission must not retire a different pending target. + { + int released = 0; + const auto release = [&] { ++released; }; + PresentReadbackState retired; + require(retired.retire(5, release) == FenceCompletion::completed && released == 0, + "a never-submitted state has no ownership to release"); + retired.submitted(20); + require(retired.retire(19, release) == FenceCompletion::pending && released == 0 && retired.pending(), + "a pending fence would retire ownership"); + require(retired.retire(20, release) == FenceCompletion::completed && released == 1 && !retired.pending(), + "a completed fence did not retire ownership"); + require(retired.retire(20, release) == FenceCompletion::completed && released == 1, + "a second completed observation retired ownership again"); + retired.submitted(21); + require(retired.retire(UINT64_MAX, release) == FenceCompletion::removed && released == 1 && retired.unusable(), + "device removal retired ownership"); + require(retired.retire(21, release) == FenceCompletion::removed && released == 1, + "an unusable state retired ownership"); + } + { + int released = 0; + PresentReadbackState drained; + drained.submitted(30); + // The drain was registered for 29; the fence completed but the pending target is a later + // submission, so the drain must not release it. + require(drained.retire(30, [&] { ++released; }, 29) == FenceCompletion::completed && released == 0 && drained.pending(), + "a drain retired a submission it was not registered for"); + // The drain for the current target releases it exactly once. + require(drained.retire(30, [&] { ++released; }, 30) == FenceCompletion::completed && released == 1 && !drained.pending(), + "a drain for the current target did not retire ownership"); + // A drain registered for the settled submission observes completed without releasing again. + drained.submitted(31); + // Completed fence value, but the drain is for the settled earlier submission: it must + // not release or settle the later target it does not own. + require(drained.retire(31, [&] { ++released; }, 30) == FenceCompletion::completed && released == 1 && drained.pending(), + "a stale drain retired or settled a later submission"); + } + std::puts("present readback: pending, stale event, completion, failed signal, removal and " + "ownership retirement controls passed"); +} diff --git a/tests/startup_present_signature.cpp b/tests/startup_present_signature.cpp index 316db9d9a4..09cc4ded72 100644 --- a/tests/startup_present_signature.cpp +++ b/tests/startup_present_signature.cpp @@ -183,11 +183,60 @@ std::vector present_all(Gpu& gpu, x2w_present_s return published; } +// Forwards every call to a real fence, except that GetCompletedValue reports UINT64_MAX once +// `removed` is set: the device-removal case the sampler has to survive without treating it as +// completion. Signal and SetEventOnCompletion still succeed, as they do while a device is being +// removed. For the destructor controls, `pending_observations`/`next` make each successive +// GetCompletedValue report a chosen value a fixed number of times and then the real fence's own +// value, so a transition across the destructor's wait is deterministic: the pre-wait +// observation sees pending, the wait runs on the real fence, the post-wait observation sees the +// completed (or, with `removed`, the removal sentinel) state. The real fence is the only object +// the driver ever sees. +class RemovedFence : public ID3D12Fence { +public: + explicit RemovedFence(ID3D12Fence* real) : real_(real) {} + bool removed = false; + UINT64 pending_observations = 0; // report `next` this many times, then the real value + UINT64 next = 0; + unsigned observations = 0; // GetCompletedValue calls since construction + unsigned event_registrations = 0; + ID3D12Fence* real() const { return real_; } + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { return real_ ? real_->QueryInterface(riid, out) : E_FAIL; } + ULONG STDMETHODCALLTYPE AddRef() override { return real_ ? real_->AddRef() : 0; } + ULONG STDMETHODCALLTYPE Release() override { return real_ ? real_->Release() : 0; } + HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID g, UINT* n, void* d) override { return real_ ? real_->GetPrivateData(g, n, d) : E_FAIL; } + HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID g, UINT n, const void* d) override { return real_ ? real_->SetPrivateData(g, n, d) : E_FAIL; } + HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID g, const IUnknown* d) override { return real_ ? real_->SetPrivateDataInterface(g, d) : E_FAIL; } + HRESULT STDMETHODCALLTYPE SetName(LPCWSTR name) override { return real_ ? real_->SetName(name) : E_FAIL; } + HRESULT STDMETHODCALLTYPE GetDevice(REFIID riid, void** out) override { return real_ ? real_->GetDevice(riid, out) : E_FAIL; } + UINT64 STDMETHODCALLTYPE GetCompletedValue() override + { + ++observations; + if (pending_observations) { + --pending_observations; + return next; + } + if (removed) return UINT64_MAX; + return real_ ? real_->GetCompletedValue() : 0; + } + HRESULT STDMETHODCALLTYPE SetEventOnCompletion(UINT64 value, HANDLE event) override + { + ++event_registrations; + return real_ ? real_->SetEventOnCompletion(value, event) : E_FAIL; + } + HRESULT STDMETHODCALLTYPE Signal(UINT64 value) override { return real_ ? real_->Signal(value) : E_FAIL; } + +private: + ID3D12Fence* real_; +}; // Forwards every call to a real queue, except that Signal fails once `fail_signal` is set: the -// "submitted, but no fence" case the sampler has to survive. +// "submitted, but no fence" case the sampler has to survive. With `observed`, Signal and Wait +// unwrap exactly our RemovedFence to its real fence, so a test fake never enters the driver. + class SignalFailingQueue : public ID3D12CommandQueue { public: - explicit SignalFailingQueue(ID3D12CommandQueue* real) : real_(real) {} + explicit SignalFailingQueue(ID3D12CommandQueue* real, RemovedFence* observed = nullptr) + : real_(real), observed_(observed) {} bool fail_signal = false; HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { return real_->QueryInterface(riid, out); } ULONG STDMETHODCALLTYPE AddRef() override { return 2; } @@ -213,8 +262,17 @@ class SignalFailingQueue : public ID3D12CommandQueue { void STDMETHODCALLTYPE SetMarker(UINT m, const void* d, UINT n) override { real_->SetMarker(m, d, n); } void STDMETHODCALLTYPE BeginEvent(UINT m, const void* d, UINT n) override { real_->BeginEvent(m, d, n); } void STDMETHODCALLTYPE EndEvent() override { real_->EndEvent(); } - HRESULT STDMETHODCALLTYPE Signal(ID3D12Fence* fence, UINT64 value) override { return fail_signal ? E_FAIL : real_->Signal(fence, value); } - HRESULT STDMETHODCALLTYPE Wait(ID3D12Fence* fence, UINT64 value) override { return real_->Wait(fence, value); } + HRESULT STDMETHODCALLTYPE Signal(ID3D12Fence* fence, UINT64 value) override + { + if (fail_signal) return E_FAIL; + // A test fake never enters the driver: unwrap exactly our RemovedFence to its real fence. + if (observed_ && fence == observed_) fence = observed_->real(); + return real_->Signal(fence, value); + } + HRESULT STDMETHODCALLTYPE Wait(ID3D12Fence* fence, UINT64 value) override + { + return real_->Wait(observed_ && fence == observed_ ? observed_->real() : fence, value); + } HRESULT STDMETHODCALLTYPE GetTimestampFrequency(UINT64* f) override { return real_->GetTimestampFrequency(f); } HRESULT STDMETHODCALLTYPE GetClockCalibration(UINT64* g, UINT64* c) override { return real_->GetClockCalibration(g, c); } #if defined(_MSC_VER) || !defined(_WIN32) @@ -225,8 +283,87 @@ class SignalFailingQueue : public ID3D12CommandQueue { private: ID3D12CommandQueue* real_; + RemovedFence* observed_; }; +// Forwards every ID3D12Device method to a real device, except that CreateFence returns the +// RemovedFence above, so the fixture controls what GetCompletedValue reports. +class RemovalDevice : public ID3D12Device { +public: + explicit RemovalDevice(ID3D12Device* real) : real_(real) {} + RemovedFence& fence() { return fence_; } + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { return real_->QueryInterface(riid, out); } + ULONG STDMETHODCALLTYPE AddRef() override { return 2; } + ULONG STDMETHODCALLTYPE Release() override { return 1; } + HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID g, UINT* n, void* d) override { return real_->GetPrivateData(g, n, d); } + HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID g, UINT n, const void* d) override { return real_->SetPrivateData(g, n, d); } + HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID g, const IUnknown* d) override { return real_->SetPrivateDataInterface(g, d); } + HRESULT STDMETHODCALLTYPE SetName(LPCWSTR name) override { return real_->SetName(name); } + // clang-format off + UINT STDMETHODCALLTYPE GetNodeCount() override { return real_->GetNodeCount(); } + HRESULT STDMETHODCALLTYPE CreateCommandQueue(const D3D12_COMMAND_QUEUE_DESC *desc, REFIID riid, void **command_queue) override { return real_->CreateCommandQueue(desc, riid, command_queue); } + HRESULT STDMETHODCALLTYPE CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE type, REFIID riid, void **command_allocator) override { return real_->CreateCommandAllocator(type, riid, command_allocator); } + HRESULT STDMETHODCALLTYPE CreateGraphicsPipelineState(const D3D12_GRAPHICS_PIPELINE_STATE_DESC *desc, REFIID riid, void **pipeline_state) override { return real_->CreateGraphicsPipelineState(desc, riid, pipeline_state); } + HRESULT STDMETHODCALLTYPE CreateComputePipelineState(const D3D12_COMPUTE_PIPELINE_STATE_DESC *desc, REFIID riid, void **pipeline_state) override { return real_->CreateComputePipelineState(desc, riid, pipeline_state); } + HRESULT STDMETHODCALLTYPE CreateCommandList(UINT node_mask, D3D12_COMMAND_LIST_TYPE type, ID3D12CommandAllocator *command_allocator, ID3D12PipelineState *initial_pipeline_state, REFIID riid, void **command_list) override { return real_->CreateCommandList(node_mask, type, command_allocator, initial_pipeline_state, riid, command_list); } + HRESULT STDMETHODCALLTYPE CheckFeatureSupport(D3D12_FEATURE feature, void *feature_data, UINT feature_data_size) override { return real_->CheckFeatureSupport(feature, feature_data, feature_data_size); } + HRESULT STDMETHODCALLTYPE CreateDescriptorHeap(const D3D12_DESCRIPTOR_HEAP_DESC *desc, REFIID riid, void **descriptor_heap) override { return real_->CreateDescriptorHeap(desc, riid, descriptor_heap); } + UINT STDMETHODCALLTYPE GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE descriptor_heap_type) override { return real_->GetDescriptorHandleIncrementSize(descriptor_heap_type); } + HRESULT STDMETHODCALLTYPE CreateRootSignature(UINT node_mask, const void *bytecode, SIZE_T bytecode_length, REFIID riid, void **root_signature) override { return real_->CreateRootSignature(node_mask, bytecode, bytecode_length, riid, root_signature); } + void STDMETHODCALLTYPE CreateConstantBufferView(const D3D12_CONSTANT_BUFFER_VIEW_DESC *desc, D3D12_CPU_DESCRIPTOR_HANDLE descriptor) override { real_->CreateConstantBufferView(desc, descriptor); } + void STDMETHODCALLTYPE CreateShaderResourceView(ID3D12Resource *resource, const D3D12_SHADER_RESOURCE_VIEW_DESC *desc, D3D12_CPU_DESCRIPTOR_HANDLE descriptor) override { real_->CreateShaderResourceView(resource, desc, descriptor); } + void STDMETHODCALLTYPE CreateUnorderedAccessView(ID3D12Resource *resource, ID3D12Resource *counter_resource, const D3D12_UNORDERED_ACCESS_VIEW_DESC *desc, D3D12_CPU_DESCRIPTOR_HANDLE descriptor) override { real_->CreateUnorderedAccessView(resource, counter_resource, desc, descriptor); } + void STDMETHODCALLTYPE CreateRenderTargetView(ID3D12Resource *resource, const D3D12_RENDER_TARGET_VIEW_DESC *desc, D3D12_CPU_DESCRIPTOR_HANDLE descriptor) override { real_->CreateRenderTargetView(resource, desc, descriptor); } + void STDMETHODCALLTYPE CreateDepthStencilView(ID3D12Resource *resource, const D3D12_DEPTH_STENCIL_VIEW_DESC *desc, D3D12_CPU_DESCRIPTOR_HANDLE descriptor) override { real_->CreateDepthStencilView(resource, desc, descriptor); } + void STDMETHODCALLTYPE CreateSampler(const D3D12_SAMPLER_DESC *desc, D3D12_CPU_DESCRIPTOR_HANDLE descriptor) override { real_->CreateSampler(desc, descriptor); } + void STDMETHODCALLTYPE CopyDescriptors(UINT dst_descriptor_range_count, const D3D12_CPU_DESCRIPTOR_HANDLE *dst_descriptor_range_offsets, const UINT *dst_descriptor_range_sizes, UINT src_descriptor_range_count, const D3D12_CPU_DESCRIPTOR_HANDLE *src_descriptor_range_offsets, const UINT *src_descriptor_range_sizes, D3D12_DESCRIPTOR_HEAP_TYPE descriptor_heap_type) override { real_->CopyDescriptors(dst_descriptor_range_count, dst_descriptor_range_offsets, dst_descriptor_range_sizes, src_descriptor_range_count, src_descriptor_range_offsets, src_descriptor_range_sizes, descriptor_heap_type); } + void STDMETHODCALLTYPE CopyDescriptorsSimple(UINT descriptor_count, const D3D12_CPU_DESCRIPTOR_HANDLE dst_descriptor_range_offset, const D3D12_CPU_DESCRIPTOR_HANDLE src_descriptor_range_offset, D3D12_DESCRIPTOR_HEAP_TYPE descriptor_heap_type) override { real_->CopyDescriptorsSimple(descriptor_count, dst_descriptor_range_offset, src_descriptor_range_offset, descriptor_heap_type); } +#ifdef WIDL_EXPLICIT_AGGREGATE_RETURNS + D3D12_RESOURCE_ALLOCATION_INFO* STDMETHODCALLTYPE GetResourceAllocationInfo(D3D12_RESOURCE_ALLOCATION_INFO* out, UINT visible_mask, UINT reource_desc_count, const D3D12_RESOURCE_DESC *resource_descs) override { return real_->GetResourceAllocationInfo(out, visible_mask, reource_desc_count, resource_descs); } + D3D12_HEAP_PROPERTIES* STDMETHODCALLTYPE GetCustomHeapProperties(D3D12_HEAP_PROPERTIES* out, UINT node_mask, D3D12_HEAP_TYPE heap_type) override { return real_->GetCustomHeapProperties(out, node_mask, heap_type); } +#else + D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo(UINT visible_mask, UINT reource_desc_count, const D3D12_RESOURCE_DESC *resource_descs) override { return real_->GetResourceAllocationInfo(visible_mask, reource_desc_count, resource_descs); } + D3D12_HEAP_PROPERTIES STDMETHODCALLTYPE GetCustomHeapProperties(UINT node_mask, D3D12_HEAP_TYPE heap_type) override { return real_->GetCustomHeapProperties(node_mask, heap_type); } +#endif + HRESULT STDMETHODCALLTYPE CreateCommittedResource(const D3D12_HEAP_PROPERTIES *heap_properties, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC *desc, D3D12_RESOURCE_STATES initial_state, const D3D12_CLEAR_VALUE *optimized_clear_value, REFIID riid, void **resource) override { return real_->CreateCommittedResource(heap_properties, heap_flags, desc, initial_state, optimized_clear_value, riid, resource); } + HRESULT STDMETHODCALLTYPE CreateHeap(const D3D12_HEAP_DESC *desc, REFIID riid, void **heap) override { return real_->CreateHeap(desc, riid, heap); } + HRESULT STDMETHODCALLTYPE CreatePlacedResource(ID3D12Heap *heap, UINT64 heap_offset, const D3D12_RESOURCE_DESC *desc, D3D12_RESOURCE_STATES initial_state, const D3D12_CLEAR_VALUE *optimized_clear_value, REFIID riid, void **resource) override { return real_->CreatePlacedResource(heap, heap_offset, desc, initial_state, optimized_clear_value, riid, resource); } + HRESULT STDMETHODCALLTYPE CreateReservedResource(const D3D12_RESOURCE_DESC *desc, D3D12_RESOURCE_STATES initial_state, const D3D12_CLEAR_VALUE *optimized_clear_value, REFIID riid, void **resource) override { return real_->CreateReservedResource(desc, initial_state, optimized_clear_value, riid, resource); } + HRESULT STDMETHODCALLTYPE CreateSharedHandle(ID3D12DeviceChild *object, const SECURITY_ATTRIBUTES *attributes, DWORD access, const WCHAR *name, HANDLE *handle) override { return real_->CreateSharedHandle(object, attributes, access, name, handle); } + HRESULT STDMETHODCALLTYPE OpenSharedHandle(HANDLE handle, REFIID riid, void **object) override { return real_->OpenSharedHandle(handle, riid, object); } + HRESULT STDMETHODCALLTYPE OpenSharedHandleByName(const WCHAR *name, DWORD access, HANDLE *handle) override { return real_->OpenSharedHandleByName(name, access, handle); } + HRESULT STDMETHODCALLTYPE MakeResident(UINT object_count, ID3D12Pageable *const *objects) override { return real_->MakeResident(object_count, objects); } + HRESULT STDMETHODCALLTYPE Evict(UINT object_count, ID3D12Pageable *const *objects) override { return real_->Evict(object_count, objects); } + HRESULT STDMETHODCALLTYPE CreateFence(UINT64 initial_value, D3D12_FENCE_FLAGS flags, REFIID riid, void **fence) override + { + if (riid != __uuidof(ID3D12Fence)) return E_NOINTERFACE; + ID3D12Fence* real_fence = nullptr; + const HRESULT hr = real_->CreateFence(initial_value, flags, IID_PPV_ARGS(&real_fence)); + if (SUCCEEDED(hr)) { + fence_ = RemovedFence(real_fence); + *fence = static_cast(&fence_); + } + return hr; + } + HRESULT STDMETHODCALLTYPE GetDeviceRemovedReason() override { return real_->GetDeviceRemovedReason(); } + void STDMETHODCALLTYPE GetCopyableFootprints(const D3D12_RESOURCE_DESC *desc, UINT first_sub_resource, UINT sub_resource_count, UINT64 base_offset, D3D12_PLACED_SUBRESOURCE_FOOTPRINT *layouts, UINT *row_count, UINT64 *row_size, UINT64 *total_bytes) override { real_->GetCopyableFootprints(desc, first_sub_resource, sub_resource_count, base_offset, layouts, row_count, row_size, total_bytes); } + HRESULT STDMETHODCALLTYPE CreateQueryHeap(const D3D12_QUERY_HEAP_DESC *desc, REFIID riid, void **heap) override { return real_->CreateQueryHeap(desc, riid, heap); } + HRESULT STDMETHODCALLTYPE SetStablePowerState(BOOL enable) override { return real_->SetStablePowerState(enable); } + HRESULT STDMETHODCALLTYPE CreateCommandSignature(const D3D12_COMMAND_SIGNATURE_DESC *desc, ID3D12RootSignature *root_signature, REFIID riid, void **command_signature) override { return real_->CreateCommandSignature(desc, root_signature, riid, command_signature); } + void STDMETHODCALLTYPE GetResourceTiling(ID3D12Resource *resource, UINT *total_tile_count, D3D12_PACKED_MIP_INFO *packed_mip_info, D3D12_TILE_SHAPE *standard_tile_shape, UINT *sub_resource_tiling_count, UINT first_sub_resource_tiling, D3D12_SUBRESOURCE_TILING *sub_resource_tilings) override { real_->GetResourceTiling(resource, total_tile_count, packed_mip_info, standard_tile_shape, sub_resource_tiling_count, first_sub_resource_tiling, sub_resource_tilings); } +#ifdef WIDL_EXPLICIT_AGGREGATE_RETURNS + LUID* STDMETHODCALLTYPE GetAdapterLuid(LUID* out) override { return real_->GetAdapterLuid(out); } +#else + LUID STDMETHODCALLTYPE GetAdapterLuid() override { return real_->GetAdapterLuid(); } +#endif + // clang-format on + +private: + ID3D12Device* real_; + RemovedFence fence_{nullptr}; +}; + + // Error and corruption messages the debug layer has stored since the last call; prints each one. // `deleted_in_use` is set when one of them reports an object released while the GPU still used it. int debug_errors(ID3D12InfoQueue* info, bool* deleted_in_use = nullptr) @@ -349,6 +486,96 @@ int lifetime(Gpu& gpu, ID3D12InfoQueue* info, x2w_present_signature::Block* bloc delete sampler; // a stranded sampler releases nothing it may still be using gate->Release(); } + // Device removal while a copy is in flight: the fence reports UINT64_MAX, which is not a + // completion. Nothing is mapped or published, the sampler stops sampling, and the source stays + // held; the destructor keeps every object the copy uses. A genuine prior sample (published + // before the removal) stays as it was: no stale publish, no clearing. + { + ID3D12Resource* presented = surface(gpu, DXGI_FORMAT_R8G8B8A8_UNORM, picture); + RemovalDevice removed_device(gpu.device); + // The queue proxy unwraps the sampler's RemovedFence to its real fence by exact fake + // identity, so no fake COM object ever reaches the driver. + SignalFailingQueue unwrapping(gpu.queue, &removed_device.fence()); + x2w_present_signature::Sampler sampler(1, true, true); + ID3D12Fence* gate = stall(gpu); + const LONG64 before = block->sequence / 2; + // First a genuine completed copy: it publishes and fills the historical sample state. + sampler.present(&removed_device, &unwrapping, presented, 1, block); + gate->Signal(1); + gpu.idle(); + sampler.present(&removed_device, &unwrapping, nullptr, 2, block); + ID3D12Resource* const sampled_surface = sampler.last_surface(); + const bool had_sample = block->sequence / 2 == before + 1 && sampler.last_present() == 1 + && sampled_surface && !sampler.holds_source(); + check(had_sample, "a genuine copy completes and publishes before the removal"); + // Then a second copy whose fence will report device removal. + sampler.present(&removed_device, &unwrapping, presented, 3, block); + check(sampler.in_flight() && sampler.holds_source(), "the second copy is in flight before the removal"); + const ULONG left = presented->Release(); // the caller's only reference + check(left == 1, "before the removal only the sampler's reference is left"); + gate->Signal(1); + gpu.idle(); // the copy has really finished; the fence still reports device removal + removed_device.fence().removed = true; + const LONG64 published_before = block->sequence / 2; + sampler.present(&removed_device, &unwrapping, nullptr, 4, block); + check(!sampler.in_flight() && sampler.failed() && sampler.stranded(), + "a removed fence is not a completion: the sampler stops, stranded like a failed Signal"); + check(sampler.holds_source(), "the source stays held after a removed fence"); + check(block->sequence / 2 == published_before, "a removed fence publishes no sample"); + // The prior historical sample survives exactly as it was: nothing cleared, nothing stale. + check(sampler.last_present() == 1 && sampler.last_surface() == sampled_surface, + "the prior published sample (number and surface) survives the removal unchanged"); + sampler.present(&removed_device, &unwrapping, nullptr, 5, block); + check(sampler.failed() && sampler.stranded() && !sampler.in_flight() && block->sequence / 2 == published_before, + "a stranded sampler records nothing more and keeps the surface"); + gate->Release(); + // The destructor must keep every object the copy uses (stranded): nothing is released + // under a removed device. (The destructor runs at the block's end.) + } + // The destructor's own re-observation: a copy still pending at destruction transitions across + // the destructor's 10 s wait deterministically, because the fence reports a chosen value for a + // fixed number of observations and then the real (or removed) state. Pending that completes + // while the wait runs releases normally; a fence that reports removal afterwards keeps + // everything. The real fence is the only object the driver sees. + { + // Pending completes during the destructor's wait: normal release, no strand. + { + ID3D12Resource* presented = surface(gpu, DXGI_FORMAT_R8G8B8A8_UNORM, picture); + RemovalDevice removal(gpu.device); + SignalFailingQueue unwrapping(gpu.queue, &removal.fence()); + ID3D12Fence* gate = stall(gpu); + x2w_present_signature::Sampler* sampler = new x2w_present_signature::Sampler(1); + sampler->present(&removal, &unwrapping, presented, 1, block); + check(sampler->in_flight() && sampler->holds_source(), "a stalled copy is in flight at destruction"); + gate->Signal(1); // the copy really completes; the fence is scripted to report pending once + removal.fence().pending_observations = 1; + removal.fence().next = 0; + delete sampler; // pre-wait observation: pending; wait: on the real fence; post-wait: completed + check(removal.fence().observations >= 2 && removal.fence().event_registrations == 1, + "the destructor observes before and after its wait, and registers its event once"); + check(presented->Release() == 0, "a copy that completes while the destructor waits releases the source normally"); + gate->Release(); + } + // The fence reports the removal sentinel to the post-wait observation: nothing releases. + { + ID3D12Resource* presented = surface(gpu, DXGI_FORMAT_R8G8B8A8_UNORM, picture); + RemovalDevice removal(gpu.device); + SignalFailingQueue unwrapping(gpu.queue, &removal.fence()); + ID3D12Fence* gate = stall(gpu); + x2w_present_signature::Sampler* sampler = new x2w_present_signature::Sampler(1); + sampler->present(&removal, &unwrapping, presented, 2, block); + check(sampler->in_flight() && sampler->holds_source(), "the second stalled copy is in flight at destruction"); + gate->Signal(1); // the copy really completes + removal.fence().pending_observations = 1; + removal.fence().next = 0; + removal.fence().removed = true; // from the second observation on: the removal sentinel + delete sampler; + check(removal.fence().observations == 2 && removal.fence().event_registrations == 1, + "the destructor re-observed removal after exactly one wait registration"); + check(presented->Release() == 1, "a fence that reports removal after the wait keeps the sampler's source reference"); + gate->Release(); + } + } const int errors = debug_errors(info); std::printf("held source: %d debug-layer errors\n", errors); check(errors == 0, "the debug layer reports no error for the sampler's stalled copy"); diff --git a/tests/startup_resource_retire_title.cpp b/tests/startup_resource_retire_title.cpp index ce21bc438f..75b638474b 100644 --- a/tests/startup_resource_retire_title.cpp +++ b/tests/startup_resource_retire_title.cpp @@ -407,7 +407,7 @@ constexpr UINT draw_side = 4; // 4x4 R8G8B8A8_UNORM target constexpr UINT draw_covered = 3; // scissor leaves the last row and column untouched as the sentinel constexpr int draw_seed = 77; constexpr UINT draw_clear_pixel = 0xffff00ffu; // ClearRenderTargetView({1, 0, 1, 1}) in R8G8B8A8_UNORM -constexpr char draw_revision[] = "x2w-startup-shader-28"; // d3d12_draw.inl cached_translation +constexpr char draw_revision[] = "x2w-startup-shader-29"; // d3d12_draw.inl cached_translation constexpr char draw_vertex_shader[] = R"( struct Varying { float4 position : SV_Position; }; diff --git a/tests/startup_run_ps1_check.py b/tests/startup_run_ps1_check.py index 1a4e1b5f7a..dd9202b2b8 100644 --- a/tests/startup_run_ps1_check.py +++ b/tests/startup_run_ps1_check.py @@ -31,7 +31,7 @@ import time from pathlib import Path -record = [sys.argv[1:], os.environ.get("X2W_TRACE_API"), os.environ.get("X2W_NATIVE_SHADERS")] +record = [sys.argv[1:], os.environ.get("X2W_TRACE_API"), os.environ.get("X2W_NATIVE_SHADERS"), os.environ.get("X2W_TITLE_ID"), os.environ.get("X2W_STORAGE_MB")] Path(__file__).with_name("debugger.json").write_text(json.dumps(record), encoding="utf-8") # Under -Translate, wait until the watcher stub has started so run.ps1 cannot stop it before then. watch = Path(__file__).with_name("watch.json") @@ -136,7 +136,7 @@ def alive(pid): def run_case(shell, script, code, work, translate=False, switches=(), passed=(), fake_user_env=False, - early_exit=False, trace_api_env=None, absolute_build=False, missing_build=False, native=False): + early_exit=False, trace_api_env=None, absolute_build=False, missing_build=False, native=False, manifest="absent"): """Run one copy of the script on a stub that exits with `code`; return what is wrong. `switches` are extra run.ps1 switches and `passed` the debugger arguments they must add. @@ -155,11 +155,19 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), build.mkdir() for dll in DLLS: # the stand-ins the script copies next to the executable (build / f"{dll}.dll").write_bytes(b"") - exe, data, log = root / "run" / "t.exe", root / "data", root / "log" + exe, data, log = root / "run" / "t.exe", root / ("data [test]" if manifest.startswith("bracket") else "data"), root / "log" exe.parent.mkdir() exe.write_bytes(b"") data.mkdir() + if manifest in ("normal", "bracket"): + (data / "MicrosoftGame.config").write_text("123442", encoding="utf-8") + if manifest.startswith("bracket"): + decoy = root / "data t" + decoy.mkdir() + (decoy / "MicrosoftGame.config").write_text("999999", encoding="utf-8") env = dict(os.environ) + env.pop("X2W_TITLE_ID", None) + env.pop("X2W_STORAGE_MB", None) # Compare PowerShell's warning text consistently on hosts that enable ANSI colors. env["NO_COLOR"] = "1" env.pop("X2W_FAKE_USER", None) @@ -221,9 +229,11 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), "--trace-files", "1", "--continue-asserts", "4", *passed] record = startup / "debugger.json" got = json.loads(record.read_text(encoding="utf-8")) if record.is_file() else None - expected = [want, "1" if "-TraceApi" in switches else trace_api_env, str(sdk) if native else None] + expected = [want, "1" if "-TraceApi" in switches else trace_api_env, str(sdk) if native else None, + "1234" if manifest in ("normal", "bracket") else None, + "42" if manifest in ("normal", "bracket") else None] if got != expected: - found.append(f"stub exit {code}: debugger [argv, X2W_TRACE_API, X2W_NATIVE_SHADERS] was {got}, " + found.append(f"stub exit {code}: debugger [argv, trace, native SDK, title ID, storage MB] was {got}, " f"expected {expected}") watch = startup / "watch.json" if translate: @@ -249,6 +259,8 @@ def run_problems(shell, script, work, first_only): if found and first_only: return found found += run_case(shell, script, 7, work, absolute_build=True) + for manifest in ("normal", "bracket", "bracket_missing"): + found += run_case(shell, script, 0, work, manifest=manifest) if found and first_only: return found found += run_case(shell, script, 0, work, switches=["-FakeUser"]) diff --git a/tests/startup_shader_cache_key_check.py b/tests/startup_shader_cache_key_check.py index e4b0733b63..134cfccf96 100644 --- a/tests/startup_shader_cache_key_check.py +++ b/tests/startup_shader_cache_key_check.py @@ -49,10 +49,10 @@ def check_request(blobs, key, diagnostic=None, rtv_request=None, layout=None): def main(): # Independently executed C++ runtime fnv_bytes/cached_translation known-answer vector. - # Revision x2w-startup-shader-28 excludes NUL. Stored order is a, b, root, then optional input layout. + # Revision x2w-startup-shader-29 excludes NUL. Stored order is a, b, root, then optional input layout. vector = (b"\x00VS\xff", b"PS\x00\x80", b"RTS0\x00") - assert gfx2hlsl.pipeline_key(*vector) == 0xe4791179bf7096b3 - assert gfx2hlsl.pipeline_key(*vector, b"ia\x00\xfe") == 0xf6cb7f56c2985cfb + assert gfx2hlsl.pipeline_key(*vector) == 0xa837b162afd547ce + assert gfx2hlsl.pipeline_key(*vector, b"ia\x00\xfe") == 0x6d5c0b7786182e0e blobs = (VERTEX, PIXEL, ROOT) canonical = gfx2hlsl.pipeline_key(*blobs) check_request(blobs, canonical) diff --git a/tests/startup_slot133_heap_cap_check.cpp b/tests/startup_slot133_heap_cap_check.cpp index dce82648f9..a45f05e871 100644 --- a/tests/startup_slot133_heap_cap_check.cpp +++ b/tests/startup_slot133_heap_cap_check.cpp @@ -764,6 +764,9 @@ int run_check(IUnknown* guest, ID3D12Device* device, ID3D12InfoQueue* debug, boo int main(int argc, char** argv) { + // The growth checks describe the default ring (doubling chunks up to 256 MiB). The stand-in reads + // X2W_D3D12_RING_RELEASE_AT_SUBMIT on first use in this process, so clear it before any call. + SetEnvironmentVariableW(L"X2W_D3D12_RING_RELEASE_AT_SUBMIT", nullptr); if (argc < 2 || argc > 3 || (std::strcmp(argv[1], "warp") && std::strcmp(argv[1], "hardware")) || (argc == 3 && std::strcmp(argv[2], "cap"))) { std::puts("usage: startup_slot133_heap_cap_check [cap]"); diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index 2419156f9b..33f84ac737 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -215,14 +215,17 @@ static void* make_committed(void* device, D3D12_HEAP_TYPE type, const D3D12_RESO // For any mode, X2W_TEST_DISPATCH_IN names 1280 bytes that replace the input words, and X2W_TEST_DISPATCH_FIELDS // names six words that replace, for the input and then the output descriptor, the stride (word 1 bits 16-31), the // record count (word 2) and word 3, which are otherwise 4, 320 and 0. +// Table controls bind away from the heap start or change the root/view heap after slot 35 without rebinding. static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::string& mode) { constexpr UINT words = 320; const bool indirect = mode.rfind("dispatch-indirect-", 0) == 0; + const bool root_srv = mode.rfind("dispatch-root-srv", 0) == 0; const UINT groups = mode == "dispatch-indirect-zero" ? 0u : mode == "dispatch-indirect-2" ? 2u : 5u; - auto* memory = static_cast(VirtualAlloc(nullptr, indirect ? 0x30000 : 0x20000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + auto* memory = static_cast(VirtualAlloc(nullptr, (indirect || root_srv) ? 0x30000 : 0x20000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); if (!memory) return 70; UINT* const buffers[2] = {memory, memory + 0x10000 / sizeof(UINT)}; + UINT* const buffer2 = memory + 0x20000 / sizeof(UINT); for (UINT i = 0; i < words; ++i) { buffers[0][i] = 0x8b02a7f1u + i * 0x413b1u; buffers[1][i] = 0xc5c5c5c5u; @@ -250,7 +253,19 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin std::memcpy(descriptors[mode == "dispatch-swapped" ? 1 - i : i], view, sizeof(view)); } const UINT64 between = reinterpret_cast(memory) + 0x8000; - if (mode == "dispatch-input-copied") { + void* placed2 = nullptr; + if (root_srv) { + for (UINT i = 0; i < words; ++i) buffer2[i] = 0x3c6ef372u + i * 0x19660du; + for (UINT i = 0; i < 64; ++i) { + buffers[0][words + i] = 0xdeadbeefu + i; + buffer2[words + i] = 0xfeedfaceu + i; + } + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, words * sizeof(UINT), 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + if (FAILED(static_cast(invoke(device, 133, word(buffer2), word(&desc), D3D12_RESOURCE_STATE_COMMON, 0, + word(&__uuidof(ID3D12Resource)), word(&placed2))))) return 71; + } + if (mode == "dispatch-input-copied" || mode == "dispatch-root-srv-copied") { const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, words * sizeof(UINT), 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; void* copied = nullptr; @@ -287,7 +302,25 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin const UINT alias[4] = {static_cast(address), static_cast(address >> 32) | (4u << 16), 5, 0}; std::memcpy(descriptors[1], alias, sizeof(alias)); } - std::memcpy(reinterpret_cast(cpu), descriptors, sizeof(descriptors)); + const bool change_table_root = mode == "dispatch-table-root-changed"; + const bool change_table_heap = mode == "dispatch-table-heap-changed"; + StreamWord table_gpu = gpu; + if (mode == "dispatch-table-offset") { + const UINT increment = static_cast(invoke(device, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)); + if (increment < sizeof(descriptors[0])) return 73; + const StreamWord offset = StreamWord{2} * increment; + // The heap starts with the wrong pair, but both records are well-formed. The correct pair starts at index 2. + std::memcpy(reinterpret_cast(cpu), descriptors[1], sizeof(descriptors[1])); + std::memcpy(reinterpret_cast(cpu + sizeof(descriptors[1])), descriptors[0], sizeof(descriptors[0])); + std::memcpy(reinterpret_cast(cpu + offset), descriptors, sizeof(descriptors)); + table_gpu += offset; + } else { + std::memcpy(reinterpret_cast(cpu), descriptors, sizeof(descriptors)); + } + void* other_heap = nullptr; + if (change_table_heap && + (FAILED(static_cast(invoke(device, 14, word(&heap_desc), word(&__uuidof(ID3D12DescriptorHeap)), + word(&other_heap)))) || !other_heap || other_heap == heap)) return 72; if (mode == "dispatch-records32") { // the output's descriptor at table byte 32, none at byte 16 std::memset(reinterpret_cast(cpu + sizeof(descriptors[0])), 0, sizeof(descriptors[1])); std::memcpy(reinterpret_cast(cpu + 32), descriptors[1], sizeof(descriptors[1])); @@ -349,6 +382,40 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin std::memcpy(reinterpret_cast(cpu + sizeof(descriptors[0])), descriptors[1], sizeof(descriptors[1])); std::memcpy(unplaced + 4, buffers[0], words * sizeof(UINT)); } + if (root_srv && mode != "dispatch-root-srv-unset") { + UINT64 addr0 = reinterpret_cast(buffers[0]); + UINT64 addr1 = reinterpret_cast(buffer2); + if (mode == "dispatch-root-srv-offset") { + addr0 += 16; + addr1 += 32; + } else if (mode == "dispatch-root-srv-upload") { + auto* const up = static_cast(reinterpret_cast(invoke(list, 148, words * sizeof(UINT), 256))); + if (!up) return 81; + std::memcpy(up, buffers[0], words * sizeof(UINT)); + addr0 = reinterpret_cast(up) + 16; + } else if (mode == "dispatch-root-srv-null") { + addr0 = 0; + } else if (mode == "dispatch-root-srv-unaligned") { + addr0 += 2; + } else if (mode == "dispatch-root-srv-unaligned-16") { + addr0 += 4; + } else if (mode == "dispatch-root-srv-unmapped" || mode == "dispatch-root-srv-copied") { + addr0 = between; + } else if (mode == "dispatch-root-srv-same-buffer") { + addr0 = reinterpret_cast(buffers[1]); + } + invoke(list, 43, 2, addr0); + if (mode != "dispatch-root-srv-unset-second") invoke(list, 43, 3, addr1); + } + if (mode == "dispatch-root-srv-root-changed") { + invoke(list, 33, word(slot67_other_root)); + invoke(list, 33, word(slot67_root)); + } else if (mode == "dispatch-root-srv-same-root") { + invoke(list, 33, word(slot67_root)); + } else if (mode == "dispatch-root-srv-reset") { + if (FAILED(static_cast(invoke(list, 9))) || FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; + bind(); + } if (mode != "dispatch-missing-word") invoke(list, 37, 0, constants[0], 0); invoke(list, 40, 0, 2, word(graphics), 0); invoke(list, 39, 0, 1, word(&constants[1]), 1); @@ -358,7 +425,7 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin if (FAILED(static_cast(invoke(list, 9))) || FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; bind(); } - if (heap_record) invoke(list, 39, 0, 1, word(&constants[2]), 2); + if (heap_record || root_srv) invoke(list, 39, 0, 1, word(&constants[2]), 2); if (heap_word) { // The index buffer of table byte 96, in this recording's upload memory (list slot 148). Byte 288 + 336 * 1 // holds the index, 2; every other word names record 0 or 1, the output's descriptor. @@ -373,17 +440,40 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin mode == "dispatch-heap-word-past" ? at : mode == "dispatch-heap-word-placed" ? words * 4 : bytes, 0}; std::memcpy(reinterpret_cast(cpu + 96), view, sizeof(view)); } - invoke(list, 35, 1, gpu); + invoke(list, 35, 1, table_gpu); + if (change_table_root) { + invoke(list, 33, word(slot67_other_root)); + invoke(list, 33, word(slot67_root)); + } + if (change_table_heap) invoke(list, 32, 1, word(&other_heap)); + if (change_table_root || change_table_heap) { + // Give Dispatch the expected entry values without rebinding slot 35. + invoke(list, 37, 0, constants[0], 0); + invoke(list, 39, 0, 1, word(&constants[1]), 1); + } + if (mode == "dispatch-table-offset") invoke(list, 32, 1, word(&heap)); // same heap keeps the offset table if (indirect) record.execute(list, mode == "dispatch-indirect-multi" ? 2 : 1, mode == "dispatch-indirect-counted", mode == "dispatch-indirect-outside"); else if (mode == "dispatch-reference-2" || mode == "dispatch-reference-5") invoke(list, 14, mode == "dispatch-reference-2" ? 2 : 5, 1, 1); - else if (mode != "dispatch-none") invoke(list, 14, 3, 2, 2); + else if (mode != "dispatch-none" && mode != "dispatch-root-srv-none") invoke(list, 14, 3, 2, 2); if (FAILED(static_cast(invoke(list, 9)))) return 75; invoke(queue, 10, 1, word(&list)); if (FAILED(static_cast(invoke(queue, 14, word(fence), 1)))) return 76; - for (const ULONGLONG deadline = GetTickCount64() + 10000; invoke(fence, 8) < 1;) { - if (GetTickCount64() >= deadline) return 78; + // Render mode publishes the guest fence value after desktop queue completion. + const ULONGLONG deadline = GetTickCount64() + 10000; + for (;;) { + const auto completed = invoke(fence, 8); + const HRESULT removed = static_cast(invoke(device, 37)); + if (completed == ~UINT64{0} || FAILED(removed)) { + std::fprintf(stderr, "slot 67 Dispatch fence: device removed (0x%08lx)\n", static_cast(removed)); + return 78; + } + if (completed == 1) break; + if (GetTickCount64() >= deadline) { + std::fputs("slot 67 Dispatch fence: timed out\n", stderr); + return 78; + } Sleep(1); } if (indirect && !record.check_record(groups)) return 80; @@ -407,9 +497,14 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin // handle, which keeps the first view; texture-store-self also creates a shader resource view of the texture at table byte 0. static int texture_slot67(void* device, const std::string& mode) { - constexpr UINT width = 32, height = 8; - const bool fp32 = mode == "texture-array" || mode == "texture-array-2d"; - const UINT layers = mode == "texture-array" || mode == "texture-array-d16" ? 6 : 1; + constexpr UINT width = 32; + const bool volume = mode == "texture-volume" || mode == "texture-volume-bad-w"; + const bool line = mode == "texture-line" || mode == "texture-line-bad-mip"; + const UINT mip = volume || line ? 1 : 0; + const UINT height = line ? 1 : 8; + const bool fp32 = volume || line || mode == "texture-array" || mode == "texture-array-2d"; + const UINT layers = volume || mode == "texture-array" || mode == "texture-array-d16" ? 6 : 1; + const UINT subresources = volume ? 1 : layers; const UINT pitch = width * (fp32 ? 16 : 8), slice_bytes = pitch * height, bytes = slice_bytes * layers; const auto word = [](const void* value) { return reinterpret_cast(value); }; const auto make = [&](D3D12_HEAP_TYPE type, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state) { @@ -417,7 +512,10 @@ static int texture_slot67(void* device, const std::string& mode) }; const DXGI_FORMAT format = fp32 ? DXGI_FORMAT_R32G32B32A32_FLOAT : mode == "texture-store-uint" ? DXGI_FORMAT_R16G16B16A16_UINT : DXGI_FORMAT_R16G16B16A16_FLOAT; - const D3D12_RESOURCE_DESC texture_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, static_cast(layers), 1, format, + const auto dimension = volume ? D3D12_RESOURCE_DIMENSION_TEXTURE3D : line ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : + D3D12_RESOURCE_DIMENSION_TEXTURE2D; + const D3D12_RESOURCE_DESC texture_desc{dimension, 0, width << mip, line ? 1 : height << mip, + static_cast(volume ? layers << mip : layers), static_cast(mip + 1), format, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, mode == "texture-store-denied" ? D3D12_RESOURCE_FLAG_NONE : D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; const D3D12_RESOURCE_DESC buffer_desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, @@ -450,7 +548,14 @@ static int texture_slot67(void* device, const std::string& mode) const StreamWord cpu = invoke(heap, 9), gpu = invoke(heap, 10); if (!cpu || !gpu) return 73; D3D12_UNORDERED_ACCESS_VIEW_DESC view{format, D3D12_UAV_DIMENSION_TEXTURE2D}; - if (layers > 1) { + if (volume) { + view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + // At mip 1 the depth is six. The bad count fits only if the binder uses the base mip's depth. + view.Texture3D = {mip, 1, mode == "texture-volume-bad-w" ? layers : ~0u}; + } else if (line) { + view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; + view.Texture1D.MipSlice = mode == "texture-line-bad-mip" ? mip + 1 : mip; // bad-mip: one past the last mip + } else if (layers > 1) { view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; view.Texture2DArray = {0, 1, 4, 0}; // four selected slices, with untouched neighbors on both sides } @@ -478,15 +583,15 @@ static int texture_slot67(void* device, const std::string& mode) if (mode == "texture-store-self") invoke(device, 18, word(texture), word(&read), cpu); D3D12_TEXTURE_COPY_LOCATION image{static_cast(texture), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; D3D12_TEXTURE_COPY_LOCATION source{static_cast(upload), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; - source.PlacedFootprint = {0, {format, width, height, 1, pitch}}; + source.PlacedFootprint = {0, {format, width, height, volume ? layers : 1, pitch}}; D3D12_TEXTURE_COPY_LOCATION result = source; result.pResource = static_cast(readback); const UINT constants[3] = {1, 2, 3}; if (FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; invoke(list, 32, 1, word(&heap)); - for (UINT layer = 0; layer < layers; ++layer) { - image.SubresourceIndex = layer; - source.PlacedFootprint.Offset = UINT64{layer} * slice_bytes; + for (UINT subresource = 0; subresource < subresources; ++subresource) { + image.SubresourceIndex = subresource + mip; + source.PlacedFootprint.Offset = UINT64{subresource} * slice_bytes; invoke(list, 16, word(&image), 0, 0, 0, word(&source), 0); } invoke(list, 25, word(slot67_pipeline)); @@ -494,9 +599,9 @@ static int texture_slot67(void* device, const std::string& mode) invoke(list, 39, 0, 3, word(constants), 0); invoke(list, 35, 1, gpu); if (mode != "texture-store-none") invoke(list, 14, 2, 1, 1); - for (UINT layer = 0; layer < layers; ++layer) { - image.SubresourceIndex = layer; - result.PlacedFootprint.Offset = UINT64{layer} * slice_bytes; + for (UINT subresource = 0; subresource < subresources; ++subresource) { + image.SubresourceIndex = subresource + mip; + result.PlacedFootprint.Offset = UINT64{subresource} * slice_bytes; invoke(list, 16, word(&result), 0, 0, 0, word(&image), 0); } if (FAILED(static_cast(invoke(list, 9)))) return 75; diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index 26b37f639f..9c7d7844bb 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -507,6 +507,9 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* } else if (GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_VIEW", nullptr, 0)) { extern int draw_formatted_view(void*, void*); if (const int result = draw_formatted_view(guest, list)) return result; + } else if (GetEnvironmentVariableW(L"X2W_TEST_TABLE_ALIAS_WRITE", nullptr, 0)) { + extern int draw_table_alias_writes(ID3D12Device*, void*, void*); + if (const int result = draw_table_alias_writes(desktop.Get(), guest, list)) return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_COPIED_VERTEX_SRV", nullptr, 0)) { extern int draw_copied_vertex_buffer_srv(void*, void*); if (const int result = draw_copied_vertex_buffer_srv(guest, list)) return result; @@ -584,6 +587,46 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* invoke(list, 25, arg(pso)); return true; }; + // X2W_TEST_CONSOLE_KEEP (with the shared ring): a second list A records 32 payloads (32 x 16 MiB = 512 MiB), + // is submitted and waited for, and is never Reset. The fixture's own list then draws payload 32 over the right + // half. A is then submitted again, still closed and not Reset, and the target is read back. + if (GetEnvironmentVariableW(L"X2W_TEST_CONSOLE_KEEP", nullptr, 0)) { + constexpr unsigned kept = 32; + void *allocator_a = nullptr, *list_a = nullptr; + const unsigned list_a_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + if (FAILED(static_cast(invoke(guest, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, + arg(&__uuidof(ID3D12CommandAllocator)), arg(&allocator_a)))) || + FAILED(static_cast(invoke(guest, 73, arg(list_a_desc), arg(allocator_a), 0, + arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list_a)))) || + FAILED(static_cast(invoke(allocator_a, 8))) || + FAILED(static_cast(invoke(list_a, 139, arg(allocator_a))))) return 23; // created closed + const D3D12_VIEWPORT whole{0, 0, static_cast(width), static_cast(height), 0, 1}; + invoke(list_a, 50, 1, arg(&rtv)); + invoke(list_a, 21, 1, arg(&whole)); + invoke(list_a, 20, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + invoke(list_a, 25, arg(pso)); + for (unsigned payload = 0; payload < kept; ++payload) + if (const int result = draw_gated_console_payload(guest, list_a, payload, payload == 0)) return result; + const auto submit_and_wait = [&](void* recorded, UINT64 value) { + invoke(queue, 10, 1, arg(&recorded)); + if (FAILED(static_cast(invoke(queue, 14, arg(fence), value)))) return false; + const auto deadline = GetTickCount64() + 60000; + while (invoke(fence, 8) < value && GetTickCount64() < deadline) Sleep(1); + return invoke(fence, 8) == value; + }; + invoke(list, 9); // the fixture's own recording so far (its clear) runs first + if (!submit_and_wait(list, 1)) return 25; + invoke(list_a, 9); + if (!submit_and_wait(list_a, 2)) return 25; + if (!next_recording()) return 35; + if (const int result = draw_gated_console_payload(guest, list, kept, false)) return result; + invoke(list, 9); + if (!submit_and_wait(list, 3)) return 25; + // A again: closed, never Reset. The target is read back after it, so a stale A that ran (its last + // payload, 31, over the right half) shows in the pixels. + if (!submit_and_wait(list_a, 4)) return 25; + return read_stream_target(desktop.Get(), frame, pixels); + } // Retrying the same bytes after abandoning a recording still needs an upload. The shared-ring // control skips it so every upload behind the gate comes from the ring, whose 256 MiB cap is // then exhausted: the later reservations are refused and those draws bind the null view. @@ -687,6 +730,10 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* extern int root_heap_report(); if (const int rc = root_heap_report()) return rc; } + if (GetEnvironmentVariableW(L"X2W_TEST_TABLE_ALIAS_WRITE", nullptr, 0)) { + extern void table_alias_debug_report(); + table_alias_debug_report(); + } return read_stream_target(desktop.Get(), frame, pixels); } diff --git a/tests/startup_stream_setup.cpp b/tests/startup_stream_setup.cpp index 929f4d3e24..2e05936d37 100644 --- a/tests/startup_stream_setup.cpp +++ b/tests/startup_stream_setup.cpp @@ -117,6 +117,15 @@ int prepare_stream_pipeline(const char* vs_path, const char* ps_path, const char return 77; } debug->EnableDebugLayer(); + // X2W_TEST_GPU_VALIDATION=1: also check the states of resources reached through descriptor tables. + ComPtr debug1; + if (GetEnvironmentVariableW(L"X2W_TEST_GPU_VALIDATION", nullptr, 0)) { + if (FAILED(debug.As(&debug1))) { + std::printf("no GPU-based validation: skipped\n"); + return 77; + } + debug1->SetEnableGPUBasedValidation(TRUE); + } } if (const int rc = pick_stream_adapter(hardware, adapter)) return rc; diff --git a/tests/startup_table_alias_check.py b/tests/startup_table_alias_check.py new file mode 100644 index 0000000000..2e07c583be --- /dev/null +++ b/tests/startup_table_alias_check.py @@ -0,0 +1,109 @@ +"""A table buffer view over a placed buffer: per-draw copies by default, a live alias with X2W_D3D12_TABLE_ALIAS=1. + +Cases (X2W_TEST_TABLE_ALIAS_WRITE in tests/startup_address_srv.cpp): + writes records rewritten between two draws and after recording: copies show 40 | 80, the alias 120. + shared-index the alias is also the draw's index buffer. Run with the debug layer and GPU-based validation; no + error may be reported, so the alias must hold both the index-buffer and shader-resource states. + odd-size a 254-byte buffer under a 127 x 2-byte structured view: the 256-byte raw view does not fit the + alias, so even with the switch the draw reads a copy (40), not the later write (120). +""" +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +from startup_address_srv_check import draw_texture, prepare_draw_cache + +VERTEX = """ +ByteAddressBuffer records : register(t0); +struct Vertex { + float4 position : SV_Position; + nointerpolation uint2 values : TEXCOORD0; +}; +Vertex main(uint id : SV_VertexID) { + const float2 corners[3] = {float2(-1, 1), float2(3, 1), float2(-1, -3)}; + Vertex output; + output.position = float4(corners[id], 0.5, 1); + output.values = uint2(records.Load(16), records.Load(20)); + return output; +} +""" + +PIXEL = """ +float4 main(float4 position : SV_Position, nointerpolation uint2 values : TEXCOORD0) : SV_Target { + return float4(float2(values) / 255.0, 0, 1); +} +""" + +BINDING = "srv 0 buf table 0 0" +VALIDATION = {"X2W_TEST_DEBUG_LAYER": "1", "X2W_TEST_GPU_VALIDATION": "1"} + + +def texel(value): + return bytes((value, value + 1, 0, 255)) + + +def run(folder, consumer, backend, modes): + """Pixels and stdout of one consumer run, or (None, "") for a capability skip.""" + try: + env, args, output = prepare_draw_cache(folder, consumer, PIXEL, modes, BINDING, vertex_hlsl=VERTEX) + except subprocess.CalledProcessError as error: + if error.returncode == 77: # no existing heaps, debug layer or GPU-based validation + return None, "" + raise + result = subprocess.run([*args, backend, output], env=env, capture_output=True, text=True) + print(result.stdout, end="") + if result.returncode == 77: + return None, "" + if result.returncode: + raise RuntimeError(f"consumer failed ({result.returncode})\n{result.stderr[-5000:]}") + return output.read_bytes(), result.stdout + + +def debug_errors(stdout, name): + found = re.search(r"^table alias debug layer errors: (\d+)$", stdout, re.M) + if not found: + raise AssertionError(f"{name}: no debug layer message count") + return int(found.group(1)) + + +def check(directory, consumer, backend): + # The fixture writes 40, draws the left half, writes 80, draws the right half, then writes 120 before the list runs. + cases = ( + # The copy case clears the switch, so it keeps testing the default when the switch is set in the environment. + ("copy", {"X2W_D3D12_TABLE_ALIAS": "0"}, texel(40) * 4 + texel(80) * 4), + ("alias", {"X2W_D3D12_TABLE_ALIAS": "1"}, texel(120) * 8), + ) + for name, switches, row in cases: + folder = directory / name + folder.mkdir() + pixels = draw_texture(folder, consumer, backend, PIXEL, {"X2W_TEST_TABLE_ALIAS_WRITE": "1", **switches}, + binding=BINDING, vertex_hlsl=VERTEX) + if pixels is None: + return 77 + expected = row * 4 + if pixels != expected: + raise AssertionError(f"{backend}: {name} table buffer got {pixels.hex()}, expected {expected.hex()}") + print(f"{backend}: 32 pixels matched the {name} reading of a rewritten table buffer") + + for name, extra, value in (("shared-index", VALIDATION, 40), ("odd-size", VALIDATION, 40)): + folder = directory / name + folder.mkdir() + modes = {"X2W_TEST_TABLE_ALIAS_WRITE": name, "X2W_D3D12_TABLE_ALIAS": "1", **extra} + pixels, stdout = run(folder, consumer, backend, modes) + if pixels is None: + return 77 + expected = texel(value) * 32 + if pixels != expected: + raise AssertionError(f"{backend}: {name} got {pixels.hex()}, expected {expected.hex()}") + errors = debug_errors(stdout, name) + if errors: + raise AssertionError(f"{backend}: {name}: {errors} debug layer errors") + print(f"{backend}: {name}: 32 pixels exact, no debug layer errors") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:])) diff --git a/tests/texture_blocks_check.py b/tests/texture_blocks_check.py new file mode 100644 index 0000000000..685e6e6e7a --- /dev/null +++ b/tests/texture_blocks_check.py @@ -0,0 +1,284 @@ +#!/usr/bin/env python3 +"""Standalone unit, bounds-guard, and mutation suite for tools/texture_blocks.py.""" + +from __future__ import annotations + +import array +from pathlib import Path +import struct +import sys +import types +import unittest + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "texture_blocks.py" +sys.path.insert(0, str(ROOT / "tools")) + +import texture_blocks # noqa: E402 + + +BC_2D_FORMATS = ( + ("BC1_UNORM", 71, 8), + ("BC2_UNORM", 74, 16), + ("BC3_UNORM", 77, 16), + ("BC4_UNORM", 79, 8), + ("BC5_UNORM", 83, 16), + ("BC6H_UF16", 95, 16), + ("BC7_UNORM", 98, 16), +) + + +def _block_bytes_tag(fam: int, x: int, y: int, block_bytes: int, z: int = 0) -> bytes: + head = struct.pack(" tuple[int, int]: + return (width + 3) // 4, (height + 3) // 4 + + +class TextureBlocksPositiveTests(unittest.TestCase): + def test_formats_table_preserved(self) -> None: + for name, dxgi, bpb in BC_2D_FORMATS: + with self.subTest(format=name): + info = texture_blocks.format_info(name) + self.assertEqual(info.dxgi_format, dxgi) + self.assertEqual(info.block_extent, (4, 4, 1)) + self.assertEqual(info.bytes_per_block, bpb) + self.assertEqual(info.dimension, 2) + vol = texture_blocks.format_info("BC7_UNORM_VOLUME") + self.assertEqual((vol.dxgi_format, vol.block_extent, vol.bytes_per_block, vol.dimension), + (98, (4, 4, 1), 16, 3)) + + def test_2d_bc1_to_bc7_round_trips_non_mult4_and_pitched(self) -> None: + dims = ((1, 1, 0), (3, 5, 1), (5, 3, 2), (17, 9, 3), (65, 19, 4)) + for fam, (name, _, bpb) in enumerate(BC_2D_FORMATS, start=1): + custom_pad = bytes([(0xA0 + fam) & 0xFF]) * bpb + for width, height, extra in dims: + cols, rows = _columns_rows(width, height) + pitch = cols + extra + tight = b"".join(_block_bytes_tag(fam, x, y, bpb) for y in range(rows) for x in range(cols)) + with self.subTest(format=name, width=width, height=height, pitch=pitch): + self.assertEqual(texture_blocks.surface_bytes(width, height, name), cols * rows * bpb) + self.assertEqual( + texture_blocks.surface_bytes(width, height, name, pitch_blocks=pitch), + pitch * rows * bpb, + ) + + tiled_tight = texture_blocks.tile_blocks(tight, width, height, name) + self.assertEqual(tiled_tight, tight) + self.assertEqual(texture_blocks.linearize_blocks(tiled_tight, width, height, name), tight) + + for pad in (custom_pad, bytearray(custom_pad), memoryview(custom_pad)): + tiled = texture_blocks.tile_blocks( + tight, + width, + height, + name, + pitch_blocks=pitch, + padding=pad, + ) + self.assertEqual(len(tiled), pitch * rows * bpb) + if extra > 0: + for y in range(rows): + row_tail_start = (y * pitch + cols) * bpb + row_tail_end = ((y + 1) * pitch) * bpb + self.assertEqual(tiled[row_tail_start:row_tail_end], custom_pad * extra) + self.assertEqual( + texture_blocks.linearize_blocks(memoryview(tiled), width, height, name, pitch_blocks=pitch), + tight, + ) + + def test_3d_volume_round_trip_with_non_mult4_dims(self) -> None: + for width, height, depth in ((1, 1, 1), (3, 5, 3), (65, 19, 2)): + cols, rows = _columns_rows(width, height) + slices = [ + b"".join(_block_bytes_tag(7, x, y, 16, z) for y in range(rows) for x in range(cols)) + for z in range(depth) + ] + expected_tight = b"".join(slices) + with self.subTest(width=width, height=height, depth=depth): + payload = texture_blocks.tile_volume_4k_s( + (s for s in slices), + width, + height, + depth, + "BC7_UNORM_VOLUME", + ) + tile_pitch = (cols + 15) // 16 + slice_stride = tile_pitch * ((rows + 15) // 16) * 4096 + self.assertEqual(len(payload), depth * slice_stride) + self.assertEqual( + texture_blocks.linearize_volume_4k_s(payload, width, height, depth, "BC7_UNORM_VOLUME"), + expected_tight, + ) + self.assertEqual( + texture_blocks.linearize_volume_4k_s(memoryview(payload), width, height, depth, "BC7_UNORM_VOLUME"), + expected_tight, + ) + + +class TextureBlocksNegativeAndMutationTests(unittest.TestCase): + def test_bool_non_int_and_non_positive_dims_and_pitch_rejected(self) -> None: + fmt = texture_blocks.format_info("BC7_UNORM") + tight_4x4 = bytes(16) + padded_4x4 = bytes(32) + vol_slice = bytes(16) + vol_payload = bytes(4096) + + for bad_dim in (True, False, 0, -1, -8, 1.5, "4", None): + with self.subTest(bad_dim=bad_dim): + with self.assertRaises(ValueError): + texture_blocks._grid(bad_dim, 4, fmt) + with self.assertRaises(ValueError): + texture_blocks._grid(4, bad_dim, fmt) + with self.assertRaises(ValueError): + texture_blocks.surface_bytes(bad_dim, 4, "BC7_UNORM") + with self.assertRaises(ValueError): + texture_blocks.surface_bytes(4, bad_dim, "BC7_UNORM") + with self.assertRaises(ValueError): + texture_blocks.linearize_blocks(tight_4x4, bad_dim, 4, "BC7_UNORM") + with self.assertRaises(ValueError): + texture_blocks.linearize_blocks(tight_4x4, 4, bad_dim, "BC7_UNORM") + with self.assertRaises(ValueError): + texture_blocks.tile_blocks(tight_4x4, bad_dim, 4, "BC7_UNORM") + with self.assertRaises(ValueError): + texture_blocks.tile_blocks(tight_4x4, 4, bad_dim, "BC7_UNORM") + with self.assertRaises(ValueError): + texture_blocks.tile_volume_4k_s([vol_slice], bad_dim, 4, 1, "BC7_UNORM_VOLUME") + with self.assertRaises(ValueError): + texture_blocks.tile_volume_4k_s([vol_slice], 4, bad_dim, 1, "BC7_UNORM_VOLUME") + with self.assertRaises(ValueError): + texture_blocks.tile_volume_4k_s([vol_slice], 4, 4, bad_dim, "BC7_UNORM_VOLUME") + with self.assertRaises(ValueError): + texture_blocks.linearize_volume_4k_s(vol_payload, bad_dim, 4, 1, "BC7_UNORM_VOLUME") + with self.assertRaises(ValueError): + texture_blocks.linearize_volume_4k_s(vol_payload, 4, bad_dim, 1, "BC7_UNORM_VOLUME") + with self.assertRaises(ValueError): + texture_blocks.linearize_volume_4k_s(vol_payload, 4, 4, bad_dim, "BC7_UNORM_VOLUME") + + for bad_pitch in (True, False, 0, 1, -1, 2.0, "2"): + with self.subTest(bad_pitch=bad_pitch): + with self.assertRaises(ValueError): + texture_blocks.surface_bytes(8, 4, "BC7_UNORM", pitch_blocks=bad_pitch) + with self.assertRaises(ValueError): + texture_blocks.linearize_blocks(padded_4x4, 8, 4, "BC7_UNORM", pitch_blocks=bad_pitch) + with self.assertRaises(ValueError): + texture_blocks.tile_blocks(padded_4x4, 8, 4, "BC7_UNORM", pitch_blocks=bad_pitch) + + def test_wrong_payload_padding_and_format_mismatches_rejected(self) -> None: + tight_bc1 = bytes(16) # 8x4 BC1_UNORM = 2 blocks * 8 bytes + for bad_len_payload in (b"", bytes(15), bytes(17), bytes(24)): + with self.subTest(bad_len=len(bad_len_payload)): + with self.assertRaises(ValueError): + texture_blocks.linearize_blocks(bad_len_payload, 8, 4, "BC1_UNORM") + with self.assertRaises(ValueError): + texture_blocks.tile_blocks(bad_len_payload, 8, 4, "BC1_UNORM") + + int_view = memoryview(array.array("I", [1, 2])) # nbytes=8 but format != 'B' + for bad_pad in (b"", b"x" * 7, b"x" * 9, "x" * 8, [0] * 8, (0,) * 8, 123, int_view): + with self.subTest(bad_pad=repr(bad_pad)): + with self.assertRaises(ValueError): + texture_blocks.tile_blocks(tight_bc1, 8, 4, "BC1_UNORM", pitch_blocks=3, padding=bad_pad) + with self.assertRaisesRegex(ValueError, "Expected one 8-byte padding block"): + texture_blocks.tile_blocks(bytes(8), 4, 4, "BC1_UNORM", pitch_blocks=1, padding=b"") + + # Volume slice count and payload length mismatches. + with self.assertRaises(ValueError): + texture_blocks.tile_volume_4k_s([bytes(16)], 4, 4, 2, "BC7_UNORM_VOLUME") + with self.assertRaises(ValueError): + texture_blocks.tile_volume_4k_s([bytes(15)], 4, 4, 1, "BC7_UNORM_VOLUME") + with self.assertRaises(ValueError): + texture_blocks.linearize_volume_4k_s(bytes(4095), 4, 4, 1, "BC7_UNORM_VOLUME") + + # 2D vs 3D and unknown format mismatches. + with self.assertRaisesRegex(ValueError, "volume format"): + texture_blocks.surface_bytes(4, 4, "BC7_UNORM_VOLUME") + with self.assertRaisesRegex(ValueError, "volume format"): + texture_blocks.tile_blocks(bytes(16), 4, 4, "BC7_UNORM_VOLUME") + with self.assertRaisesRegex(ValueError, "2-D format"): + texture_blocks.tile_volume_4k_s([bytes(16)], 4, 4, 1, "BC7_UNORM") + with self.assertRaisesRegex(ValueError, "2-D format"): + texture_blocks.linearize_volume_4k_s(bytes(4096), 4, 4, 1, "BC1_UNORM") + for unknown in ("UNKNOWN_BC", 123, None, ["BC7_UNORM"]): + with self.subTest(unknown=unknown): + with self.assertRaises(ValueError): + texture_blocks.format_info(unknown) + + def test_fast_temp_mutations(self) -> None: + source = TOOL.read_text(encoding="utf-8") + + def _check_bool_mutation(mod) -> None: + self.assertEqual(mod.surface_bytes(True, 4, "BC7_UNORM"), 16) + + def _check_narrow_pitch_mutation(mod) -> None: + self.assertEqual(mod.surface_bytes(8, 4, "BC7_UNORM", pitch_blocks=1), 16) + + def _check_padding_type_mutation(mod) -> None: + out = mod.tile_blocks(bytes(8), 4, 4, "BC1_UNORM", pitch_blocks=2, padding=[0x5A] * 8) + self.assertEqual(len(out), 16) + + def _check_padding_len_mutation(mod) -> None: + out = mod.tile_blocks(bytes(8), 4, 4, "BC1_UNORM", pitch_blocks=1, padding=b"") + self.assertEqual(out, bytes(8)) + + def _check_depth_positive_mutation(mod) -> None: + self.assertEqual(mod.linearize_volume_4k_s(b"", 4, 4, 0, "BC7_UNORM_VOLUME"), b"") + + mutations = ( + ( + "drop_bool_guard", + " if isinstance(value, bool) or not isinstance(value, int):\n", + " if not isinstance(value, int):\n", + _check_bool_mutation, + ), + ( + "drop_narrow_pitch_guard", + ' if pitch < columns:\n raise ValueError(f"Block pitch {pitch} is narrower than the {columns}-block surface")\n', + " pass\n", + _check_narrow_pitch_mutation, + ), + ( + "drop_padding_type_guard", + ' elif isinstance(padding, (bytes, bytearray)):\n' + ' padding_bytes = bytes(padding)\n' + ' elif isinstance(padding, memoryview) and padding.ndim == 1 and padding.format == "B":\n' + ' padding_bytes = bytes(padding)\n' + ' else:\n' + ' raise ValueError(f"Expected bytes-like padding of {block_bytes} bytes, got {type(padding).__name__}")\n', + " else:\n padding_bytes = padding\n", + _check_padding_type_mutation, + ), + ( + "drop_padding_len_guard", + ' if len(padding_bytes) != block_bytes:\n raise ValueError(f"Expected one {block_bytes}-byte padding block")\n', + " pass\n", + _check_padding_len_mutation, + ), + ( + "drop_depth_positive_guard", + ' if depth <= 0:\n raise ValueError("Expected a positive volume depth")\n', + " pass\n", + _check_depth_positive_mutation, + ), + ) + + for label, target, replacement, check_fn in mutations: + with self.subTest(mutation=label): + count = source.count(target) + self.assertGreaterEqual(count, 1, target) + # For depth guard, target appears twice (tile_volume_4k_s and linearize_volume_4k_s); + # mutate the linearize_volume_4k_s guard or replace all for clean mutant check. + mutated_src = source.replace(target, replacement) + mod = types.ModuleType(f"texture_blocks_mut_{label}") + mod.__file__ = str(TOOL) + sys.modules[mod.__name__] = mod + try: + exec(compile(mutated_src, str(TOOL), "exec"), mod.__dict__) + check_fn(mod) + finally: + sys.modules.pop(mod.__name__, None) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/upload_reservation_check.cpp b/tests/upload_reservation_check.cpp index 9b84a3b4d0..075e38f685 100644 --- a/tests/upload_reservation_check.cpp +++ b/tests/upload_reservation_check.cpp @@ -64,6 +64,51 @@ void check_ring_reuse() check(!reuse_upload_chunk(chunk, 0, bytes, queues).mapped, "untracked submit prevents reuse"); } +// X2W_D3D12_RING_RELEASE_AT_SUBMIT=1 bookkeeping: a closed list stops holding its chunks once its submit is fenced, +// the fence alone then guards the chunks, and a later submit of the same list before its Reset fences the intact +// chunks again and reports the reused ones. +void check_release_at_submit() +{ + constexpr std::uint64_t bytes = 4 * kAlign; + unsigned char storage[2][bytes]; + std::array chunks{}; + UploadChunkMask recording = 0; + for (unsigned i = 0; i < chunks.size(); ++i) { + chunks[i] = {nullptr, storage[i], bytes}; + check(reserve_upload_chunk(chunks[i], bytes).mapped != nullptr, "release: fill chunk"); + chunks[i].hold(recording, i); + } + + TestFence fence; + std::map> queues{{0, {&fence, 1}}}; + queues[0].submitted(recording, true); + check(!reuse_upload_chunk(chunks[0], 0, bytes, queues).mapped, "release: a closed list holds until released"); + + ReleasedUploadChunks released; + release_upload_chunks_at_submit(recording, chunks.data(), released); + check(recording == 0 && chunks[0].recordings == 0 && chunks[1].recordings == 0, "release: holds dropped"); + check(released.chunks == 3 && released.generation[0] == 0 && released.generation[1] == 0, + "release: chunks and generations recorded"); + check(!reuse_upload_chunk(chunks[0], 0, bytes, queues).mapped, "release: the fence still guards the chunk"); + + fence.value = 1; + const auto reused = reuse_upload_chunk(chunks[0], 0, bytes, queues); + check(reused.mapped == storage[0] && reused.generation == 1, "release: chunk reused after the fence"); + + UploadChunkMask recycled = UINT32_MAX; + const auto intact = resubmitted_upload_chunks(released, chunks.data(), recycled); + check(intact == 2 && recycled == 1, "release: a resubmit finds chunk 1 intact and chunk 0 reused"); + + ++queues[0].value; + queues[0].submitted(intact, true); + check(!reuse_upload_chunk(chunks[1], 1, bytes, queues).mapped, "release: the resubmit fences the intact chunk"); + fence.value = 2; + check(reuse_upload_chunk(chunks[1], 1, bytes, queues).mapped != nullptr, + "release: the intact chunk is reused after the resubmit's fence"); + check(resubmitted_upload_chunks(released, chunks.data(), recycled) == 0 && recycled == 3, + "release: both chunks reported once reused"); +} + } // namespace int main() @@ -111,6 +156,7 @@ int main() "existing reservations survive exhaustion"); check_ring_reuse(); + check_release_at_submit(); std::puts("upload_reservation_check: all checks passed"); return 0; } diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index 2ed0625dfb..703a8e81ec 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -322,9 +322,14 @@ def read(index, reg, name): if op in LDS_SHARED_ATOMICS: place(single) (value,) = words_of(data, 1) - if op == "sub_u32": - value = f"(0u - {value})" method = LDS_SHARED_ATOMICS[op] + if op == "sub_u32": + # mem - v == mem + ~v + 1 (mod 2^32), as two additions. One InterlockedAdd of (0u - v) on groupshared + # memory fails compute PSO creation with E_OUTOFMEMORY on NVIDIA GeForce RTX 5080 (driver + # 32.0.16.2124); DXC folds every spelling of the negation to `sub i32 0, v`. The update has no + # return value and the step ends with a barrier, so the intermediate word is never read. + statements.append(f" if ({base} < {words}u) InterlockedAdd(lds[{base}], ~({value}));") + value = "1u" statements.append(f" if ({base} < {words}u) Interlocked{method}(lds[{base}], {value});") return "\n".join(statements) count = int(m["bits"]) // 32 diff --git a/tools/ffx_version_query.py b/tools/ffx_version_query.py index 713619abd9..6846c594a0 100644 --- a/tools/ffx_version_query.py +++ b/tools/ffx_version_query.py @@ -599,6 +599,7 @@ def lower(body, initial, globals_, calls, exits, *, host_ops=None, x87=False, ho M.SHUFPS, M.UNPCKHPS, M.UNPCKLPS, M.MOVHLPS, M.MOVLHPS, M.MOVMSKPS, M.MOVUPS, M.MOVAPS, M.RCPPS, M.RCPSS, M.RSQRTPS, M.RSQRTSS, M.SHUFPD, M.UNPCKHPD, M.UNPCKLPD, M.MOVMSKPD, M.MOVUPD, M.MOVAPD, M.MOVDQA, + M.MOVNTPS, M.MOVNTPD, M.MOVNTDQ, M.VSHUFPS, M.VUNPCKHPS, M.VUNPCKLPS, M.VSHUFPD, M.VUNPCKHPD, M.VUNPCKLPD, M.VPSHUFD, M.VPSHUFHW, M.VPSHUFLW, M.VMOVHLPS, M.VMOVLHPS, M.VMOVMSKPS, M.VMOVMSKPD, M.VMOVAPS, M.VMOVAPD, M.VMOVDQA, M.VPMOVMSKB, M.VRCPPS, M.VRCPSS, M.VRSQRTPS, M.VRSQRTSS, @@ -923,6 +924,12 @@ def write_register(dest, expr): stmt = f"{decrement} if ({count} != 0{condition}) goto block_{target:x};" elif op in (M.MOV, M.MOVZX): stmt = write(operand(1)) + elif op == M.MOVNTI and i.op0_kind == K.MEMORY and i.op1_kind == K.REGISTER: + # A non-temporal store of a 32- or 64-bit register, with no alignment requirement and no flag change. + if MemorySizeExt.size(i.memory_size) == 8: + stmt = f"_mm_stream_si64(reinterpret_cast({address()}), static_cast({operand(1)}));" + else: + stmt = f"_mm_stream_si32(reinterpret_cast({address()}), static_cast({operand(1)}));" elif op == M.MOVSXD: stmt = write(f"int64_t(int32_t({operand(1)}))") elif op == M.MOVSX: @@ -2564,6 +2571,16 @@ def _lane_copy(sel, out_off): f"memcpy(reinterpret_cast(target), {wide_xmm[i.op1_register]}.data(), 16); }}") else: raise ValueError(f"unsupported aligned SSE move form at {i.ip:#x}: {i}") + elif op in (M.MOVNTPS, M.MOVNTPD, M.MOVNTDQ) and i.encoding == EncodingKind.LEGACY and has_wide: + # Non-temporal stores of a whole XMM register. Like MOVAPS, a target that is not 16-byte aligned + # raises #GP(0) before anything is written. The streaming store keeps the non-temporal hint; its weak + # ordering is the guest's own (only an SFENCE, MFENCE or locked instruction orders it). + if i.op0_kind == K.MEMORY and i.op1_kind == K.REGISTER and i.op1_register in wide_xmm: + stmt = (f"{{ const word target = {address()}; if (target & 15u) raise_aligned_m128_fault(); " + f"__m128i value; memcpy(&value, {wide_xmm[i.op1_register]}.data(), 16); " + f"_mm_stream_si128(reinterpret_cast<__m128i*>(target), value); }}") + else: + raise ValueError(f"unsupported non-temporal SSE store form at {i.ip:#x}: {i}") elif op in (M.MOVUPS, M.MOVUPD) and has_wide: is_vex = i.encoding == EncodingKind.VEX if i.op0_kind == K.REGISTER and i.op0_register in wide_xmm and i.op1_kind == K.MEMORY: diff --git a/tools/host_commit.py b/tools/host_commit.py index 8bdf263d84..1c5576bf92 100644 --- a/tools/host_commit.py +++ b/tools/host_commit.py @@ -4,10 +4,17 @@ amount of free physical RAM. This is a snapshot, not a reservation. """ +from collections.abc import Mapping import ctypes as C import sys MIB = 1 << 20 +_SNAPSHOT_KEYS = ("available_bytes", "limit_mib", "used_mib", "available_mib") + + +def _is_int(value): + """Return True only for exact integers, excluding bool.""" + return isinstance(value, int) and not isinstance(value, bool) class PerformanceInformation(C.Structure): @@ -33,10 +40,12 @@ class PerformanceInformation(C.Structure): def snapshot_from_pages(limit_pages, used_pages, page_size): """Pure conversion of GetPerformanceInfo page counts; never wrap under pressure.""" - if not page_size or not limit_pages: + if not _is_int(page_size) or page_size <= 0 or not _is_int(limit_pages) or limit_pages <= 0: raise ValueError("Windows reported an invalid commit page size or limit") - limit_bytes = int(limit_pages) * int(page_size) - used_bytes = int(used_pages) * int(page_size) + if not _is_int(used_pages) or used_pages < 0: + raise ValueError("Windows reported an invalid commit used page count") + limit_bytes = limit_pages * page_size + used_bytes = used_pages * page_size free_bytes = max(limit_bytes - used_bytes, 0) return {"limit_mib": limit_bytes // MIB, "used_mib": used_bytes // MIB, "available_mib": free_bytes // MIB, "available_bytes": free_bytes} @@ -60,8 +69,16 @@ def read_host_commit(): def require_commit_budget(minimum_mib, snapshot): """Reject a requested budget before any guest module is mapped or started.""" - if not isinstance(minimum_mib, int) or minimum_mib < 0 or minimum_mib > 1 << 20: + if not _is_int(minimum_mib) or minimum_mib < 0 or minimum_mib > 1 << 20: raise ValueError("--min-commit-mib must be between 0 and 1048576") + if not isinstance(snapshot, Mapping): + raise ValueError("commit snapshot must be a Mapping") + for key in _SNAPSHOT_KEYS: + if key not in snapshot: + raise ValueError(f"commit snapshot is missing required field: {key}") + value = snapshot[key] + if not _is_int(value) or value < 0: + raise ValueError(f"commit snapshot field {key} must be a non-negative integer") if snapshot["available_bytes"] < minimum_mib * MIB: raise ValueError( f"Windows system commit headroom {snapshot['available_mib']} MiB is below the " diff --git a/tools/import_routing.py b/tools/import_routing.py index b4ed416d7f..42e2d08eb0 100644 --- a/tools/import_routing.py +++ b/tools/import_routing.py @@ -4,6 +4,8 @@ prove a provider, or load the image. """ +from collections.abc import MutableMapping + POLICY_VERSION = 2 ROUTE_KIND = "candidate" RESOLUTION = "not_checked" @@ -61,8 +63,17 @@ } +def _validate_module(module): + """Reject non-str, empty, whitespace, or control-character module names.""" + if not isinstance(module, str): + raise ValueError(f"module name must be a str, got {type(module).__name__}") + if not module or any(ch.isspace() or ord(ch) < 0x20 or 0x7F <= ord(ch) <= 0x9F for ch in module): + raise ValueError(f"invalid module name: {module!r}") + + def classify(module): """Return (route, reason) for a module name. No route is inferred.""" + _validate_module(module) name = module.lower() if name in POLICY["hle"]: return "hle", POLICY["hle"][name] @@ -82,6 +93,10 @@ def annotate(row, module_key="module"): The caller keeps its own caller and symbol fields. No provider or export resolution is recorded. """ + if not isinstance(row, MutableMapping): + raise TypeError(f"row must be a MutableMapping, got {type(row).__name__}") + if module_key not in row: + raise KeyError(module_key) module = row[module_key] route, reason = classify(module) row.update({ diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index bb30bdf3cb..fad77b98e2 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -79,7 +79,28 @@ def _bounded_code(image, start): return image[start:end] -def _check_two_exits(code, llvm, *, cpu, features, mesh=False): +def _calculated_early_out(code, instructions): + """Cross-check the decoded extent and instruction inventory before accepting a calculated continuation.""" + if not any(line.startswith("s_getpc_b64 ") for line in instructions.values()): + return None + # gfx2hlsl imports pixel_aot symbols lazily too. + from startup import gfx2hlsl as G + ins = G.decode(code) + if [(off, name) for off, _n, name, _asm in ins] != [(off, line.split()[0]) for off, line in instructions.items()]: + raise ValueError("Calculated early-out: LLVM and the repository decoder disagree on the instruction inventory") + if ins[-1][0] + ins[-1][1] != len(code): + raise ValueError("Calculated early-out: the decoded instructions do not consume the bounded span") + try: + calculated = G.calculated_pc_proof(ins, None) + profile = G.terminal_continuation_proof(ins, calculated) + except G.Unsupported as reason: + raise ValueError(str(reason)) from None + if profile is None: + raise ValueError("Calculated early-out: no proven transfer onto a terminating continuation") + return profile + + +def _check_two_exits(code, llvm, *, cpu, features, mesh=False, early_out=False): """Both decoded exits must be reachable from the single entry.""" instructions = dict(disassemble(code, llvm, offsets=True, cpu=cpu, features=features)) exits = [pc for pc, line in instructions.items() if line == "s_endpgm"] @@ -90,6 +111,7 @@ def _check_two_exits(code, llvm, *, cpu, features, mesh=False): mesh_alloc = "s_sendmsg sendmsg(MSG_GS_ALLOC_REQ)" if mesh and mesh_alloc not in instructions.values(): raise ValueError("Unverified multi-exit program: missing mesh allocation") + early_out = _calculated_early_out(code, instructions) if early_out and not mesh else None # An aligned word can be a literal or the second half of an instruction. # Follow branches only from decoded PCs and reject unresolved transfers. pcs = list(instructions) @@ -112,17 +134,22 @@ def _check_two_exits(code, llvm, *, cpu, features, mesh=False): pending.append(target) if op == "s_branch": continue - elif not ((mesh and instructions[pc] in ("s_barrier", mesh_alloc)) - or op.startswith(("v_", "image_", "buffer_", "tbuffer_", "ds_", "flat_", "global_", - "scratch_", "exp", "s_load_", "s_buffer_load_", "s_cmp", "s_bitcmp", - "s_mov_", "s_and", "s_or_", "s_xor_", "s_not_", "s_lsh", "s_ash", - "s_add", "s_sub", "s_mul", "s_min_", "s_max_", "s_cselect", "s_bfe", - "s_bfm", "s_brev", "s_ff", "s_bcnt", "s_wqm", "s_quadmask")) - or op in ("s_nop", "s_version", "s_inst_prefetch", "s_waitcnt", "s_clause", "s_delay_alu", - "s_setprio", "s_sleep", "s_movk_i32", "s_cmovk_i32", "s_mulk_i32", - "s_flbit_i32_b32", "s_abs_i32", "s_cmov_b32", "s_bitset0_b32", "s_bitset1_b32", - "s_bitreplicate_b64_b32", "s_bitset0_b64", "s_bitset1_b64", - "s_setreg_imm32_b32", "s_setreg_b32", "s_getreg_b32")): + elif early_out is not None and pc == early_out[0]: + targets.add(early_out[1]) + pending.append(early_out[1]) + continue + elif not (early_out is not None and pc in early_out[2]) and not ( + (mesh and instructions[pc] in ("s_barrier", mesh_alloc)) + or op.startswith(("v_", "image_", "buffer_", "tbuffer_", "ds_", "flat_", "global_", + "scratch_", "exp", "s_load_", "s_buffer_load_", "s_cmp", "s_bitcmp", + "s_mov_", "s_and", "s_or_", "s_xor_", "s_not_", "s_lsh", "s_ash", + "s_add", "s_sub", "s_mul", "s_min_", "s_max_", "s_cselect", "s_bfe", + "s_bfm", "s_brev", "s_ff", "s_bcnt", "s_wqm", "s_quadmask")) + or op in ("s_nop", "s_version", "s_inst_prefetch", "s_waitcnt", "s_clause", "s_delay_alu", + "s_setprio", "s_sleep", "s_movk_i32", "s_cmovk_i32", "s_mulk_i32", + "s_flbit_i32_b32", "s_abs_i32", "s_cmov_b32", "s_bitset0_b32", "s_bitset1_b32", + "s_bitreplicate_b64_b32", "s_bitset0_b64", "s_bitset1_b64", + "s_setreg_imm32_b32", "s_setreg_b32", "s_getreg_b32")): raise ValueError(f"Unverified multi-exit control flow: {op}") pending.append(following[pc]) # A direct branch may skip alignment NOPs. Keep them in the original span. @@ -189,8 +216,9 @@ def container_code(program, *, stage, llvm=None, cpu=b"gfx1013", features=b""): if markers == 1: return code mesh = stage == 13 and cpu == b"gfx1013" and features == MESH_WAVE64 + pixel = stage == 0 and cpu == b"gfx1013" and not features if (stage in (0, 5) or mesh) and markers == 2 and llvm is not None: - _check_two_exits(code, llvm, cpu=cpu, features=features, mesh=mesh) + _check_two_exits(code, llvm, cpu=cpu, features=features, mesh=mesh, early_out=pixel) return code raise ValueError("Unverified multi-exit program") # Older fixtures lack the section extent; preserve their unique-marker rule. diff --git a/tools/run_checks_parallel.py b/tools/run_checks_parallel.py index 45a71459d0..2c1d702ee6 100644 --- a/tools/run_checks_parallel.py +++ b/tools/run_checks_parallel.py @@ -29,6 +29,11 @@ SKIP_EXIT_CODE = 77 +def _command_key(command): + """Return a comparison key with the script path resolved to collapse spelling variants.""" + return (str(Path(command[0]).resolve()), *command[1:]) + + def _validate_script_path(raw_path: str) -> str: if not raw_path or not raw_path.strip(): raise ValueError("script path must not be empty") @@ -109,7 +114,7 @@ def read_check_files(directory): _validate_script_path(command[0]) except (ValueError, OSError) as exc: raise type(exc)(f"{where}: {exc}") from exc - key = tuple(command) + key = _command_key(command) if key in seen: raise ValueError(f"{where}: duplicate of {seen[key]}: {line}") seen[key] = where @@ -124,9 +129,9 @@ def merge_checks(inline, directory): list to a file without running twice. The listed commands keep their sorted file order. """ inline = list(inline) - known = {tuple(command) for command, _ in inline} + known = {_command_key(command) for command, _ in inline} return inline + [(command, {}) for command in read_check_files(directory) - if tuple(command) not in known] + if _command_key(command) not in known] def run_one(check): @@ -184,9 +189,12 @@ def main(argv=None) -> int: parser.error("the following arguments are required: scripts (or --from-dir)") try: scripts = [_validate_script_path(script) for script in args.scripts] - for number, script in enumerate(scripts): - if script in scripts[:number]: + seen_scripts = set() + for script in scripts: + key = _command_key([script]) + if key in seen_scripts: raise ValueError(f"duplicate command-line script: {script}") + seen_scripts.add(key) checks = [([script], None) for script in scripts] if args.from_dir: checks = merge_checks(checks, args.from_dir) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index fcddc6cec9..0d3243d868 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -492,7 +492,7 @@ def check_encoding(code, off, n, name, asm): word0, word1 = struct.unpack_from('<2I', code, off) if word0 & 0x700 or word1 & 0xe0000000: raise Unsupported('%s with neg/abs: not a 16-bit integer source modifier' % name) - if name in ('v_sad_u8', 'v_sad_hi_u8', 'v_sad_u16', 'v_sad_u32', 'v_msad_u8', *VOP3_ONLY_VEC_U): + if name in ('v_lerp_u8', 'v_perm_b32', 'v_sad_u8', 'v_sad_hi_u8', 'v_sad_u16', 'v_sad_u32', 'v_msad_u8', *VOP3_ONLY_VEC_U): # VOP3A integer forms take no source abs/neg; refuse those bits here so neg on an inline # integer does not print as -N and get accepted as a negative constant. word0, word1 = struct.unpack_from('<2I', code, off) @@ -500,6 +500,12 @@ def check_encoding(code, off, n, name, asm): raise Unsupported('%s with neg/abs' % name) if name in VOP3_ONLY_VEC_U and (word1 >> 18) & 0x1ff: raise Unsupported('%s with unused src2 field set' % name) + if name.removesuffix('_e64') == 'v_ldexp_f32': + word0, word1 = struct.unpack_from('<2I', code, off) + if word0 & 0x600 or word1 & 0xc0000000: + raise Unsupported('%s with neg/abs on exponent or unused source' % name) + if (word1 >> 18) & 0x1ff: + raise Unsupported('%s with unused src2 field set' % name) if name == 'v_cvt_off_f32_i4_e64': # Integer-nibble conversion: the instruction has one source, so only src0's VOP3A ABS (w0[8]) and NEG # (w1[29]) can carry a modifier. Masking all three bit positions of each field (w0[10:8], w1[31:29]) @@ -549,6 +555,8 @@ def check_encoding(code, off, n, name, asm): float_sources = VEC_F[base][0] elif re.fullmatch(r'v_cmpx?_\w+_f32', base): float_sources = 1 if base in ('v_cmp_class_f32', 'v_cmpx_class_f32') else 2 + elif base == 'v_ldexp_f32': + float_sources = 1 rewritten = {} for i in range(3): if name == 'v_cndmask_b32_e64' and i < 2 or not word1 & (1 << (29 + i)): @@ -846,8 +854,9 @@ def scalar_effects(name, asm): may |= EXEC_KEYS if (base in SCA and SCA[base][1]) or 'saveexec' in base or 'wrexec' in base: writes.add('scc') - # A wave64 compare or carry-out prints its mask destination in the 32-bit spelling vcc_lo but writes vcc_hi too. - if 'vcc' in writes and base.startswith(('v_cmp', 'v_add_co', 'v_sub_co', 'v_subrev_co', 'v_div_scale')): + # Wave64 compare and carry-out instructions print vcc_lo but may also write vcc_hi. + if 'vcc' in writes and base.startswith(('v_cmp', 'v_add_co', 'v_sub_co', 'v_subrev_co', 'v_div_scale', + 'v_mad_u64_u32')): may.add('vcc_hi') return reads, writes, writes | may | ({'scc'} if base.startswith('s_') else set()) @@ -887,6 +896,12 @@ def names_one_value(sym): return sym[0] in ('const', 'ud', 'execcopy') or (sym[0] in ('ptr', 'ptrhi') and len(sym) == 2) +def descriptor_select(sym): + """True for what Stage.scalar_select records for a compute s_cselect_b32 with a descnum arm: + ('descnum', 'cselect', select offset, arm, arm). It has no run-time value, so no consumer may read it as one.""" + return bool(sym) and sym[:2] == ('descnum', 'cselect') + + def scalar_destinations(name, asm): """The SGPRs (and 'm0') an instruction may write; 'any' for s_movrel*, whose register comes from m0.""" if name.startswith(NO_SCALAR_DESTINATION) or '_store' in name: @@ -1363,6 +1378,81 @@ def clobber(written): return lowered +TERMINAL_NOP_NAMES = ('s_nop', 'v_nop') + + +def terminal_continuation_proof(ins, calculated): + """Prove a single calculated forward transfer onto a pure terminating continuation in a two-exit program.""" + transfers = [(off, target) for off, target in calculated.items() if target is not None] + ends = [off for off, _, name, _ in ins if name == 's_endpgm'] + if len(transfers) != 1 or len(ends) != 2: + return None + setpc, target = transfers[0] + if target <= setpc: + raise Unsupported('far early-out: the calculated continuation target %#x is not forward' % target) + by_off = {off: (n, name, asm) for off, n, name, asm in ins} + if setpc not in by_off: + raise Unsupported('far early-out: the calculated transfer is not a decoded instruction') + # GETPC, ADD, ADDC and SETPC must be contiguous; a literal ADD occupies eight bytes. + elided = sorted(off for off in calculated if off < setpc) + chain = list(elided[-3:]) + [setpc] + if (len(elided) != 3 or any(off not in by_off for off in chain) + or chain[0] + by_off[chain[0]][0] != chain[1] or chain[1] + by_off[chain[1]][0] != chain[2] + or chain[2] + by_off[chain[2]][0] != chain[3]): + raise Unsupported('far early-out: the documented GETPC/ADD/ADDC/SETPC chain is not contiguous') + get_n, _, get_asm = by_off[chain[0]] + _, add_name, add_asm = by_off[chain[1]] + _, addc_name, addc_asm = by_off[chain[2]] + set_n, _, set_asm = by_off[chain[3]] + get_ops, get_mods = parse(get_asm)[1:] + add_ops, add_mods = parse(add_asm)[1:] + addc_ops, addc_mods = parse(addc_asm)[1:] + set_ops, set_mods = parse(set_asm)[1:] + pair = pc_pair(get_ops[0]) if len(get_ops) == 1 and not get_mods and get_n == 4 else None + if (pair is None or set_ops != ['s[%d:%d]' % (pair, pair + 1)] or set_mods or set_n != 4 + or add_name != 's_add_u32' or addc_name != 's_addc_u32'): + raise Unsupported('far early-out: the calculated transfer does not use the documented chain form') + displacement = pc_word(add_ops[2]) if len(add_ops) == 3 and add_ops[0] == add_ops[1] == 's%d' % pair and not add_mods else None + extension = pc_word(addc_ops[2]) if len(addc_ops) == 3 and addc_ops[0] == addc_ops[1] == 's%d' % (pair + 1) and not addc_mods else None + if displacement is None or extension is None or extension != (-1 if displacement < 0 else 0): + raise Unsupported('far early-out: the displacement is not a complete constant with its matching sign extension') + if target != chain[0] + get_n + displacement: + raise Unsupported('far early-out: the proven target disagrees with the chain displacement') + # An ordinary definition of either scratch register would outlive the elided chain. + for off, _n, name, asm in ins: + if off in calculated: + continue + if {pair, pair + 1} & scalar_registers(asm): + raise Unsupported('far early-out: the scratch pair s[%d:%d] is not fresh' % (pair, pair + 1)) + branch_targets = set() + for off, _n, name, asm in ins: + if name == 's_setpc_b64': + to = calculated.get(off) + elif name.startswith('s_cbranch') or name == 's_branch': + to = int(parse(asm)[1][0].split('_')[1], 16) + else: + continue + if to is not None: + branch_targets.add(to) + for off in chain[1:]: + if off in branch_targets: + raise Unsupported('far early-out: a branch enters the chain interior at +0x%x' % off) + # Even exp null with vm may change pixel validity; only observable no-op instructions are admitted. + at = target + while at in by_off: + _n, name, asm = by_off[at] + if name in TERMINAL_NOP_NAMES: + at += 4 + continue + if name == 's_endpgm': + if asm != 's_endpgm' or at != ends[-1]: + raise Unsupported('far early-out: the continuation ends at +0x%x, not the program\'s final exit' + % at) + return setpc, target, tuple(chain) + raise Unsupported('far early-out: the continuation instruction %s is not a pure terminating no-op' % asm.split()[0]) + raise Unsupported('far early-out: the continuation leaves the decoded program before ending') + + def _lds_single(tok): """Single hardware VGPR vN (v0..v255) for bounded LDS exchange validation.""" m = re.fullmatch(r'v(\d+)', tok) @@ -2293,6 +2383,7 @@ def __init__(self, pipe, kind, code, refusals=None, decoded=None): first_refusal = len(refusals) if refusals is not None else 0 while True: self.lines = [] # body statements (per block) + self.vconst = {} # VGPR -> literal 32-bit value while the program is straight-line self.sym = {} # scalar register -> symbolic value self.used_s, self.used_v = set(), set() self.used_atomic = set() @@ -2512,7 +2603,7 @@ def f(self, tok): text = 'F(%s)' % self.u(tok) if absolute: text = 'abs(%s)' % text - return '(-%s)' % text if neg else text + return ('(-(%s))' % text) if (neg and text.startswith('-')) else ('(-%s)' % text if neg else text) def is_const(self, n): s = self.sym.get(n) @@ -2707,6 +2798,13 @@ def record_v_write(self, n, *, low16_only=False, align4=False): def set_v(self, n, expr, *, low16_only=False, align4=False): self.record_v_write(n, low16_only=low16_only, align4=align4) self.last_v = (n, expr) + vconst = getattr(self, 'vconst', None) + if isinstance(vconst, dict): + literal = re.fullmatch(r'0x([0-9a-fA-F]{8})u', expr) + if literal: + vconst[n] = int(literal.group(1), 16) + else: + vconst.pop(n, None) self.emit('v%d = %s;' % (n, expr) if self.exec_known else 'if (exec & 1) v%d = %s;' % (n, expr)) temps = getattr(self, 'uniform_temps', None) if temps is not None: # a uniform load past the entry block (one()): every lane keeps the words @@ -2814,6 +2912,14 @@ def set_s(self, n, expr, sym=None, scc=None, uniform=None, align4=False): def descriptor(self, tok): """Resource key for a descriptor operand like s[8:11]: (source, byte offset or None).""" r = reg_range(tok) + held = self.select_word(tok) + if held is not None: + # Only the first word names the resource below; a select of descriptor data in any word (such as a + # size word zeroed on one arm) would be dropped, so the access refuses. + raise Unsupported('descriptor operand %s: s%d holds a select of descriptor data' % (tok, held)) + held = self.joined_word(tok) + if held is not None: + raise Unsupported('descriptor operand %s: s%d holds a word joined at a branch target' % (tok, held)) s = self.sym.get(r[1]) if r else None if r and r[0] == 's' and r[1] <= 107 and r[2] >= 106: if getattr(self, 'has_branches', False): @@ -2835,6 +2941,23 @@ def descriptor(self, tok): return s[1], None raise Unsupported('descriptor operand %s holds %s' % (tok, s)) + def select_word(self, tok): + """The first SGPR of operand tok that holds a select of descriptor data (descriptor_select), or None.""" + r = reg_range(tok) + if not r or r[0] != 's': + return None + return next((n for n in range(r[1], min(r[2], 105) + 1) if descriptor_select(self.sym.get(n))), None) + + def joined_word(self, tok): + """In compute, the first SGPR after the first word of operand tok that holds a value joined at a branch + target, or None. The paths bring different words there, a select of descriptor data possibly among them, + and the access names its resource by the first word only. A loop head joins the same way.""" + r = reg_range(tok) + if getattr(self, 'kind', None) != 'cs' or not r or r[0] != 's': + return None + return next((n for n in range(r[1] + 1, min(r[2], 105) + 1) + if (self.sym.get(n) or ('',))[0] == 'joined at a branch target'), None) + def heap_sampler(self, tok): """'qh[...]' when the four sampler words of tok came from one run-time sampler heap load.""" r = reg_range(tok) @@ -2857,6 +2980,59 @@ def const_words(self, tok): for n in range(r[1], r[2] + 1)] return None if any(w is None for w in words) else words + def sampler_join_shape(self, branches): + # A single forward SCC diamond, with all four final writes in each arm literal. + if (getattr(self, 'kind', None) != 'ps' or len(branches) != 2 or + not any(name in ('image_sample_l', 'image_sample_lz') for _, _, name, _ in self.ins)): + return None + (cond, taken), (skip, join) = sorted(branches) + if not cond < skip < taken < join: + return None + row = {off: (n, name) for off, n, name, _ in self.ins} + if (row[cond][1] not in ('s_cbranch_scc0', 's_cbranch_scc1') or + row[skip][1] != 's_branch' or skip + row[skip][0] != taken): + return None + literals = [set(), set()] + bases = set() + for off, _, name, asm in self.ins: + _, ops, mods = parse(asm) + if off < join and (writes_exec(name, ops) or (cond < off and name == 's_endpgm')): + return None + arm = 0 if cond < off < skip else 1 if taken <= off < join else None + if arm is not None: + dests = scalar_destinations(name, asm) + if 'any' in dests: + return None + literals[arm].difference_update(dests) + if (name == 's_mov_b32' and len(ops) == 2 and not mods and + re.fullmatch(r'(?:0x[0-9a-fA-F]+|\d+)', ops[1])): + literals[arm].update(dests) + if (off >= join and name in ('image_sample_l', 'image_sample_lz') and len(ops) == 4 + and 'dim:SQ_RSRC_IMG_2D' in mods): + r = reg_range(ops[3]) + if r and r[0] == 's' and r[2] == r[1] + 3 and r[2] <= 105: + regs = set(range(r[1], r[2] + 1)) + if all(regs <= written for written in literals): + bases.add(r[1]) + return cond, join, bases + + def joined_sampler_call(self, tex, operand, pair, uv, level, name): + for words in pair: + # Point-filtered normalized wrap/clamp, with an actual point mip filter. + w0, w1, w2, w3 = words + if (w0 & ~0x3f or (w0 & 7) not in (0, 2) or ((w0 >> 3) & 7) not in (0, 2) + or w1 & ~0xffffff or w2 != 1 << 26 or w3): + raise Unsupported('%s with unsupported joined sampler words' % name) + self.lod_sampler_words(name, words) + a, b = pair + base = reg_range(operand)[1] + k = next(i for i in range(4) if a[i] != b[i]) + self.used_s.add(base + k) + qa = self.pipe.sampler(a, lod_limits=True) + qb = self.pipe.sampler(b, lod_limits=True) + return '(s%d == 0x%08xu ? %s.SampleLevel(%s, %s, %s) : %s.SampleLevel(%s, %s, %s))' % ( + base + k, a[k], tex, qa, uv, level, tex, qb, uv, level) + def execz_refusals(self): """{offset: reason} for compute blocks that s_cbranch_execz skips and the one-lane model cannot run. @@ -3441,6 +3617,12 @@ def translate(self): raise refusals.append((str(reason), self.kind)) self.calculated_pc = {} + try: + terminal_continuation_proof(self.ins, self.calculated_pc) + except Unsupported as reason: + if refusals is None: + raise + refusals.append((str(reason), self.kind)) targets = set() targets.update(target for target in self.calculated_pc.values() if target is not None) # (branch, target) of every branch, the proven s_setpc_b64 jumps included @@ -3462,6 +3644,7 @@ def translate(self): execz_targets = set() if getattr(self, 'kind', None) == 'cs' else { t for t in targets if all(pc < t and names[pc] == 's_cbranch_execz' for pc, to in branches if to == t)} back_targets = {to for pc, to in branches if to <= pc} + sampler_diamond = self.sampler_join_shape(branches) if branches else None self.mesh_allocation_block = None splits = set(targets) if getattr(self, 'kind', None) == 'ms' and targets: @@ -3526,6 +3709,7 @@ def translate(self): self.address_carry_reader = None uniform_vcc_compares = set() self.lines = [] + self.vconst = {} self.blocks = [] # (offset, [lines], terminator) self.sym = dict(init_sym) self.exec_known = init_exec_known @@ -3592,6 +3776,7 @@ def translate(self): incoming = {} kept = {} self.back_force = {} + self.sampler_joins = {} written = set(init_written) falls = True start = 0 @@ -3641,6 +3826,19 @@ def translate(self): arriving = ([({reg: self.sym.get(reg) for reg in here}, written & here)] if falls else []) + \ incoming.get(off, []) written = (written - here) | set().union(*(w for _, w in arriving)) + self.sampler_joins.clear() + if (sampler_diamond and off == sampler_diamond[1] and falls and len(arriving) == 2 + and self.exec_known and self.uniform_cf and sampler_diamond[0] in self.uniform_branches): + for base in sampler_diamond[2]: + regs = range(base, base + 4) + if any(forced.get(off, {}).get(r) is not None for r in regs): + continue + if not all(all(r in w and s.get(r) and s[r][0] == 'const' and len(s[r]) == 2 + for r in regs) for s, w in arriving): + continue + pair = tuple(tuple(s[r][1] & 0xffffffff for r in regs) for s, _ in arriving) + if pair[0] != pair[1]: + self.sampler_joins[base] = pair for reg in here: paths = [s[reg] for s, w in arriving if reg in w] force = forced.get(off, {}).get(reg) @@ -3725,6 +3923,10 @@ def translate(self): reg, 'run' if run_time_symbol(sym) else 'refuse') falls = name not in ('s_branch', 's_setpc_b64', 's_endpgm') dests = scalar_destinations(name, asm) + if self.sampler_joins and dests: + for base in tuple(self.sampler_joins): + if 'any' in dests or any(r in dests for r in range(base, base + 4)): + del self.sampler_joins[base] written |= every_sgpr if 'any' in dests else dests last_write.update(dict.fromkeys(every_sgpr if 'any' in dests else dests, off)) self._pre_fconst = dict(self.float_const_s) @@ -4228,8 +4430,8 @@ def one(self, name, asm): reads, _, _ = scalar_effects(name, asm) if reads & {'vcc', 'vcc_hi'}: self.read_vcc() - # v_bfm_b32 exists only as VOP3 (opcode 0x363); a VOP2 spelling is not an instruction. - if name.endswith('_e32') and (name[:-4] in VOP3_ONLY_VEC_U or name[:-4] == 'v_bfm_b32'): + # v_bfm_b32 and v_ldexp_f32 exist only as VOP3; a VOP2 spelling is not an instruction. + if name.endswith('_e32') and (name[:-4] in VOP3_ONLY_VEC_U or name[:-4] in ('v_bfm_b32', 'v_ldexp_f32')): raise Unsupported(name) base = re.sub(r'_e(32|64)$', '', name) # Compute the proof before lowering, since a destination can also be a source. @@ -4835,6 +5037,14 @@ def _lower(self, base, asm, ops, mods): pipe = getattr(self, 'pipe', None) if pipe is not None and isinstance(getattr(pipe, 'uses_sad', None), set): pipe.uses_sad.add(base) + elif base == 'v_lerp_u8': + pipe = getattr(self, 'pipe', None) + if pipe is not None and hasattr(pipe, 'uses_lerp_u8'): + pipe.uses_lerp_u8 = True + elif base == 'v_perm_b32': + pipe = getattr(self, 'pipe', None) + if pipe is not None and hasattr(pipe, 'uses_perm_b32'): + pipe.uses_perm_b32 = True align4 = self.valu_align4(base, ops[1:1 + arity]) return self.set_v(reg_range(ops[0])[1], text.format(*args), align4=align4) if base in SCA: @@ -4931,7 +5141,7 @@ def dpp_broadcast(self, base, ops, mods): # proved whole-quad EXEC: the hardware can return 0 or the old value for a source lane whose EXEC bit # is off (an uncovered pixel of an edge quad), and the intrinsics have no such case. Other permutations, fi:1 without that proof, DPP8, row shifts and partial masks stay refused. def dpp(self, base, ops, mods): - if base in VOP3_ONLY_VEC_U: + if base in ('v_ldexp_f32', *VOP3_ONLY_VEC_U): raise Unsupported('DPP form of %s' % base) # fi:1 (fetch inactive, DPP16 dword bit 18; LLVM AMDGPU `fi`, Mesa ACO fetch_inactive) only decides what a # disabled source lane returns. Every lowering below is taken only with the whole quad proven active, so no @@ -5025,7 +5235,7 @@ def half_operand(self, tok, kind): text = 'f16tof32(%s & 0xffffu)' % self.u(tok) if absolute: text = 'abs(%s)' % text - return '(-%s)' % text if neg else text + return ('(-(%s))' % text) if (neg and text.startswith('-')) else ('(-%s)' % text if neg else text) def half_alu(self, base, ops, mods): """16-bit VALU: operands are the low 16 bits, the result fills the low 16 bits and zeroes the rest (RDNA 2).""" @@ -5107,7 +5317,7 @@ def sdwa_half(self, base, ops, mods): def sdwa(self, base, ops, mods): if base in ('v_add_f16', 'v_sub_f16', 'v_subrev_f16', 'v_mul_f16'): return self.sdwa_half(base, ops, mods) - if base in ('v_cvt_off_f32_i4', *VOP3_ONLY_VEC_U): + if base in ('v_cvt_off_f32_i4', 'v_ldexp_f32', *VOP3_ONLY_VEC_U): raise Unsupported('SDWA form of %s' % base) fields = {} out_mods = [] @@ -5384,6 +5594,7 @@ def src_sym(t): self.set_s(dst[1], '0u', ('const', 0), scc='false') return None raise Unsupported('TG_SIZE register s%d read outside s_and_b32 with 0xfc0' % tg_srcs[0]) + self.refuse_select_source(base, ops[1:]) # whole ranges: srcs names only the low word of a pair if any(s and s[0] in ('desc', 'descnum', 'ptr', 'ptrhi') for s in syms): if 'src_scc' in srcs and not getattr(self, 'scc_verified', False): raise Unsupported('src_scc with unverified SCC') @@ -5792,6 +6003,12 @@ def op_s_bitset0_b32(self, ops, mods): def op_s_bitset1_b32(self, ops, mods): return self.scalar_bitset(ops, mods, clear=False) + def op_s_bitset0_b64(self, ops, mods): + return self.scalar_bitset64(ops, mods, clear=True) + + def op_s_bitset1_b64(self, ops, mods): + return self.scalar_bitset64(ops, mods, clear=False) + def scalar_bitset(self, ops, mods, clear): """s_bitset0/1_b32: clear or set bit S0[4:0] of D in place; SCC unchanged. @@ -5840,6 +6057,74 @@ def scalar_bitset(self, ops, mods, clear): self.masks.discard(d) return None + def scalar_bitset64(self, ops, mods, clear): + """s_bitset0/1_b64: clear or set bit S0[5:0] of 64-bit pair D in place; SCC unchanged. + + RDNA 2 ISA SOP1 0x1c / 0x1e: bit 5 of S0 selects the high vs. low word of D, and + S0[4:0] selects the bit within that word. The destination pair is read-modify-write; + when S0 aliases the low word of D, the high word is updated first so S0 is read intact. + """ + name = 's_bitset%d_b64' % (0 if clear else 1) + if mods or len(ops) != 2: + raise Unsupported('%s with %d operands, expected 2 unmodified' % (name, len(ops))) + dst = reg_range(ops[0]) + if not dst or dst[0] != 's' or dst[2] != dst[1] + 1 or dst[1] % 2 != 0 or dst[2] > 105: + raise Unsupported('%s destination %s' % (name, ops[0])) + d = dst[1] + masks = getattr(self, 'masks', ()) + mask_high = getattr(self, 'mask_high', ()) + if self.is_lane_mask(ops[0]) or any(w in masks or w in mask_high for w in (d, d + 1)): + raise Unsupported('%s on a lane mask' % name) + imm = re.fullmatch(r'-?(0x[0-9a-fA-F]+|\d+)', ops[1]) + src_reg = None + if ops[1] == 'null': + index_imm = 0 + elif imm: + index_imm = int(ops[1], 0) & 63 + else: + src = reg_range(ops[1]) + if not src or src[0] != 's' or src[1] != src[2] or src[1] > 105: + raise Unsupported('%s source %s' % (name, ops[1])) + src_reg = src[1] + if self.is_lane_mask(ops[1]) or src_reg in masks or src_reg in mask_high: + raise Unsupported('%s on a lane mask' % name) + bit_sym = self.sym.get(src_reg) + if bit_sym and bit_sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('%s on %s data' % (name, bit_sym[0])) + index_imm = bit_sym[1] & 63 if bit_sym and bit_sym[0] == 'const' else None + for r in (d, d + 1): + sym = self.sym.get(r) + if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('%s on %s data' % (name, sym[0])) + if index_imm is not None: + target = d + (index_imm >> 5) + shift = index_imm & 31 + sym = self.sym.get(target) + if sym and sym[0] == 'const': + val = ((sym[1] & ~(1 << shift)) if clear else (sym[1] | (1 << shift))) & 0xffffffff + self.set_s(target, '0x%08xu' % val, ('const', val)) + else: + prev = self.S(target) + mask = '0x%08xu' % (1 << shift) + self.set_s(target, '(%s & ~%s)' % (prev, mask) if clear else '(%s | %s)' % (prev, mask)) + else: + prev_lo, prev_hi = self.S(d), self.S(d + 1) + bit = self.u(ops[1]) + mask = '(1u << (%s & 31u))' % bit + upd_lo = '(%s & ~%s)' % (prev_lo, mask) if clear else '(%s | %s)' % (prev_lo, mask) + upd_hi = '(%s & ~%s)' % (prev_hi, mask) if clear else '(%s | %s)' % (prev_hi, mask) + lo_expr = '((%s & 32u) == 0u ? %s : %s)' % (bit, upd_lo, prev_lo) + hi_expr = '((%s & 32u) != 0u ? %s : %s)' % (bit, upd_hi, prev_hi) + if src_reg == d: + self.set_s(d + 1, hi_expr) + self.set_s(d, lo_expr) + else: + self.set_s(d, lo_expr) + self.set_s(d + 1, hi_expr) + if hasattr(self, 'masks'): + self.masks.difference_update((d, d + 1)) + return None + def scalar_cmov(self, ops, mods, pair, name=None): """D = SCC ? S0 : D on plain SGPR destinations; SCC is unchanged.""" name = name or 's_cmov_b%d' % (64 if pair else 32) @@ -5873,6 +6158,16 @@ def scalar_select(self, ops, pair): low = [('s%d' % reg_range(t)[1]) if reg_range(t) and reg_range(t)[0] == 's' else t for t in ops] if pair and 'm0' in low: raise Unsupported('64-bit scalar operand m0') + r = reg_range(low[0]) + if not pair and getattr(self, 'kind', None) == 'cs' and r and r[0] == 's' and r[1] == r[2] <= 105: + # A select between descriptor-derived data (descnum, no run-time value) and constants, such as + # s_cselect_b32 sX, 0, sX, which can zero a buffer's size: record both arms and the offset whose SCC + # picks one. Nothing reads that symbol as a value (S, refuse_select_source, select_word), so neither + # arm is dropped. + arms = [self.select_arm(t) for t in low[1:]] + if None not in arms and any(arm[0] == 'descnum' for arm in arms): + self.set_s(r[1], None, ('descnum', 'cselect', self.pc, *arms)) + return expr = 'scc ? %s : %s' % (self.u(low[1]), self.u(low[2])) if low[0] == 'm0': self.sym.pop('m0', None) @@ -5894,6 +6189,28 @@ def scalar_select(self, ops, pair): self.masks.add(d) self.set_s(d + 1, '0u') + def select_arm(self, tok): + """An s_cselect_b32 source as a symbol: the descnum a register holds, ('const', value) for a literal or a + register holding a known constant, otherwise None.""" + r = reg_range(tok) + if r: + sym = self.sym.get(r[1]) if r[0] == 's' and r[1] == r[2] and r[1] <= 105 else None + return sym if sym and (sym[0] == 'descnum' or sym[0] == 'const' and len(sym) == 2) else None + value = self.const_u32(tok) + return None if value is None else ('const', value) + + def refuse_select_source(self, base, srcs): + """A scalar ALU source holding a select of descriptor data in any of its registers (the high word of a pair + too): a move copies the symbol, anything else would turn it into an unrelated descnum or descriptor edit, + losing the arm that SCC picks, so it refuses.""" + if base in ('s_mov_b32', 's_mov_b64'): + return + for tok in srcs: + r = reg_range(tok) + regs = ['m0'] if tok == 'm0' else range(r[1], r[2] + 1) if r and r[0] == 's' else () + if any(descriptor_select(self.sym.get(n)) for n in regs): + raise Unsupported('%s on a select of descriptor data' % base) + def smem_soffset(self, tok, record_use=True): """Runtime expression for an SMEM scalar offset operand (s0..s105 or m0).""" if tok == 'm0': @@ -7205,13 +7522,15 @@ def image(self, ops, mods, how): raise Unsupported('image_sample_b with a per-lane bias past a divergent EXEC') bias, cs = cs[0], cs[1:] if how == 'get_lod': - # image_get_lod returns [0] the LOD a sample would use, clamped, and [1] the computed LOD before the clamp - # (Mesa nir_texop_lod, which ACO emits as image_get_lod; GLSL textureQueryLod x/y). Only the 2D form with - # two address registers and dmask 0x1-0x3 is lowered; the cache-policy bits are the only other modifiers. + # Mesa nir_texop_lod returns the clamped LOD followed by the computed LOD. + # DXIL CalculateLOD uses only spatial coordinates, including on Texture2DArray; + # the guest array form still consumes a third address register for the slice. for m in mods: if not (m.startswith(('dim:', 'dmask:')) or m in ('dlc', 'glc', 'slc')): raise Unsupported('image_get_lod modifier %s' % m) - if self.kind != 'ps' or dim != 'SQ_RSRC_IMG_2D' or not dmask or dmask & ~3 or len(cs) != 2: + want_addr = 3 if dim == 'SQ_RSRC_IMG_2D_ARRAY' else 2 + if (self.kind != 'ps' or dim not in ('SQ_RSRC_IMG_2D', 'SQ_RSRC_IMG_2D_ARRAY') or + not dmask or dmask & ~3 or len(cs) != want_addr): raise Unsupported('image_get_lod form %s %s' % (', '.join(ops), ' '.join(mods))) # Both HLSL calls take implicit derivatives, so the rule of image_sample_b applies. if not self.derivative_exec_ok() or not getattr(self, 'uniform_cf', True): @@ -7271,6 +7590,11 @@ def image(self, ops, mods, how): heap = self.heap_sampler(ops[3]) words = None if heap else self.const_words(ops[3]) name = 'image_sample' + ('' if how == 'sample' else '_' + how) + sjoin = None + if dim == 'SQ_RSRC_IMG_2D' and how in ('l', 'lz') and not packed_2d and not heap and words is None: + r = reg_range(ops[3]) + if r and r[0] == 's' and r[2] == r[1] + 3: + sjoin = getattr(self, 'sampler_joins', {}).get(r[1]) if how == 'b': # The guest clamps the biased LOD to the sampler's MIN_LOD and MAX_LOD. Only a constant descriptor # can be read here, and only its limits are carried to the static sampler (line smpl), so a sampler @@ -7283,6 +7607,8 @@ def image(self, ops, mods, how): if heap or not words or self.default_sampler_words(words): raise Unsupported('image_get_lod with a sampler that is not constant (LOD limits and bias unknown)') smp = self.pipe.sampler(tuple(self.lod_sampler_words('image_get_lod', words)), lod_limits=True) + elif sjoin is not None: + smp = None elif how in ('sample', 'l', 'lz', 'd') and (heap or (words and self.default_sampler_words(words))): # A heap sampler, or the fixed default that stands in for one, keeps its unbounded static LOD range: the # descriptor is read at run time, so its MIN_LOD, MAX_LOD and bias are not validated here (#2221). @@ -7301,7 +7627,7 @@ def image(self, ops, mods, how): uv = 'float2(f16tof32(%s), f16tof32(%s >> 16))' % (packed, packed) elif one: uv = self.f(cs[0]) - elif three: + elif three and how != 'get_lod': uv = 'float3(%s, %s, %s)' % (self.f(cs[0]), self.f(cs[1]), self.f(cs[2])) else: uv = 'float2(%s, %s)' % (self.f(cs[0]), self.f(cs[1])) @@ -7312,6 +7638,8 @@ def image(self, ops, mods, how): axes = len(grads[0]) dx, dy = ['float%d(%s)' % (axes, ', '.join(self.f(r) for r in g)) for g in grads] call = '%s.SampleGrad(%s, %s, %s, %s)' % (tex, smp, uv, dx, dy) + elif sjoin is not None: + call = self.joined_sampler_call(tex, ops[3], sjoin, uv, self.f(lod) if how == 'l' else '0', name) elif how == 'l': call = '%s.SampleLevel(%s, %s, %s)' % (tex, smp, uv, self.f(lod)) elif how == 'b': @@ -7320,8 +7648,7 @@ def image(self, ops, mods, how): # sample_b_sampler. call = '%s.SampleBias(%s, %s, %s)' % (tex, smp, uv, self.f(bias)) elif how == 'get_lod': - # HLSL CalculateLevelOfDetail (clamped) and CalculateLevelOfDetailUnclamped (SM 4.1+). Which clamps - # each side applies besides the sampler's (the view's mip range) is assumed to agree. + # The view mip-range clamp is assumed to agree on both sides. call = 'float4(%s.CalculateLevelOfDetail(%s, %s), %s.CalculateLevelOfDetailUnclamped(%s, %s), 0.0, 0.0)' % ( tex, smp, uv, tex, smp, uv) elif how == 'lz' or not self.exec_known or self.kind != 'ps': @@ -7500,17 +7827,128 @@ def fixed_table_image(self, operand, name): raise Unsupported('%s through a modified image descriptor' % name) return self.descriptor(operand) + def bvh_descriptor(self, tok): + """The binding key and literal words of an inline constant BVH T#. + + The table-name form and the run-time descriptor are deliberately outside this first slice: the + host binding for a T# read from a descriptor heap is not part of this change, and passing the + four words as uninitialized SGPRs would read address zero. A constant T# built by four s_mov_b32 + instructions is fully proved here, so the emitted helper receives literals and the manifest can + name the node allocation by its base and size. + """ + name = 'image_bvh_intersect_ray' + r = reg_range(tok) + if not r or r[0] != 's' or r[2] - r[1] != 3: + raise Unsupported('%s descriptor %s is not four consecutive SGPRs' % (name, tok)) + values = [self.is_const(n) for n in range(r[1], r[2] + 1)] + if any(value is None for value in values): + first = self.sym.get(r[1]) + if first and first[0] == 'desc': + raise Unsupported('%s descriptor %s is loaded at run time: only a constant inline T# is ' + 'lowered in this slice' % (name, tok)) + raise Unsupported('%s descriptor %s is not four constant SGPRs' % (name, tok)) + words = ['0x%08xu' % (value & 0xffffffff) for value in values] + base = ((values[1] & 0xff) << 32) | values[0] + return (('bvhbase', base, values[2]), None), words, values + + def op_image_bvh_intersect_ray(self, ops, mods): + """Ray/box intersection for the 128-byte FP32 box node (kind 5). + + RDNA 2 ISA section 8.2.10 and Table 48: VDATA is four result dwords, VADDR is 11 dwords + (node pointer, extent, origin xyz, direction xyz, inverse direction xyz) and SRSRC is the + four-word BVH T# of Table 49. This first slice accepts only a straight-line compute program + with a constant node base, a constant inline T# and a node whose kind bits are 5. + The descriptor base binds a ByteAddressBuffer at the 256-byte-aligned allocation; the node + pointer is an offset in 8-byte units from that base. The emitted helper performs the four + slab tests, clips against extent, compacts misses to 0xffffffff, and sorts by entry distance + only when the descriptor's box-sorting enable bit is set. Triangle nodes, 16-bit box nodes, + the 64-bit form, A16, non-sequential addresses and every other node kind are refused by name. + """ + name = 'image_bvh_intersect_ray' + if self.kind != 'cs': + raise Unsupported('%s outside a compute stage' % name) + if mods: + raise Unsupported('%s modifier %s' % (name, ' '.join(mods))) + if len(ops) != 3: + raise Unsupported('%s with %d operands, expected 3' % (name, len(ops))) + dst = reg_range(ops[0]) + if not dst or dst[0] != 'v' or dst[2] - dst[1] != 3 or dst[2] > 255: + raise Unsupported('%s destination %s is not four consecutive VGPRs' % (name, ops[0])) + if ops[1].startswith('['): + raise Unsupported('%s non-sequential address %s is not lowered' % (name, ops[1])) + addr = reg_range(ops[1]) + if not addr or addr[0] != 'v' or addr[2] > 255 or addr[2] - addr[1] + 1 not in (11, 16): + raise Unsupported('%s address %s is not an 11-dword VGPR range' % (name, ops[1])) + cs = ['v%d' % n for n in range(addr[1], addr[1] + 11)] + node = self.const_u32(cs[0]) + node_reg = reg_range(cs[0]) + if node is None and node_reg and node_reg[0] == 'v' and not getattr(self, 'has_branches', True): + node = getattr(self, 'vconst', {}).get(node_reg[1]) + if node is None: + raise Unsupported('%s non-constant node base %s' % (name, cs[0])) + kind = node & 7 + if kind == 4: + raise Unsupported('%s 16-bit box node (kind 4) is not lowered' % name) + if kind == 0: + raise Unsupported('%s triangle node (kind 0) is not lowered' % name) + if kind != 5: + raise Unsupported('%s node kind %d is not lowered' % (name, kind)) + node_offset = (node & 0xfffffff8) << 3 + if node_offset > 0xffffff80 or node_offset & 0x7f: + raise Unsupported('%s node base %#x is not an aligned 128-byte node' % (name, node_offset)) + key, words, vals = self.bvh_descriptor(ops[2]) + if vals[0] is not None and vals[0] & 0xff: + raise Unsupported('%s descriptor base is not 256-byte aligned' % name) + if vals[1] is not None: + if vals[1] & 0x7f800000: + raise Unsupported('%s box growing amount %d is not lowered' % (name, (vals[1] >> 23) & 0xff)) + if vals[1] & 0x007fff00: + raise Unsupported('%s descriptor reserved word 1 %#x' % (name, vals[1])) + if vals[3] is not None: + if (vals[3] >> 28) & 0xf != 8: + raise Unsupported('%s descriptor type %d is not 8' % (name, (vals[3] >> 28) & 0xf)) + if vals[3] & 0x0fffffff: + raise Unsupported('%s descriptor size above 4 GiB or reserved word 3 %#x' % (name, vals[3])) + if vals[0] is not None and vals[1] is not None and ((vals[1] & 0xff) << 32 | vals[0]) == 0: + raise Unsupported('%s absolute node base is not lowered' % name) + if vals[2] is not None: + if vals[2] < 1 or vals[2] >= 0x04000000: + raise Unsupported('%s descriptor size %d does not cover a 128-byte node' % (name, vals[2])) + if (node_offset >> 6) + 1 > vals[2]: + raise Unsupported('%s node base %#x is outside descriptor size %d' % (name, node_offset, vals[2])) + extent = self.f(cs[1]) + origin = [self.f(cs[2 + i]) for i in range(3)] + [self.f(cs[5 + i]) for i in range(3)] # the instruction consumes ray_dir; the helper uses inv_dir + inv_dir = [self.f(cs[8 + i]) for i in range(3)] + if vals[1] is not None: + sort = '0x80000000u' if vals[1] & 0x80000000 else '0x00000000u' + else: + sort = '(%s & 0x80000000u)' % words[1] + res = self.pipe.resource(key, 'bvh') + self.pipe.uses_bvh = True + call = 'x2w_bvh_intersect_box32(%s, 0x%08xu, %s, %s, %s, %s, %s, float3(%s, %s, %s), float3(%s, %s, %s))' % ( + res, node, words[0], sort, words[2], words[3], extent, + origin[0], origin[1], origin[2], inv_dir[0], inv_dir[1], inv_dir[2]) + self.emit('uint4 bt%x = %s;' % (self.pc or 0, call)) + for i in range(4): + self.set_v(dst[1] + i, 'bt%x.%s' % (self.pc or 0, 'xyzw'[i])) + + def op_image_bvh64_intersect_ray(self, ops, mods): + raise Unsupported('image_bvh64_intersect_ray: only the 32-bit image_bvh_intersect_ray is lowered') + def op_image_store(self, ops, mods): - """Write a full 2D texel or, for compute, a full 2D-array texel. + """Write a texel to a 2D or 2D-array image, or to a 1D or 3D compute image. MIMG opcode 0x08 (LLVM AMDGPU MIMGInstructions.td, IMAGE_STORE via MIMG_Store): VDATA is the - source, VADDR the integer texel address (x, y for dim 2D, x, y, layer for dim 2D-array) and SRSRC + source, VADDR the integer texel address (x; x, y; x, y, z; or x, y, layer) and SRSRC the image descriptor; the channels selected by DMASK are written in order from consecutive VDATA - registers. HLSL's typed UAV store writes every channel of the view, so only DMASK 0xf is exact here; - a partial mask would need a read-modify-write and is refused. The data is stored as float4, so the - bound view must be of a float or normalized format (the runtime side is not part of this lowering). - The store runs under the lane's exec bit, like the other per-lane writes, and D3D drops UAV writes - from helper lanes as the hardware drops them for lanes outside exec. + registers. A full DMASK 0xf is a direct float4 assignment. A partial pixel-stage mask writes only + those components (a swizzle store). It does not read the texel: a float4 read-modify-write would + store every channel, so two invocations that hit one texel with disjoint masks can put stale + values back, and the load needs a typed-UAV-load format. Compute, D16 and array stores still + require DMASK 0xf. The bound view must be a float or normalized format (the runtime side is not + part of this lowering). The store runs under the lane's exec bit, and D3D drops UAV writes from + helper lanes as the hardware drops them for lanes outside exec. """ name = 'image_store' if self.kind not in ('ps', 'cs'): @@ -7528,29 +7966,42 @@ def op_image_store(self, ops, mods): masks = [m[6:] for m in mods if m.startswith('dmask:')] if len(dims) != 1 or len(masks) != 1: raise Unsupported('%s without exactly one dim and dmask' % name) - array = dims[0] == 'SQ_RSRC_IMG_2D_ARRAY' - if dims[0] not in ('SQ_RSRC_IMG_2D', 'SQ_RSRC_IMG_2D_ARRAY'): - raise Unsupported('%s on %s: only 2D images are lowered' % (name, dims[0])) + shapes = { + 'SQ_RSRC_IMG_2D': ('tex2d', 2, 'x and y'), + 'SQ_RSRC_IMG_2D_ARRAY': ('tex2da', 3, 'x, y and layer'), + } + if self.kind == 'cs': + shapes.update({ + 'SQ_RSRC_IMG_1D': ('tex1d', 1, 'x'), + 'SQ_RSRC_IMG_3D': ('tex3d', 3, 'x, y and z'), + }) + if dims[0] not in shapes: + supported = '1D, 2D, 2D-array and 3D' if self.kind == 'cs' else '2D' + raise Unsupported('%s on %s: only %s images are lowered' % (name, dims[0], supported)) + kind, address, axes = shapes[dims[0]] + array = kind == 'tex2da' try: mask = int(masks[0], 0) except ValueError: raise Unsupported('%s with dmask %s: not an integer' % (name, masks[0])) from None - if mask != 0xf: + # Pixel 2D only. Compute, D16 and arrays keep the full-mask store. + sparse = self.kind == 'ps' and not array and not d16 and 0 < mask <= 0xf and mask != 0xf + if not sparse and mask != 0xf: raise Unsupported('%s with dmask %s: a typed UAV store writes all four channels' % (name, masks[0])) data = reg_range(ops[0]) - count = 2 if d16 else 4 + count = bin(mask).count('1') if sparse else (2 if d16 else 4) if not data or data[0] != 'v' or data[2] - data[1] + 1 != count or data[2] > 255: - raise Unsupported('%s data %s: %s VGPRs expected' % (name, ops[0], 'two' if d16 else 'four')) + raise Unsupported('%s data %s: %s VGPRs expected' % ( + name, ops[0], 'two' if d16 else ('four' if count == 4 else str(count)))) coords = ops[1] if coords.startswith('['): cs = [c.strip() for c in coords[1:-1].split(',')] else: r = reg_range(coords) cs = ['v%d' % n for n in range(r[1], r[2] + 1)] if r and r[0] == 'v' else [] - address = 3 if array else 2 if len(cs) != address: raise Unsupported('%s with %d address registers: %s expected' - % (name, len(cs), 'x, y and layer' if array else 'x and y')) + % (name, len(cs), axes)) words = [self.u('v%d' % n) for n in range(data[1], data[2] + 1)] if self.kind == 'cs': if not all(re.fullmatch(r'v\d+', c) and int(c[1:]) <= 255 for c in cs): @@ -7558,15 +8009,23 @@ def op_image_store(self, ops, mods): key = self.fixed_table_image(ops[2], name) else: key = self.descriptor(ops[2]) + image = self.pipe.uav(key, kind) + index_type = 'uint' if address == 1 else 'uint%d' % address + index = '%s(%s)' % (index_type, ', '.join(self.u(c) for c in cs)) if d16: # RDNA 2 ISA §8.2.5: RG occupy VDATA, BA occupy VDATA+1, low half first. rgba = ['f16tof32(%s & 0xffffu), f16tof32(%s >> 16)' % (word, word) for word in words] value = 'float4(%s)' % ', '.join(rgba) + body = '%s[%s] = %s;' % (image, index, value) + elif sparse: + # Selected components only, in VDATA order. No texel read. + comps = [channel for bit, channel in enumerate('xyzw') if mask & (1 << bit)] + swizzle = ''.join(comps) + values = ', '.join('asfloat(%s)' % word for word in words) + rhs = values if len(comps) == 1 else 'float%d(%s)' % (len(comps), values) + body = '%s[%s].%s = %s;' % (image, index, swizzle, rhs) else: - value = 'asfloat(uint4(%s))' % ', '.join(words) - image = self.pipe.uav(key, 'tex2da' if array else 'tex2d') - index = 'uint%d(%s)' % (address, ', '.join(self.u(c) for c in cs)) - body = '%s[%s] = %s;' % (image, index, value) + body = '%s[%s] = asfloat(uint4(%s));' % (image, index, ', '.join(words)) self.emit(body if self.exec_known else 'if (exec & 1) ' + body) def gather_2d_setup(self, name, ops, mods, addr_count, addr_label, *, mip_preclamp): @@ -8832,13 +9291,13 @@ def op_v_fma_mixlo_f16(self, ops, mods): def op_v_fma_mixhi_f16(self, ops, mods): self.mix(ops, mods, 'hi') - def packed_half(self, base, arity, text, ops, mods): - """v_pk_{mul,add,fma}_f16: the same binary16 operation on two lanes of a VGPR pair of halves. + def packed_half(self, base, arity, text, ops, mods, *, select_bits=False): + """Apply the same binary16 operation to each of two selected halves. Result low half = op(source i half op_sel[i], ...); high half = op(source i half op_sel_hi[i], ...). Absent modifiers mean op_sel [0,0,0] and op_sel_hi [1,1,1] (LLVM VOP3P defaults). Both lanes are written (no zeroing). - Not modelled, so refused: neg_lo, neg_hi, clamp, any other modifier, and a source that is not a plain VGPR - (an inline constant or a literal reaches the high lane in a way that is not proven; hold it in a VGPR first). + Add, mul and fma require plain VGPRs. Min and max also accept numeric SGPRs, 32-bit hex literals and inline 0, + and select a result by its encoding. All forms refuse neg_lo, neg_hi, clamp and other modifiers. """ if len(ops) != arity + 1: raise Unsupported('%s with %d operands, expected %d' % (base, len(ops), arity + 1)) @@ -8851,17 +9310,32 @@ def packed_half(self, base, arity, text, ops, mods): if len(bits) != arity or any(b not in ('0', '1') for b in bits): raise Unsupported('%s with %s' % (base, m)) sel[key] = [int(b) for b in bits] - for tok in ops: + for i, tok in enumerate(ops): r = reg_range(tok) + if select_bits and i: + if re.fullmatch(r'0x[0-9a-f]{1,8}|0', tok): + continue + if r and tok == '%s%d' % (r[0], r[1]) and r[1] <= (255 if r[0] == 'v' else 105): + continue + raise Unsupported('%s source %s requires a single VGPR, numeric SGPR, hex word or inline 0' + % (base, tok)) if not r or r[0] != 'v' or r[1] != r[2] or tok != 'v%d' % r[1]: raise Unsupported('%s operand %s is not a single VGPR' % (base, tok)) + if select_bits and r[1] > 255: + raise Unsupported('%s destination %s is out of range' % (base, tok)) lanes = [] for picks in (sel['op_sel'], sel['op_sel_hi']): args = [] for tok, hi, both in zip(ops[1:], picks, zip(sel['op_sel'], sel['op_sel_hi'])): - word = self.u(tok, low16_only=not any(both)) - args.append('f16tof32(%s)' % ('(%s >> 16) & 0xffffu' % word if hi else '%s & 0xffffu' % word)) - lanes.append('f16rn(%s)' % text.format(*args)) + if select_bits and tok.startswith('s'): + self.reject_lane_mask_data(base, tok) + word = self.S(int(tok[1:])) + else: + word = self.u(tok, low16_only=not any(both)) + half = '(%s >> 16) & 0xffffu' % word if hi else '%s & 0xffffu' % word + args.append(half if select_bits else 'f16tof32(%s)' % half) + expr = text.format(*args) + lanes.append(expr if select_bits else 'f16rn(%s)' % expr) d = reg_range(ops[0])[1] self.set_v(d, '%s | (%s << 16)' % tuple(lanes)) @@ -8874,6 +9348,12 @@ def op_v_pk_add_f16(self, ops, mods): def op_v_pk_fma_f16(self, ops, mods): self.packed_half('v_pk_fma_f16', 3, 'fma16o({0}, {1}, {2})', ops, mods) + def op_v_pk_max_f16(self, ops, mods): + self.packed_half('v_pk_max_f16', 2, 'minmax16_bits({0}, {1}, true)', ops, mods, select_bits=True) + + def op_v_pk_min_f16(self, ops, mods): + self.packed_half('v_pk_min_f16', 2, 'minmax16_bits({0}, {1}, false)', ops, mods, select_bits=True) + def cube(self, kind, ops, mods): """v_cube{id,sc,tc,ma}_f32: LLVM's ConstantFoldAMDGCNCubeIntrinsic. @@ -8919,6 +9399,32 @@ def op_v_cubetc_f32(self, ops, mods): def op_v_cubema_f32(self, ops, mods): self.cube('ma', ops, mods) + def op_v_ldexp_f32(self, ops, mods): + if len(ops) != 3: + raise Unsupported('v_ldexp_f32 with %d operands, expected 3' % len(ops)) + dst = reg_range(ops[0]) + if not dst or dst[0] != 'v' or dst[1] != dst[2] or dst[1] > 255: + raise Unsupported('v_ldexp_f32 destination %s' % ops[0]) + src0 = self.f(ops[1]) + src1_tok = ops[2] + if src1_tok.startswith('-') and not re.fullmatch(r'-\d+', src1_tok): + raise Unsupported('v_ldexp_f32 exponent %s has float modifier' % src1_tok) + if src1_tok.startswith('|') or src1_tok.endswith('|') or src1_tok.startswith('abs('): + raise Unsupported('v_ldexp_f32 exponent %s has float modifier' % src1_tok) + sr = reg_range(src1_tok) + if sr is not None: + if sr[1] != sr[2] or (sr[0] == 'v' and sr[1] > 255) or (sr[0] == 's' and sr[1] > 105): + raise Unsupported('v_ldexp_f32 source %s' % src1_tok) + elif src1_tok not in FLOATS and src1_tok not in ('m0', 'null'): + try: + val = int(src1_tok, 0) + except ValueError: + raise Unsupported('operand %r' % src1_tok) + if not -0x80000000 <= val <= 0xffffffff: + raise Unsupported('v_ldexp_f32 source %s' % src1_tok) + src1 = 'asint(%s)' % self.u(src1_tok) + self.set_vf(dst[1], 'ldexp32(%s, %s)' % (src0, src1), mods) + def i64_words(self, tok, signed=False, literal=False): """(low, high) uint expressions of a 64-bit integer source: a VGPR/SGPR pair, an inline int or a 32-bit hex literal when `literal` is set (zero-extended, sign-extended when the operation is signed).""" @@ -9900,6 +10406,8 @@ def lower_wave_readlane(self, sd, vt, claim): # Unsigned sums of absolute differences (AMD RDNA 2 ISA reference, VOP3 opcodes 0x15a to 0x15d and 0x171), all # modulo 2^32. src1 is the reference: v_msad_u8 leaves out each byte lane whose src1 byte is zero, as in # tools/pixel_aot.py. + 'v_lerp_u8': (3, 'lerp_u8({0}, {1}, {2})'), + 'v_perm_b32': (3, 'perm_b32({0}, {1}, {2})'), 'v_sad_u8': (3, 'sad_u8({0}, {1}, {2})'), 'v_sad_hi_u8': (3, 'sad_hi_u8({0}, {1}, {2})'), 'v_sad_u16': (3, 'sad_u16({0}, {1}, {2})'), @@ -10034,6 +10542,29 @@ def handler(self, ops, mods): self.set_scc((cast % op).format(self.u(ops[0]), '0x%08xu' % sopk_imm(ops[1], signed))) return handler setattr(Stage, 'op_s_cmpk_%s_%s' % (_name, _typ), _make_cmpk()) +# s_cmp_eq_u64 / s_cmp_lg_u64: SCC = (S0.u64 == S1.u64) / (S0.u64 != S1.u64). +for _name, _op, _join in (('eq', '==', '&&'), ('lg', '!=', '||')): + def _make_cmp64(op=_op, join=_join, name='s_cmp_%s_u64' % _name): + def handler(self, ops, mods): + if len(ops) != 2 or mods: + raise Unsupported('%s requires two unmodified operands' % name) + if any(self.is_lane_mask(tok) for tok in ops): + raise Unsupported('%s on a lane mask' % name) + masks = getattr(self, 'masks', ()) + mask_high = getattr(self, 'mask_high', ()) + words = [] + for tok in ops: + r = reg_range(tok) + if r: + if r[0] != 's': + raise Unsupported('%s source %s' % (name, tok)) + if any(w in masks or w in mask_high for w in range(r[1], r[2] + 1)): + raise Unsupported('%s on a lane mask' % name) + words.append(('0u', '0u') if tok == 'null' else self.i64_words(tok, False, True)) + (a0, a1), (b0, b1) = words + self.set_scc('((%s %s %s) %s (%s %s %s))' % (a0, op, b0, join, a1, op, b1)) + return handler + setattr(Stage, 'op_s_cmp_%s_u64' % _name, _make_cmp64()) # Scalar bit counts and scans with a 32-bit result. `lo`/`hi` are the uint words of the source: a 32-bit source has only # `lo`. The scans return 0xffffffff (-1) when no bit qualifies. Only the counts set SCC (result != 0). def _clz64(lo, hi): @@ -10092,6 +10623,32 @@ def handler(self, ops, mods): self.set_scc('((%s >> (%s & 31)) & 1u) == %du' % (self.u(ops[0]), self.u(ops[1]), bit)) return handler setattr(Stage, 'op_s_bitcmp%d_b32' % _bit, _make_bitcmp()) +# s_bitcmp1_b64 / s_bitcmp0_b64: SCC = S0.u64[S1.u[5:0]] == 1 / == 0. +for _bit in (0, 1): + def _make_bitcmp64(bit=_bit, name='s_bitcmp%d_b64' % _bit): + def handler(self, ops, mods): + if len(ops) != 2 or mods: + raise Unsupported('%s requires two unmodified operands' % name) + if any(self.is_lane_mask(tok) for tok in ops): + raise Unsupported('%s on a lane mask' % name) + r0, r1 = reg_range(ops[0]), reg_range(ops[1]) + masks = getattr(self, 'masks', ()) + mask_high = getattr(self, 'mask_high', ()) + if r0: + if r0[0] != 's': + raise Unsupported('%s source %s' % (name, ops[0])) + if any(w in masks or w in mask_high for w in range(r0[1], r0[2] + 1)): + raise Unsupported('%s on a lane mask' % name) + if (r1 and (r1[0] != 's' or r1[1] != r1[2] or r1[1] > 105)) or ops[1] in FLOATS: + raise Unsupported('%s bit index %s' % (name, ops[1])) + if r1 and r1[1] in mask_high: + raise Unsupported('%s on a lane mask' % name) + low, high = ('0u', '0u') if ops[0] == 'null' else self.i64_words(ops[0], False, True) + idx = self.u(ops[1]) + word = '((%s & 32u) != 0u ? %s : %s)' % (idx, high, low) + self.set_scc('((%s >> (%s & 31u)) & 1u) == %du' % (word, idx, bit)) + return handler + setattr(Stage, 'op_s_bitcmp%d_b64' % _bit, _make_bitcmp64()) def scalar_wide_fold(helper, x, amount, signed): @@ -10170,12 +10727,107 @@ def read(fmt, data, offset): VERIFIED_SINT_RTVS = frozenset((4, 14, 18, 32, 38, 43, 52, 59, 64)) +BVH_HELPERS = ( + 'static const uint X2W_BVH_MISS = 0xffffffffu;', + # The 128-bit BVH T# (RDNA 2 ISA Table 49): base 39:0, box growing 62:55, sort enable 63, + # size 105:64 and type 8 at 127:124. This slice binds a ByteAddressBuffer at the base and + # keeps the descriptor in a 32-bit address window, so the size-high ten bits and every + # reserved field must be zero. A zero base selects the absolute pointer form, which this + # slice does not bind, so it is refused here as a miss rather than read at address zero. + 'bool x2w_bvh_descriptor_ok(uint word0, uint word1, uint word2, uint word3) {', + ' return (word0 & 0x000000ffu) == 0u && (word1 & 0x7fffff00u) == 0u &&', + ' word3 == 0x80000000u && word2 >= 1u && word2 < 0x04000000u &&', + ' (word0 != 0u || (word1 & 0x000000ffu) != 0u);', + '}', + # One FP32 box from a radv_bvh_box32_node (Mesa 25.1.0 bvh/bvh.h, MIT): children[4] at + # bytes 0..15, coords[4][2][3] at 16..111 (lo then hi per child) and reserved at 112..127. + 'float x2w_bvh_box32_slot(ByteAddressBuffer nodes, uint node_offset, uint index, float extent,', + ' float3 origin, float3 inv_dir, out bool hit) {', + ' uint at = node_offset + 16u + 24u * index;', + ' float3 lo = float3(asfloat(nodes.Load(at)), asfloat(nodes.Load(at + 4u)),', + ' asfloat(nodes.Load(at + 8u)));', + ' float3 hi = float3(asfloat(nodes.Load(at + 12u)), asfloat(nodes.Load(at + 16u)),', + ' asfloat(nodes.Load(at + 20u)));', + ' float3 bound0 = (lo - origin) * inv_dir;', + ' float3 bound1 = (hi - origin) * inv_dir;', + ' float tmin = max(max(min(bound0.x, bound1.x), min(bound0.y, bound1.y)),', + ' min(bound0.z, bound1.z));', + ' float tmax = min(min(max(bound0.x, bound1.x), max(bound0.y, bound1.y)),', + ' max(bound0.z, bound1.z));', + # A NaN in min.x marks an inactive box (Vulkan inactive primitive rule; Mesa tests NaN != NaN). + ' bool active = (asuint(lo.x) & 0x7fffffffu) <= 0x7f800000u;', + ' hit = active && tmax >= max(0.0, tmin) && tmin < extent;', + ' return hit ? tmin : 3.402823466e+38;', + '}', + # The five compare-exchange stages of Mesa radv_nir_rt_common.c: equal keys do not swap, + # so misses (key +inf) sink to the end and unsorted hits keep their child order. + 'void x2w_bvh_sort_pair(inout uint ia, inout uint ib, inout float ka, inout float kb) {', + ' if (kb < ka) { uint ti = ia; ia = ib; ib = ti; float tk = ka; ka = kb; kb = tk; }', + '}', + 'uint4 x2w_bvh_intersect_box32(ByteAddressBuffer nodes, uint node, uint word0, uint word1,', + ' uint word2, uint word3, float extent, float3 origin,', + ' float3 inv_dir) {', + ' uint4 miss = uint4(X2W_BVH_MISS, X2W_BVH_MISS, X2W_BVH_MISS, X2W_BVH_MISS);', + ' if ((node & 7u) != 5u || !x2w_bvh_descriptor_ok(word0, word1, word2, word3)) return miss;', + ' uint offset = (node & 0xfffffff8u) << 3u;', + ' if ((offset >> 6u) + 1u > word2) return miss;', + # Mesa clamps the inverse direction so a zero direction component cannot turn 0 * inf + # into NaN. The box test then follows the software reference exactly. + ' inv_dir = clamp(inv_dir, -3.402823466e+38, 3.402823466e+38);', + ' bool h0, h1, h2, h3;', + ' float d0 = x2w_bvh_box32_slot(nodes, offset, 0u, extent, origin, inv_dir, h0);', + ' float d1 = x2w_bvh_box32_slot(nodes, offset, 1u, extent, origin, inv_dir, h1);', + ' float d2 = x2w_bvh_box32_slot(nodes, offset, 2u, extent, origin, inv_dir, h2);', + ' float d3 = x2w_bvh_box32_slot(nodes, offset, 3u, extent, origin, inv_dir, h3);', + ' bool sort_boxes = (word1 & 0x80000000u) != 0u;', + ' uint c0 = nodes.Load(offset);', + ' uint c1 = nodes.Load(offset + 4u);', + ' uint c2 = nodes.Load(offset + 8u);', + ' uint c3 = nodes.Load(offset + 12u);', + # A disabled child stores 0xffffffff and must not enter the hit list even if its box is valid. + ' h0 = h0 && c0 != X2W_BVH_MISS;', + ' h1 = h1 && c1 != X2W_BVH_MISS;', + ' h2 = h2 && c2 != X2W_BVH_MISS;', + ' h3 = h3 && c3 != X2W_BVH_MISS;', + ' c0 = h0 ? c0 : X2W_BVH_MISS;', + ' c1 = h1 ? c1 : X2W_BVH_MISS;', + ' c2 = h2 ? c2 : X2W_BVH_MISS;', + ' c3 = h3 ? c3 : X2W_BVH_MISS;', + # Sorting disabled keeps the children in their original order. Do not reuse the sort network: + # its nonadjacent compare-exchange stages move a later hit into an earlier position while + # compacting the miss between them, which reorders equal keys. + ' if (!sort_boxes) {', + ' uint4 ordered = miss;', + ' uint n = 0u;', + ' if (h0) ordered[n++] = c0;', + ' if (h1) ordered[n++] = c1;', + ' if (h2) ordered[n++] = c2;', + ' if (h3) ordered[n++] = c3;', + ' return ordered;', + ' }', + ' float k0 = h0 ? d0 : 3.402823466e+38;', + ' float k1 = h1 ? d1 : 3.402823466e+38;', + ' float k2 = h2 ? d2 : 3.402823466e+38;', + ' float k3 = h3 ? d3 : 3.402823466e+38;', + ' x2w_bvh_sort_pair(c0, c1, k0, k1);', + ' x2w_bvh_sort_pair(c2, c3, k2, k3);', + ' x2w_bvh_sort_pair(c0, c2, k0, k2);', + ' x2w_bvh_sort_pair(c1, c3, k1, k3);', + ' x2w_bvh_sort_pair(c1, c2, k1, k2);', + ' return uint4(c0, c1, c2, c3);', + '}', +) + + class Pipeline: vertex_kind = 'vs' uses_pack16_rne = False + uses_bvh = False uses_gather_2d_lod = False uses_store_d16_x = False uses_sad = () + uses_lerp_u8 = False + uses_perm_b32 = False uses_store_format_xyzw = False srv_formats = () uavs = None # key -> dict(index, kind): images a pixel stage stores to (u registers); None until the first store @@ -10211,9 +10863,12 @@ def _init_pixel_context(self, root_blob, sampler_heap=None, rtv_formats=(), ps_h 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.uses_bvh = False self.uses_gather_2d_lod = False self.uses_store_d16_x = False self.uses_sad = set() + self.uses_lerp_u8 = False + self.uses_perm_b32 = False self.uses_store_format_xyzw = False self.resources = {} # key -> dict(index, kind) self.samplers = {} # key -> index @@ -10344,6 +10999,34 @@ def common(self): ' float f = frac(value);', ' return asuint(f) == 0x3f800000u ? asfloat(0x3f7fffffu) : f;', '}', + # v_ldexp_f32: exact binary32 scaling by 2^delta, preserving +/-0, +/-Inf and NaN (same as pixel_aot). + 'float ldexp32(float value, int delta) {', + ' uint bits = asuint(value);', + ' uint sign = bits & 0x80000000u;', + ' uint exp = (bits >> 23) & 0xffu;', + ' uint mant = bits & 0x7fffffu;', + ' if (exp == 0xffu || (exp == 0u && mant == 0u)) return value;', + ' int e = (int)exp;', + ' if (exp == 0u) {', + ' uint shift = 23u - firstbithigh(mant);', + ' mant = (mant << shift) & 0x7fffffu;', + ' e = 1 - (int)shift;', + ' }', + ' e += clamp(delta, -512, 512);', + ' if (e >= 255) return asfloat(sign | 0x7f800000u);', + ' if (e <= 0) {', + ' if (e < -23) return asfloat(sign);', + ' uint full = mant | 0x800000u;', + ' uint shift = (uint)(1 - e);', + ' uint half_bit = 1u << (shift - 1u);', + ' uint mask = (1u << shift) - 1u;', + ' uint rem = full & mask;', + ' uint q = full >> shift;', + ' if (rem > half_bit || (rem == half_bit && (q & 1u) != 0u)) q++;', + ' return asfloat(sign | q);', + ' }', + ' return asfloat(sign | ((uint)e << 23) | mant);', + '}', # v_med3_f32 with a NaN source is the minimum of the three (ISA "343 V_MED3_F32"), so the test is # on the encoding: a float isnan() may be folded away by the compiler. D3D min() returns the # other operand, so the min3 chain over a NaN source is the smallest of the non-NaN ones. min, max @@ -10355,6 +11038,17 @@ def common(self): ' ? minmax_zero32(minmax_zero32(a, b, false), c, false)', ' : minmax_zero32(minmax_zero32(a, b, false), minmax_zero32(minmax_zero32(a, b, true), c, false), true);', '}', + 'uint minmax16_bits(uint a, uint b, bool maximum) {', + ' bool a_nan = (a & 0x7fffu) > 0x7c00u;', + ' bool b_nan = (b & 0x7fffu) > 0x7c00u;', + # Two NaNs produce a canonical quiet NaN. This payload choice is not hardware-proven. + ' if (a_nan) return b_nan ? 0x7e00u : b;', + ' if (b_nan) return a;', + # Reverse negative encodings and put positives above them, ordering -0 below +0. + ' uint a_key = a ^ ((a & 0x8000u) != 0u ? 0xffffu : 0x8000u);', + ' uint b_key = b ^ ((b & 0x8000u) != 0u ? 0xffffu : 0x8000u);', + ' return (maximum ? a_key > b_key : a_key < b_key) ? a : b;', + '}', # High half of an unsigned 32x32 product, by halfword products so it fits 32-bit HLSL. 'uint mul_hi_u32(uint a, uint b) { uint la = a & 0xffffu, lb = b & 0xffffu;' ' uint middle = (a >> 16) * lb + ((la * lb) >> 16);' @@ -10430,10 +11124,12 @@ def common(self): 'uint ldu(ByteAddressBuffer b, uint a) { uint k = (a & 3) * 8, lo = b.Load(a & ~3u); if (k == 0) return lo; ' 'return (lo >> k) | (b.Load((a & ~3u) + 4) << (32 - k)); }', 'cbuffer entry : register(b0) { %s };' % ' '.join('uint ud%d;' % i for i in range(len(self.uds)))] + if self.uses_bvh: + out.extend(BVH_HELPERS) for key, r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): - out.append('%s r%d : register(t%d);' % ({'buf': 'ByteAddressBuffer', 'tex1d': 'Texture1D', 'tex2d': 'Texture2D', 'tex2da': 'Texture2DArray', 'tex3d': 'Texture3D'}[r['kind']], r['index'], r['index'])) + out.append('%s r%d : register(t%d);' % ({'buf': 'ByteAddressBuffer', 'bvh': 'ByteAddressBuffer', 'tex1d': 'Texture1D', 'tex2d': 'Texture2D', 'tex2da': 'Texture2DArray', 'tex3d': 'Texture3D'}[r['kind']], r['index'], r['index'])) for key, r in sorted(self.stored_images().items(), key=lambda kv: kv[1]['index']): - out.append('%s %s%d : register(u%d);' % ({'tex2d': 'RWTexture2D', 'tex2da': 'RWTexture2DArray', 'raw': 'RWByteAddressBuffer'}[r['kind']], 'u' if r['kind'] == 'raw' else 'w', r['index'], r['index'])) + out.append('%s %s%d : register(u%d);' % ({'tex1d': 'RWTexture1D', 'tex2d': 'RWTexture2D', 'tex2da': 'RWTexture2DArray', 'tex3d': 'RWTexture3D', 'raw': 'RWByteAddressBuffer'}[r['kind']], 'u' if r['kind'] == 'raw' else 'w', r['index'], r['index'])) for key, i in self.samplers.items(): out.append('%s q%d : register(s%d);' % ('SamplerComparisonState' if key[0] == 'cmp' else 'SamplerState', i, i)) if self.uses_sampler_heap: @@ -10576,6 +11272,27 @@ def common(self): ' }', '}', )) + if self.uses_lerp_u8: + # RDNA 2 ISA V_LERP_U8: for each byte lane i, D_i = (S0_i + S1_i + (S2_i & 1)) >> 1. + out.append( + 'uint lerp_u8(uint a, uint b, uint c) {' + ' return (((a & 0xffu) + (b & 0xffu) + (c & 1u)) >> 1)' + ' | (((((a >> 8) & 0xffu) + ((b >> 8) & 0xffu) + ((c >> 8) & 1u)) >> 1) << 8)' + ' | (((((a >> 16) & 0xffu) + ((b >> 16) & 0xffu) + ((c >> 16) & 1u)) >> 1) << 16)' + ' | (((((a >> 24) & 0xffu) + ((b >> 24) & 0xffu) + ((c >> 24) & 1u)) >> 1) << 24); }') + if self.uses_perm_b32: + # RDNA 2 ISA V_PERM_B32: {S0, S1} bytes 0..7, selectors 8..11 sign-extend bytes 1/3/5/7, 12 -> 0x00, >=13 -> 0xff. + out.append( + 'uint perm_byte(uint hi, uint lo, uint sel) {' + ' return sel >= 13u ? 0xffu : sel == 12u ? 0u' + ' : sel >= 8u ? ((((sel >= 10u ? hi : lo) >> ((sel & 1u) != 0u ? 31u : 15u)) & 1u) != 0u ? 0xffu : 0u)' + ' : (((sel >= 4u ? hi : lo) >> ((sel & 3u) * 8u)) & 0xffu); }') + out.append( + 'uint perm_b32(uint hi, uint lo, uint sel) {' + ' return perm_byte(hi, lo, sel & 0xffu)' + ' | (perm_byte(hi, lo, (sel >> 8) & 0xffu) << 8)' + ' | (perm_byte(hi, lo, (sel >> 16) & 0xffu) << 16)' + ' | (perm_byte(hi, lo, (sel >> 24) & 0xffu) << 24); }') if 'v_sad_u8' in self.uses_sad: out.append( 'uint sad_u8(uint a, uint b, uint c) {' @@ -10756,8 +11473,12 @@ def manifest(self): lines.append('udsrc %d %s' % (i, ' '.join(str(x) for x in source))) for key, r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): source, off = key - where = {'table': 'table %d %d' % (source[1] if len(source) > 1 else 0, off or 0), 'vbtab': 'vb %d' % ((off or 0) // 16), - 'root': 'root %d' % (source[1] if len(source) > 1 else 0)}.get(source[0]) + if source[0] == 'bvhbase': + where = 'base 0x%x size 0x%x' % (source[1], source[2]) + else: + where = {'table': 'table %d %d' % (source[1] if len(source) > 1 else 0, off or 0), + 'vbtab': 'vb %d' % ((off or 0) // 16), + 'root': 'root %d' % (source[1] if len(source) > 1 else 0)}.get(source[0]) if where is None: raise Unsupported('resource through %s' % (source,)) lines.append('srv %d %s %s' % (r['index'], r['kind'], where)) @@ -10810,7 +11531,10 @@ def __init__(self, cs_code, root_blob, rsrc2, group, sampler_heap=None, refusals self.uses_sampler_heap = False self.uses_gather_2d_lod = False self.uses_store_d16_x = False + self.uses_bvh = False self.uses_sad = set() + self.uses_lerp_u8 = False + self.uses_perm_b32 = False self.resources, self.uavs, self.samplers, self.uds = {}, {}, {}, [] self.notes, self.modified, self.other_modified = set(), set(), set() # other: unproved descriptor writes self.lod_unvalidated = set() @@ -10853,7 +11577,9 @@ def manifest(self): lines = ['x2w-manifest 2', 'stage cs', 'group %d %d %d' % self.group, 'ud %d' % len(self.uds)] lines += ['udsrc %d %s' % (i, ' '.join(str(x) for x in source)) for i, source in enumerate(self.uds)] for (source, off), r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): - if source[0] == 'table': + if source[0] == 'bvhbase': + where = 'base 0x%x size 0x%x' % (source[1], source[2]) + elif source[0] == 'table': where = 'table %d %d' % (source[1], off or 0) elif source[0] == 'root': where = 'root %d' % source[1] @@ -10959,7 +11685,7 @@ def pipeline_key(vs_code, ps_code, root_blob, layout=b'', ps_inputs=None): SPI_PS_INPUT_ENA and SPI_PS_INPUT_ADDR as little-endian u32. Two pipelines with the same stages, root signature and input layout but different masks are then two requests with their own results. Without a description the key is unchanged.""" - key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-28')))) + key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-29')))) key = fnv(layout, key) if layout else key return key if ps_inputs is None else fnv(b'psin1' + struct.pack('([^<]*)") { $env:X2W_TITLE_ID = $Matches[1] } if ($text -match "([^<]*)") { $env:X2W_STORAGE_MB = $Matches[1] } } diff --git a/tools/texture_blocks.py b/tools/texture_blocks.py index 48529ede0e..1d6a851409 100644 --- a/tools/texture_blocks.py +++ b/tools/texture_blocks.py @@ -42,13 +42,20 @@ def block_extent(self) -> tuple[int, int, int]: def format_info(name: str) -> Format: - try: - return FORMATS[name] - except KeyError: - raise ValueError(f"Unknown texture format {name!r}") from None + if not isinstance(name, str) or name not in FORMATS: + raise ValueError(f"Unknown texture format {name!r}") + return FORMATS[name] + + +def _require_int(value, name: str) -> int: + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError(f"Expected integer {name}, got {type(value).__name__}") + return value def _grid(width: int, height: int, format: Format) -> tuple[int, int]: + width = _require_int(width, "width") + height = _require_int(height, "height") if width <= 0 or height <= 0: raise ValueError("Expected positive pixel dimensions") return ((width + format.block_width - 1) // format.block_width, @@ -75,7 +82,7 @@ def surface_bytes(width: int, height: int, format_name: str, *, pitch_blocks: in """Bytes in one block-row surface, including any row pitch padding.""" format = _two_dimensional(format_name) columns, rows = _grid(width, height, format) - pitch = columns if pitch_blocks is None else pitch_blocks + pitch = columns if pitch_blocks is None else _require_int(pitch_blocks, "pitch_blocks") if pitch < columns: raise ValueError(f"Block pitch {pitch} is narrower than the {columns}-block surface") return rows * pitch * format.bytes_per_block @@ -86,7 +93,7 @@ def linearize_blocks(payload, width: int, height: int, format_name: str, *, """Copy the visible blocks of a pitched block-row surface into tight rows.""" format = _two_dimensional(format_name) columns, rows = _grid(width, height, format) - pitch = columns if pitch_blocks is None else pitch_blocks + pitch = columns if pitch_blocks is None else _require_int(pitch_blocks, "pitch_blocks") expected = surface_bytes(width, height, format_name, pitch_blocks=pitch) if len(payload) != expected: raise ValueError(f"Expected {expected} bytes for {format.name}, got {len(payload)}") @@ -100,21 +107,27 @@ def linearize_blocks(payload, width: int, height: int, format_name: str, *, def tile_blocks(blocks, width: int, height: int, format_name: str, *, - pitch_blocks: int | None = None, padding: bytes | None = None) -> bytes: + pitch_blocks: int | None = None, padding: bytes | bytearray | memoryview | None = None) -> bytes: """Write tight block rows into a pitched block-row surface.""" format = _two_dimensional(format_name) columns, rows = _grid(width, height, format) + pitch = columns if pitch_blocks is None else _require_int(pitch_blocks, "pitch_blocks") + expected = surface_bytes(width, height, format_name, pitch_blocks=pitch) block_bytes = format.bytes_per_block tight = columns * rows * block_bytes if len(blocks) != tight: raise ValueError(f"Expected {tight} tight bytes for {format.name}, got {len(blocks)}") - pitch = columns if pitch_blocks is None else pitch_blocks - expected = surface_bytes(width, height, format_name, pitch_blocks=pitch) if padding is None: - padding = b"\xff" * block_bytes - if len(padding) != block_bytes: + padding_bytes = b"\xff" * block_bytes + elif isinstance(padding, (bytes, bytearray)): + padding_bytes = bytes(padding) + elif isinstance(padding, memoryview) and padding.ndim == 1 and padding.format == "B": + padding_bytes = bytes(padding) + else: + raise ValueError(f"Expected bytes-like padding of {block_bytes} bytes, got {type(padding).__name__}") + if len(padding_bytes) != block_bytes: raise ValueError(f"Expected one {block_bytes}-byte padding block") - output = bytearray(padding * (rows * pitch)) + output = bytearray(padding_bytes * (rows * pitch)) row_bytes = columns * block_bytes for y in range(rows): source = y * row_bytes @@ -136,12 +149,13 @@ def _volume_geometry(width: int, height: int, format: Format) -> tuple[int, int, def tile_volume_4k_s(slices, width: int, height: int, depth: int, format_name: str) -> bytes: """Tile tight BC7 volume slices, one padded 4 KiB surface per Z slice.""" format = _volume(format_name) + depth = _require_int(depth, "depth") if depth <= 0: raise ValueError("Expected a positive volume depth") + _, _, slice_bytes, _ = _volume_geometry(width, height, format) slices = list(slices) if len(slices) != depth: raise ValueError(f"Expected {depth} volume slices, got {len(slices)}") - _, _, slice_bytes, _ = _volume_geometry(width, height, format) output = bytearray() for z, blocks in enumerate(slices): if len(blocks) != slice_bytes: @@ -154,6 +168,7 @@ def tile_volume_4k_s(slices, width: int, height: int, depth: int, format_name: s def linearize_volume_4k_s(payload, width: int, height: int, depth: int, format_name: str) -> bytes: """Read tight BC7 volume slices from one 4 KiB surface per Z slice.""" format = _volume(format_name) + depth = _require_int(depth, "depth") if depth <= 0: raise ValueError("Expected a positive volume depth") _, _, _, slice_stride = _volume_geometry(width, height, format)