diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 2260dcb3c..9f2d82948 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -4,7 +4,7 @@ on: push: branches: [main] pull_request: - branches: [main] + branches: [main, cpp-migration] workflow_dispatch: concurrency: @@ -496,6 +496,14 @@ jobs: ctest --preset dev --no-tests=error --parallel 4 -E '_hardware$' --output-junit "$PWD/out/test-results.xml" } exit $LASTEXITCODE + - name: Check native DXIL generation on migration pull requests + if: github.base_ref == 'cpp-migration' + shell: pwsh + run: | + .\tools\dev.ps1 + cmake --build --preset dev --target compile_dxil + if ($LASTEXITCODE) { exit $LASTEXITCODE } + ctest --preset dev --no-tests=error -R '^native_dxil_llvm_ident_controls$' - name: Require the SPIR-V bridge WARP tests if: ${{ !cancelled() }} shell: pwsh diff --git a/CMakeLists.txt b/CMakeLists.txt index aab267c78..fef07e485 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,6 +3,38 @@ project(Xbox2Windows LANGUAGES CXX) enable_testing() +if(WIN32) + include(CheckIncludeFiles) + check_include_files("windows.h;dxcapi.h" X2W_HAVE_DXCAPI LANGUAGE CXX) + if(X2W_HAVE_DXCAPI) + add_library(x2w_shader_compiler STATIC src/gfx1013_pixel.cpp src/gfx1013_compute_clear.cpp + src/shader_compute_request.cpp src/guest_shader_container.cpp src/gfx1013_isa.cpp src/direct_compute_cache.cpp src/gfx1013_compute_native.cpp src/native_compute_pipeline.cpp + src/gfx1013_compute_ir.cpp src/gfx1013_sampled_pixel.cpp src/gfx1013_vertex_id.cpp src/gfx1013_rect_geometry.cpp src/shader_dxil_compiler.cpp) + set(native_shader_revision "") + foreach(source gfx1013_compute_native.cpp gfx1013_compute_native.h gfx1013_compute_opcodes.inl gfx1013_graphics_wqm.inl + gfx1013_isa_tables.inl gfx1013_isa.cpp gfx1013_isa.h gfx1013_compute_alu.inl gfx1013_direct_compute.inl gfx1013_compute_ir.cpp gfx1013_compute_ir.h + gfx1013_compute_mtbuf.inl gfx1013_direct_graphics.inl gfx1013_rect_geometry.cpp guest_shader_container.cpp guest_shader_container.h + dxil_module.h direct_compute_cache.cpp direct_compute_cache.h + shader_compute_request.cpp shader_compute_request.h startup_stubs/inflate.h) + set(native_shader_file "${CMAKE_CURRENT_SOURCE_DIR}/src/${source}") + set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${native_shader_file}") + file(SHA256 "${native_shader_file}" native_shader_part) + string(APPEND native_shader_revision "${native_shader_part}") + endforeach() + string(SHA256 native_shader_revision "${native_shader_revision}") + file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/generated/native_shader_revision.h" + CONTENT "#define X2W_NATIVE_SHADER_REVISION \"${native_shader_revision}\"\n") + target_include_directories(x2w_shader_compiler PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/generated") + target_include_directories(x2w_shader_compiler PUBLIC src) + target_compile_features(x2w_shader_compiler PUBLIC cxx_std_17) + target_link_libraries(x2w_shader_compiler PRIVATE bcrypt d3d12) + add_executable(compile_dxil tools/startup/compile_dxil.cpp) + target_link_libraries(compile_dxil PRIVATE x2w_shader_compiler) + set_target_properties(compile_dxil x2w_shader_compiler PROPERTIES + MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + endif() +endif() + # Python never caches the bytecode of the script it is started with, so every start of a big # tests/.py recompiled it. tests/pyc_main.py runs that file through the import system, # which reuses a valid .pyc. The add_test calls below keep naming the script; this wrapper swaps in @@ -399,6 +431,12 @@ set_target_properties(d3d12_xs_shim PROPERTIES OUTPUT_NAME d3d12_xs) target_include_directories(d3d12_xs_shim PRIVATE src) target_compile_features(d3d12_xs_shim PRIVATE cxx_std_17) target_link_libraries(d3d12_xs_shim PRIVATE d3d12) +# X2W_NATIVE_SHADERS: the stand-in translates slot 67 compute requests in-process +# (src/startup_stubs/d3d12_compute_dispatch.inl). Both use the static CRT. +if(TARGET x2w_shader_compiler) + target_link_libraries(d3d12_xs_shim PRIVATE x2w_shader_compiler) + target_compile_definitions(d3d12_xs_shim PRIVATE X2W_NATIVE_SHADERS) +endif() # The creation-IID gate and refusal text of D3D12XboxCreateDevice (src/d3d12x_device_slots.h), # without a device. The mutated run is the negative control. add_executable(d3d12x_device_slots_check tests/d3d12x_device_slots_check.cpp src/d3d12x_device_slots.cpp) @@ -1818,6 +1856,110 @@ foreach(backend IN ITEMS warp hardware) ENVIRONMENT "X2W_MESH86_FIXTURE_XMEM=$") endforeach() get_filename_component(DXC_BIN_DIR "${DXC_EXECUTABLE}" DIRECTORY) + +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_executable(native_store_replay tests/native_store_replay.cpp tests/desktop_gpu.cpp) + target_include_directories(native_store_replay PRIVATE src tests) + target_link_libraries(native_store_replay PRIVATE x2w_shader_compiler d3d12 dxgi d3dcompiler) + set_property(TARGET native_store_replay PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + add_test(NAME native_scalar_lds_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_scalar_lds_check.py" "$" "${DXC_BIN_DIR}") + set_tests_properties(native_scalar_lds_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_test(NAME native_adjacent_srv_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_adjacent_srv_check.py" "$" "${DXC_BIN_DIR}") + set_tests_properties(native_adjacent_srv_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_test(NAME native_mtbuf_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_mtbuf_check.py" "$" "$" "${DXC_BIN_DIR}") + set_tests_properties(native_mtbuf_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_test(NAME native_indexed_atomic_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_indexed_atomic_check.py" "$" "$" "${DXC_BIN_DIR}") + set_tests_properties(native_indexed_atomic_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_executable(native_wave_request_gpu tests/native_wave_request_gpu.cpp tests/native_compute_grid.cpp tests/native_half_grid.cpp tests/desktop_gpu.cpp) + target_link_libraries(native_wave_request_gpu PRIVATE x2w_shader_compiler d3d12 dxgi) + set_target_properties(native_wave_request_gpu PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + add_test(NAME native_wave_request_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_wave_request_check.py" "$" + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_wave_request_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_executable(native_lds_gpu tests/native_lds_gpu.cpp tests/desktop_gpu.cpp) + target_link_libraries(native_lds_gpu PRIVATE x2w_shader_compiler d3d12 dxgi) + set_target_properties(native_lds_gpu PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + add_executable(native_sampled_pixel_gpu tests/native_sampled_pixel_gpu.cpp tests/desktop_gpu.cpp) + add_executable(native_buffered_vertex_gpu tests/native_buffered_vertex_gpu.cpp tests/desktop_gpu.cpp) + target_link_libraries(native_buffered_vertex_gpu PRIVATE x2w_shader_compiler d3d12 dxgi) + set_target_properties(native_buffered_vertex_gpu PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + target_link_libraries(native_sampled_pixel_gpu PRIVATE x2w_shader_compiler d3d12 dxgi) + set_target_properties(native_sampled_pixel_gpu PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + add_test(NAME native_sampled_replay COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/native_sampled_replay_check.py" + "$" "$" "${DXC_BIN_DIR}") + foreach(backend IN ITEMS warp hardware) + add_test(NAME native_buffered_vertex_${backend} COMMAND native_buffered_vertex_gpu ${backend} "${DXC_BIN_DIR}" + "${CMAKE_CURRENT_BINARY_DIR}/native-buffered-${backend}") + set_tests_properties(native_buffered_vertex_${backend} PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME native_sampled_pixel_${backend} COMMAND native_sampled_pixel_gpu ${backend} "${DXC_BIN_DIR}" + "${CMAKE_CURRENT_BINARY_DIR}/native-sampled-${backend}") + set_tests_properties(native_sampled_pixel_${backend} PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME native_lds_${backend} COMMAND native_lds_gpu ${backend} "${DXC_BIN_DIR}" + "${CMAKE_SOURCE_DIR}/tests/native_lds_gpu.hlsl" "${CMAKE_CURRENT_BINARY_DIR}/native-lds-${backend}") + set_tests_properties(native_lds_${backend} PROPERTIES SKIP_RETURN_CODE 77) + endforeach() + add_test(NAME native_lds_control_flow COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_lds_control_flow_check.py") + add_test(NAME native_compute_clear COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_compute_clear_check.py" "$" "${DXC_BIN_DIR}") + add_test(NAME native_compute_raw_root COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_compute_raw_root_check.py" "$" "${DXC_BIN_DIR}") + add_test(NAME native_direct_container + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/native_direct_container_check.py" + "$" "${DXC_BIN_DIR}") + add_test(NAME native_dpp_mirror_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_dpp_mirror_check.py" "$" + "$" "$" "${DXC_BIN_DIR}") + set_tests_properties(native_dpp_mirror_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_test(NAME native_graphics_wqm_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_graphics_wqm_check.py" "$" + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_graphics_wqm_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_test(NAME native_graphics_interface_library + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/native_graphics_interface_library_check.py" + "$" "${DXC_BIN_DIR}") + add_executable(native_recording_check tests/native_recording_check.cpp) + target_include_directories(native_recording_check PRIVATE src) + target_compile_features(native_recording_check PRIVATE cxx_std_17) + target_link_libraries(native_recording_check PRIVATE x2w_shader_compiler dxgi d3d12) + set_property(TARGET native_recording_check PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + add_test(NAME native_comparison_pso_warp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_direct_container_check.py" --sampler-pso + "${DXC_BIN_DIR}" "$") + set_tests_properties(native_comparison_pso_warp PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME native_graphics_comparison_pso_warp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_direct_container_check.py" --graphics-sampler-pso + "${DXC_BIN_DIR}" "$") + set_tests_properties(native_graphics_comparison_pso_warp PROPERTIES SKIP_RETURN_CODE 77) + # Cycle 1 of the global SRV work: ResourceDescriptorHeap[index] from a native DXIL module against a DXC reference. + add_executable(native_heap_handle_probe tests/native_heap_handle_probe.cpp) + target_include_directories(native_heap_handle_probe PRIVATE src) + target_compile_features(native_heap_handle_probe PRIVATE cxx_std_17) + target_link_libraries(native_heap_handle_probe PRIVATE x2w_shader_compiler dxgi d3d12) + set_property(TARGET native_heap_handle_probe PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_heap_handle_probe_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_heap_handle_probe_check.py" "$" + "${DXC_BIN_DIR}" ${adapter}) + set_tests_properties(native_heap_handle_probe_${adapter} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + endforeach() + add_test(NAME native_recording_pages_warp COMMAND native_recording_check) + add_test(NAME native_dispatch_states_warp COMMAND native_recording_check --subresources) + set_tests_properties(native_dispatch_states_warp PROPERTIES SKIP_RETURN_CODE 77) + set_tests_properties(native_recording_pages_warp PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME native_rectangle_pso_warp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_direct_container_check.py" --rect-pso + "$" "${DXC_BIN_DIR}" "$") + set_tests_properties(native_rectangle_pso_warp PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME native_pixel_dxil + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/native_pixel_dxil_check.py" + "$" "${DXC_BIN_DIR}") +endif() target_compile_definitions(root_probe PRIVATE SDK_DXC_DIR=L"${DXC_BIN_DIR}/") add_executable(offscreen_check tests/offscreen_check.cpp tests/compute_check.cpp tests/dxr_check.cpp tests/buffer_ops.cpp tests/descriptor_heap_paging.cpp) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c3a2bba76..372442385 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -33,6 +33,8 @@ Start with the [first build](README.md#first-build). Create the Python environme On pull requests, `Build and test on Windows` builds the smoke-test targets with `cmake --build --preset pr` and runs `ctest --preset pr --no-tests=error`. The preset selects tests for CPU translation, PE startup, memory, archive decoding and WARP rendering, including the SPIR-V bridge checks. The bridge checks can skip locally if their tools are missing; hosted CI installs the pinned tools and requires the WARP bridge checks to pass. For a strict local run, run [the pinned tool setup](tools/setup-spirv-tools.ps1) (`.\tools\setup-spirv-tools.ps1` in PowerShell) before configuring or reconfiguring, then set `$env:X2W_REQUIRE_SPIRV_TOOLS = '1'` before running CTest. Run the tests for your specific change locally and include their results in the PR. +Pull requests into `cpp-migration` also build `compile_dxil` and run `native_dxil_llvm_ident_controls` on Windows to check direct DXIL generation. + On `main` and manual runs, CI runs the full non-hardware suites in Debug and Release (/O2), generates the coverage chart and smoke-tests the standalone GPU package. To check a branch in both configurations before merge, select it under **Actions → Windows checks → Run workflow**. The Ubuntu jobs assemble gfx1013 fixtures with LLVM 15 and run the platform-independent Python checks. [CI workflow](.github/workflows/windows.yml) Contributors supply physical GPU coverage. Record the commit, adapter and driver, Windows version, test names and debug-layer status. Include the feature tier or wave width when relevant. Report capability skips separately from passes and failures. [Non-Windows host guide](docs/non-windows-hosts.md) diff --git a/docs/experiments.md b/docs/experiments.md index cde85df97..2365cd0c2 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -2,6 +2,96 @@ New notes go in `docs/experiments/.md` (see [the folder guide](experiments/README.md)); this file keeps the older notes. +## Plain binary16 arithmetic in direct compute + +VOP2 and VOP3 add, sub, subrev and mul use binary32 arithmetic and an integer nearest-even conversion back +to binary16. [Plain-form experiment](experiments/f16-alu-direct.md) + +## SDWA binary16 arithmetic in direct compute + +The same four operations accept VGPR half selection, input abs and neg, and half-word destination placement +with pad or preserve. The readback fixture checks both halves and untouched buffer guards. +[SDWA experiment](experiments/native-sdwa-f16.md) + +## Guest logical 64-bit shift sources in direct compute + +Logical 64-bit shifts accept sign-extended inline integers, zero-extended +32-bit literals and numeric even SGPR pairs. The compute fixture checks +both directions, boundary shift amounts and the inline-float refusal. +[Experiment and reproduction commands](experiments/native-shift64-sources.md) + +## Guest quad permutations in direct compute + +DPP16 quad permutations reuse the row mirror's EXEC and operand handling. +The compute fixture checks arithmetic, lane selection and disabled sources. +[Experiment and reproduction commands](experiments/native-dpp-quad-compute.md) + +## Guest lane reads and writes in direct compute + +`v_readlane_b32` and `v_writelane_b32` lower with a constant or SGPR lane; lane writes ignore EXEC. +Lane reads may refill `vcc_lo` and, in wave32, `vcc_hi` as ordinary scalar data. +[Experiment and reproduction commands](experiments/native-lane-access-compute.md) + +## 64-bit scalar operations in direct compute + +`s_bfm_b64`, `s_cselect_b64` and `s_not_b64` lower to two scalar words. +The compute fixture reads both result words and SCC from two workgroups. +[Experiment and reproduction commands](experiments/native-salu64-ops.md) + +## Byte-window stores in direct compute + +Raw buffer stores accept a descriptor with a cleared stride, a byte count +derived from that descriptor's clamped stride, and the raw OOB selector. +The compute fixture reads back all four store widths across two workgroups. +[Experiment and reproduction commands](experiments/native-bytewin-store.md) + +## Guest row mirrors and masked branches in the direct DXIL frontend + +The hardware fixture gives each guest lane a distinct value. DPP16 control +`0x141` reverses each group of eight and `0x140` reverses each group of +sixteen. The reference implementation at Victory revision `9376fd6` computes +these indices in `victory-shader/src/emit/lower.rs::dpp`. Its `cross_lane` +check restricts pixel shaders to quad-local operations. The older Python +`pixel_aot.parse_dpp` also checks whether both halves use the same quad +permutation. The compute shader exchanges the first operand before applying the +local second operand. A sparse EXEC mask distinguishes fetching an inactive +source, supplying zero and retaining the destination. The test checks both +workgroups and the surrounding buffer guards. + +The pixel fixture opens EXEC to all lanes, seeds a guest register with scalar +lane writes and reads back lanes in each half of a guest wave64. The compiler +can track those words independently of the desktop rasterizer's choice of +quads. A second fixture uses repeated min/max, alternate-row selection and +a scalar lane broadcast. An ordinary WQM pixel input whose source lies in +another quad still requires a guest pixel-wave layout. For structured vertex +EXEC branches the container fixture checks control-flow joins, saved-mask +clobbers and scalar values escaping a masked arm. + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay offscreen_check +ctest --preset dev --no-tests=error -R '^(native_dpp_mirror_hardware|native_direct_container)$' +``` + +### Pixel coverage and whole-wave mask branches + +For a mask held in scalar registers, `s_wqm_b32` and `s_wqm_b64` expand +each occupied four-bit group to four ones. A scalar region that saves the +expanded EXEC or branches on zero tests the complete guest width. The fixture +includes a wave64 with only bit 32 set and a wave32 with the same two input +words. They take opposite branches. + +A separate pixel fixture interpolates a value, removes covered lanes where it +is negative, runs a quad permutation under WQM and restores exact coverage +before exporting. A survivor can read a neighbor whose coverage was removed. +Successive filters intersect the surviving coverage. This lowering checks that +an empty quad cannot contribute to another quad or leave an observable store. +A cross-quad permutation in the same live arm is a rejection control. + +```powershell +cmake --build --preset dev --target compile_dxil offscreen_check +ctest --preset dev --no-tests=error -V -R '^native_graphics_wqm_hardware$' +``` + ## Desktop culling and front-face winding `raster_winding_warp` and `raster_winding_hardware` draw two mirrored triangles diff --git a/docs/experiments/f16-alu-direct.md b/docs/experiments/f16-alu-direct.md new file mode 100644 index 000000000..fdb570954 --- /dev/null +++ b/docs/experiments/f16-alu-direct.md @@ -0,0 +1,53 @@ +# Binary16 add, sub, subrev and mul in the direct compute path + +Lowers VOP2 and VOP3 `v_add_f16`, `v_sub_f16`, `v_subrev_f16` and `v_mul_f16` in the direct C++ compute frontend ([`src/gfx1013_direct_compute.inl`](../../src/gfx1013_direct_compute.inl)). The handler returns without lowering when the stage is graphics, so a graphics program keeps the generic direct-lowering refusal. A graphics container was not dumped on this host. + +## Semantics + +- Each source is its low 16 bits. An inline float uses the binary16 rounding of that f32 value. An integer inline or a literal uses its low 16 bits. +- abs clears bit 15 of the half, then neg toggles it. +- The operation is an f32 add, sub or mul. An f32 value has a 24-bit significand, which covers a correctly rounded binary16 add, sub or mul. +- The result is rounded with the same integer round-to-nearest-even conversion `v_cvt_f16_f32` uses. The low 16 bits are written and the high half is zero. +- `v_subrev_f16` subtracts the first source from the second. + +The bit-exact reference is `half_op` in [`tests/f16_packed_model.py`](../../tests/f16_packed_model.py). NaN results match by class. The check is [`tests/native_f16_alu_check.py`](../../tests/native_f16_alu_check.py). + +## Refused forms + +The SDWA operand profile is covered by the [SDWA experiment](native-sdwa-f16.md). + +Each of these is a named diagnostic: + +- DPP +- clamp or omod +- a high-half `op_sel` (instruction bits 11 through 14) +- a binary16 rounding mode other than round-to-nearest-even, an f16 denormal mode other than keep on input and output, or `FP16_OVFL` +- `s_setreg_b32` of those MODE bits, because the source is a register + +`s_round_mode` and `s_denorm_mode` that leave the f16 fields at that contract, and that leave the f32 fields unchanged, are accepted. A write that changes an f32 rounding or denormal field keeps the previous control-instruction refusal. A guest branch together with a MODE write makes the contract unprovable and is refused with the rounding diagnostic. + +fma, fmac, fmamk, fmaak, min, max, ldexp, the min3/max3/med3 forms, div_fixup, VOP1 and the `v_pk` forms stay on the generic direct-lowering diagnostic. The fixture checks `v_fmac_f16` and `v_min_f16`. + +## Linux + +Python 3.12.3. `compile_dxil` is created only in the `WIN32` section of `CMakeLists.txt`, so this host did not build that target. The IR dumper was compiled from `src/gfx1013_compute_native.cpp`, `src/gfx1013_isa.cpp`, `src/guest_shader_container.cpp`, `src/gfx1013_compute_ir.cpp` and `tests/native_compute_ir_dump.cpp` with g++ 13.3.0 and a local stub of `d3d12.h` and `wrl/client.h`. That stub is not in the tree. + +``` +python3 -B tests/native_f16_alu_check.py model +python3 -B tests/native_f16_alu_check.py ir +``` + +- `model` printed `native_f16_alu model: 82 results match f32-then-round; a sub/subrev swap and a non-zero upper half are rejected`. +- `ir` printed `native_f16_alu IR: 82 results match the model; 20 refusals carry the named diagnostic`. The module calls `legacyF16ToF32`, `fadd`, `fsub` and `fmul`, and the integer round contains the constant `939524096`. + +`native_f16_alu_hardware` was not run. It is registered with skip code 77, the same code `native_store_replay` returns when the device cannot run a wave32 shader. WARP is expected to take that skip. + +## Windows + +Pending. On the Windows test machine: + +``` +cmake --preset dev +cmake --build --preset dev --target compile_dxil offscreen_check +ctest --preset dev --no-tests=error -R "^native_f16_alu_(ir|hardware)$" -V -j 1 +``` diff --git a/docs/experiments/native-bytewin-store.md b/docs/experiments/native-bytewin-store.md new file mode 100644 index 000000000..b4e6c028e --- /dev/null +++ b/docs/experiments/native-bytewin-store.md @@ -0,0 +1,38 @@ +# Byte-window stores in the direct C++ compute path + +Issue #2965 covers raw stores through a rewritten table descriptor. The +guest loads the descriptor with `s_load_dwordx4`, extracts the stride +from word 1 with `s_bfe_u32` and clamps it to at least 1 with +`s_max_u32`. It clears the stride in word 1 with `0xc000ffff`, scales +word 2 by the clamped stride with `s_mul_i32`, and sets the raw OOB +selector in word 3 with `s_or_b32` and `0x30000000`. + +The compiler proves that all three edits originate from the descriptor +selected by word 0. The OR works on a loaded word 3 or one whose selector +has already been cleared. The original table slot supplies the raw UAV. +The host UAV's extent determines which writes are in range. + +## Verification + +`native_bytewin_store_controls` expects refusal for a plain SGPR +multiplier, a byte count from another table slot, and the OOB mask +`0x20000000`. Dropping the stride proof or accepting a foreign +descriptor's word should make the corresponding control fail. + +`native_bytewin_store_hardware` dispatches two 32-thread groups through +`native_store_replay`. Each store width has a 1024-byte plane with a +16-byte slot per lane. Widths 1 to 4 write the first 1 to 4 words of each +slot with `16 * lane + component + 1`. Unwritten words and both +eight-word guards retain `0x69696969`. All writes fit in the 8192-byte +raw UAV. Hardware without shader model 6.6 and wave32 support returns +skip code 77. + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_bytewin_store_(controls|hardware)$' +``` + +Results: on an NVIDIA GeForce RTX 5080 (Windows 11, DXC from the Windows SDK 10.0.26100) all four store widths +matched in both workgroups, with the unwritten words and guards intact, and the four controls were refused, including a buffer atomic through the byte window. +Dropping the clamped-stride proof lets the constant-multiplier control compile, and ignoring descriptor identity +lets the foreign word 2 control compile; each fails the controls. diff --git a/docs/experiments/native-compile-dxil-refusals.md b/docs/experiments/native-compile-dxil-refusals.md new file mode 100644 index 000000000..494f62a51 --- /dev/null +++ b/docs/experiments/native-compile-dxil-refusals.md @@ -0,0 +1,38 @@ +# `.fail` diagnostics and read-only `--refusals` summary in `compile_dxil` + +[The test fixture](../../tests/native_compile_dxil_refusals_check.py) verifies two diagnostics in +`tools/startup/compile_dxil.cpp` and their ingestion by `tools/startup/triage_run.py` on `cpp-migration` +(part of #2935): + +1. **Per-request `.fail` lifecycle in `--requests` batch mode:** + - Refused graphics (`req_.a`) and slot-67 compute (`req_.c67`) requests atomically publish a + single-line `.fail` file alongside withdrawing any prior `.txt`, while publishing no stage + `.cso` bytecode. + - Re-running `--requests` after fixing a refused request removes the stale `.fail` once `.txt` + is published. + - `tools/startup/triage_run.py` classifies native `.fail` entries under allowlisted categories in + `SHADER_REASONS` without echoing private strings or raw instruction bytes. +2. **Read-only `--refusals REQUEST_DIRECTORY [--jobs N] [--json]`:** + - Summarizes first-refusal counts across graphics (`req_.a`) and slot-67 compute (`req_.c67`) + requests without invoking DXC or writing any cache or output files. + - Strips PC offsets and normalizes hex words, byte offsets, and register indices so repeated failures + across different instructions or requests aggregate into one row. + +## Verification + +```powershell +.\tools\dev.ps1 +cmake --preset release +cmake --build --preset release --target compile_dxil +ctest --preset release --no-tests=error -V -R "^native_compile_dxil_refusals$" +.\out\pe-env\Scripts\python.exe -B tests/startup_triage_run_check.py +``` + +## Limits + +- `--refusals` reports the first refusal reached per request by `read_graphics_request` / + `prepare_direct_graphics(..., /*write_cache=*/false)` and `read_compute_request` / `translate_compute`; it + does not walk past the first refusal or invoke DXC. +- Graphics requests use `req_.a` and `req_.rtv` ([RTV variant note](native-rtv-variant-requests.md)); + when both markers share a key, the variant takes precedence. Slot-57 mesh requests remain outside the + native path. diff --git a/docs/experiments/native-compile-dxil-watch.md b/docs/experiments/native-compile-dxil-watch.md new file mode 100644 index 000000000..1c5b5f816 --- /dev/null +++ b/docs/experiments/native-compile-dxil-watch.md @@ -0,0 +1,29 @@ +# `--watch` mode in `compile_dxil` + +[The test fixture](../../tests/native_compile_dxil_watch_check.py) verifies continuous and one-shot +`--watch` operation in `tools/startup/compile_dxil.cpp` on `cpp-migration` (part of #2935): + +- `compile_dxil --watch SDK_DIRECTORY CACHE_DIRECTORY REQUEST_DIRECTORY [--jobs N] [--interval MS] [--once]` + loads and fingerprints the DXC SDK once and translates pending startup graphics (`req_.a`) and slot-67 + compute (`req_.c67`) requests into `.{vs,ps,cs}.cso`, optional `.psdep`, and `.txt`, or + writes `.fail` on refusal. +- Pending and resume checks match `tools/startup/gfx2hlsl.py`: completed `.txt` entries with valid DXBC `.cso` + containers are skipped, truncated or missing stage `.cso` files are resumed, `.psin` additions/updates/removals + trigger rechecks, pre-existing `.fail` entries are retried once on the first pass, and unchanged `.fail` entries + are skipped on subsequent passes until the marker or `.psin` is rewritten. + +## Verification + +```powershell +.\tools\dev.ps1 +cmake --preset release +cmake --build --preset release --target compile_dxil +ctest --preset release --no-tests=error -V -R "^native_compile_dxil_watch$" +``` + +## Limits + +- Watches startup graphics (`req_.a`), RTV variant (`req_.rtv`), and slot-67 compute + (`req_.c67`) requests; slot-57 mesh requests remain outside the native path. +- `run.ps1 -Translate` still invokes `gfx2hlsl.py --watch` until the remaining graphics/runtime migration items + in #2935 land. diff --git a/docs/experiments/native-direct-align-bfm.md b/docs/experiments/native-direct-align-bfm.md new file mode 100644 index 000000000..fd94d397b --- /dev/null +++ b/docs/experiments/native-direct-align-bfm.md @@ -0,0 +1,34 @@ +# v_alignbit_b32, v_alignbyte_b32 and v_bfm_b32 in the direct C++ compute path (#2985) + +The direct compute frontend (`src/gfx1013_direct_compute.inl`) now lowers three VOP3 bit operations that it +refused with `direct DXIL lowering for `. The semantics are the expressions of the `gfx2hlsl.py` VOP3 table: + +- `v_alignbit_b32`: bits [k + 31 : k] of the 64-bit value {S0, S1}, with k = S2[4:0]. A zero k returns S1. +- `v_alignbyte_b32`: the same with k = 8 * S2[1:0]. +- `v_bfm_b32`: ((1 << S0[4:0]) - 1) << S1[4:0], the rule `s_bfm_b32` already uses in this path. + +Shift amounts are masked to five bits. The zero case is a select, so the masked shift by 32 - k in the other arm +stays in range. + +These three were found with a local probe that is not part of this change. It compiles one instruction per VOP3 +name of `src/gfx1013_isa_tables.inl` (VOP3 encoding, VGPR operands) through `compile_dxil ... gfx1013-direct-cs@0`. +On `cpp-migration` `05438d65` it saw 79 names refused, and these three had a `gfx2hlsl.py` lowering and no issue or +PR at the time. + +## Fixture + +`tests/native_align_bfm_check.py controls|hardware` +(`ctest --preset dev --no-tests=error -R '^native_align_bfm_' -V`). The words were assembled with LLVM 15.0.7 (`clang +-cc1as -triple amdgcn -target-cpu gfx1013 -filetype asm -show-encoding`). + +- The dispatch has two groups of 32 lanes. Lane L of group g uses S0 = 0x89abcdef, S1 = 0x01234567 and + S2 = L + 32g, so every shift 0 to 31 and every byte count appears. Group 1 repeats them with bit 5 set, which the + field must ignore. `v_bfm_b32` takes S0 = S2 and S1 = S2 ^ 0x15. The 192 results and the guard words are compared + with a CPU reference. +- The controls compile the program and check that the references with the zero shift not special-cased, with S0 + and S1 exchanged, and with the field not masked each differ from the expected words. + +Measured on 27.11.2026, `cpp-migration` `05438d65` plus this change, Windows 10.0.26100.9711. The controls printed +`compiled; the zero-shift, exchanged-source and unmasked references each differ from the expected words`. The +readback printed `requires shader model 6.6 with wave32` and reported a skip (77) on the NVIDIA Quadro M1000M (driver +32.0.15.7371, debug layer unavailable). The readback is not measured. diff --git a/docs/experiments/native-direct-cvt-pk-u8.md b/docs/experiments/native-direct-cvt-pk-u8.md new file mode 100644 index 000000000..2174ac8ac --- /dev/null +++ b/docs/experiments/native-direct-cvt-pk-u8.md @@ -0,0 +1,51 @@ +# v_cvt_pk_u8_f32 in the direct C++ compute path (#2997) + +The direct compute frontend (`src/gfx1013_direct_compute.inl`) now lowers `v_cvt_pk_u8_f32`, which it refused with +`direct DXIL lowering for v_cvt_pk_u8_f32`. It computes +D = (S2 & ~(0xff << 8 * S1[1:0])) | (flt32_to_uint8(S0) << 8 * S1[1:0]). + +The conversion is the one `gfx2hlsl.py` (`op_v_cvt_pk_u8_f32`) uses, measured on RDNA 2 hardware +(`docs/experiments.md`, `tools/rdna_cvt_pk_u8.py`): round to nearest even, saturate to [0, 255]. NaN, both zeros and +every negative value give 0; +inf gives 255. + +The lowering follows that expression: +- The positive test is the integer comparison (bits - 1) < 0x7f800000, which fast-math cannot fold. +- The value then goes through DXIL `FMin` with 255.0 and `Round_ne`, and `fptoui`. +- The resulting byte is merged into S2. + +Source and output modifiers stay refused (`direct ALU operand modifiers`), as `gfx2hlsl.py` refuses them. + +## Fixture + +`tests/native_cvt_pk_u8_check.py controls|hardware` +(`ctest --preset dev --no-tests=error -R '^native_cvt_pk_u8_' -V`). + +Sixteen cases set S0 and S1 by `v_mov` literals over S2 = 0xa5a5a5a5, and every lane of two groups stores the +results. The cases cover: +- the ties 0.5, 1.5, 2.5 and 254.5; +- the bound 255.5, 1e30 and +inf; +- -0.0, -1.0 and -inf; +- a quiet NaN; +- the smallest subnormal; +- 127.4999, 0.0 and 255.0; +- all four byte selects, plus a select of 6 that must use only its low two bits. + +The VOP3 word (opcode 0x15e) was assembled with LLVM 15.0.7 (`clang -cc1as -triple amdgcn -target-cpu gfx1013 +-filetype asm -show-encoding`). + +The controls: +- compile the program and check its module with `dxc -dumpbin`: one `FMin` (DXIL opcode 36) and one `Round_ne` + (opcode 26) per case, and no `FMax`; +- refuse it with a negated S0; +- check that three references differ from the expected words: rounding half up, truncating, and letting negatives + through. + +The reference agrees with `model_rne_sat` of `tools/rdna_cvt_pk_u8.py` for all sixteen inputs (checked once while +writing the fixture). Fourteen of the sixteen inputs are also rows of the measured table +`tests/data/rdna_cvt_pk_u8_measured.tsv`; 1e30 and 127.4999 rely on the model only. + +Measured on 27.11.2026, `cpp-migration` `4ff5e36d` plus this change, Windows 10.0.26100.9711. The controls printed +`compiled with one FMin and one Round_ne per case; a negated source refused; the half-up, truncating and +negative-passing references differ`. The readback +reported a skip (77) on the NVIDIA Quadro M1000M (driver 32.0.15.7371, debug layer unavailable), because +`native_store_replay` needs shader model 6.6 with wave32. The readback is not measured. diff --git a/docs/experiments/native-direct-cvt-pk16.md b/docs/experiments/native-direct-cvt-pk16.md new file mode 100644 index 000000000..e8696911e --- /dev/null +++ b/docs/experiments/native-direct-cvt-pk16.md @@ -0,0 +1,34 @@ +# v_cvt_pk_u16_u32 and v_cvt_pk_i16_i32 in the direct C++ compute path (#2995) + +The direct compute frontend (`src/gfx1013_direct_compute.inl`) now lowers the two saturating 16-bit packs that it +refused with `direct DXIL lowering for `. The semantics are the `gfx2hlsl.py` VOP3-table expressions. Each +saturates S0 and S1 to 16 bits and packs S0 into the low half and S1 into the high half: + +- `v_cvt_pk_u16_u32`: min(S, 0xffff) of the unsigned values. +- `v_cvt_pk_i16_i32`: the signed values clamped to [-32768, 32767]. + +A nonzero unused SRC2 field is refused (` with unused src2 field set`), as in `gfx2hlsl.py`, and so are the +op_sel bits (` with op_sel`). Source and output modifiers stay refused like the other integer VOP3 forms. + +As `docs/experiments.md` notes for the Python path, the RDNA 2 ISA text does not define the `u32_to_u16` and +`i32_to_i16` conversions. The saturation follows Mesa and the existing translators, and it is not measured on the +console. + +## Fixture + +`tests/native_cvt_pk16_check.py controls|hardware` +(`ctest --preset dev --no-tests=error -R '^native_cvt_pk16_' -V`). Eight operand pairs are set by `v_mov` literals and +converted by both instructions; each of 64 lanes stores the sixteen results. The pairs cross both bounds of both forms: +0, 0xffff, 0x10000, 0xffffffff, -32768, -32769, 32767, 32768, 0x7fffffff and 0x80000000 all occur. The VOP3 words +were assembled with LLVM 15.0.7 (`clang -cc1as -triple amdgcn -target-cpu gfx1013 -filetype asm -show-encoding`). +The other words were checked with `tools/disasm_rdna2.py --hex`. + +- The controls compile the program, refuse the same program with SRC2 = 3 or an op_sel bit, and check that references that truncate + instead of saturating, or that apply the unsigned bound to the signed form, differ from the expected words. The + reference agrees with the `gfx2hlsl.py` table expressions evaluated in Python for all eight pairs. This was checked + once while writing the fixture. + +Measured on 27.11.2026, `cpp-migration` `4ff5e36d` plus this change, Windows 10.0.26100.9711. The controls printed +`compiled; a nonzero src2 field and op_sel refused; the truncating and unsigned-bound references differ`. The readback printed +`requires shader model 6.6 with wave32` and reported a skip (77) on the NVIDIA Quadro M1000M (driver 32.0.15.7371, +debug layer unavailable). The readback is not measured. diff --git a/docs/experiments/native-direct-f16-high-half.md b/docs/experiments/native-direct-f16-high-half.md new file mode 100644 index 000000000..667ac8ad1 --- /dev/null +++ b/docs/experiments/native-direct-f16-high-half.md @@ -0,0 +1,33 @@ +# Binary16 add, sub, subrev and mul keep the destination's high half + +In the direct compute path (`src/gfx1013_direct_compute.inl`), the non-SDWA forms of `v_add_f16`, `v_sub_f16`, +`v_subrev_f16` and `v_mul_f16` wrote the rounded binary16 result to D[15:0] and zeroed D[31:16]. They now keep +D[31:16]. + +- **LLVM:** `GCNSubtarget::zeroesHigh16BitsOfDest` lists exactly these four operations, in both the VOP2 and VOP3 encodings. It states "On gfx10, all 16-bit instructions preserve the high bits" and returns false from GFX10 on. +- **The same path:** `v_cvt_f16_f32` already keeps the high half. +- **#669:** for the non-packed 16-bit integer operations, an inline-assembly measurement on RDNA 2 silicon found the high half kept. + +No silicon measurement of these four f16 operations is known to me. + +SDWA forms still place the result through their `dst_sel` and `dst_unused` fields, and are unchanged. + +## Fixture + +`tests/native_f16_alu_check.py model|ir|gpu` (`native_f16_alu_ir`, `native_f16_alu_hardware`). Every destination +already held `0xabcd` in its high half before the operation. The model, the IR interpreter and the readback now +require each stored word to be `0xabcd` in the high half and the binary16 result in the low half. A zeroed high half +is a rejected mutant, in place of the earlier mutant that rejected a kept one. + +## Measured + +On `cpp-migration` `999e17cd` plus this change, Windows 10 build 19045, NVIDIA GeForce RTX 3080, driver +32.0.15.9174: +- **Model:** 82 results match. +- **IR:** 82 results and 16 refusals match. +- **Readback:** all 164 words match with the high half kept. +- **Old lowering:** with the previous zeroing restored, both the IR check and the readback fail at the first stored word. + +The readback used a local copy of `native_store_replay` linked with the app-local Agility SDK exports +(`D3D12SDKVersion` 620). The registered test reports a skip (77) on Windows 10, whose inbox runtime does not report +shader model 6.6. diff --git a/docs/experiments/native-direct-gather-compare.md b/docs/experiments/native-direct-gather-compare.md new file mode 100644 index 000000000..c257de1f3 --- /dev/null +++ b/docs/experiments/native-direct-gather-compare.md @@ -0,0 +1,45 @@ +# Comparison gather in the direct C++ image path (#2969) + +`image_io` in `src/gfx1013_direct_compute.inl` now lowers `image_gather4_c_lz` (MIMG opcode 79), which +`tools/startup/gfx2hlsl.py` lowers as `op_image_gather4_c_lz`. Before, the direct frontend refused it with +`direct image opcode or descriptor modifiers`, while the same program with `image_sample_c_lz` compiled (the fixture +keeps that control). + +## The form + +- 2D and 2D-array images with `dmask` 0x1. The address is the reference, then u and v (and the slice), as for + the comparison samples of this path. +- The lowering is DXIL `textureGatherCmp` (opcode 74). It uses channel 0, because gather4_c compares the resource's + red component, and takes the reference as its compare value. Like `image_gather4_lz` here, the gather reads the + view's first mip: DXIL gathers have no LOD operand, so the static sampler is fixed to mip zero. +- The sampler is a constant comparison sampler under the existing field checks of `sampler_index` (from + `pixel_aot.comparison_sampler_state`). +- The four results come back in the order DXIL returns them, the same assumption `image_gather4` and + `image_gather4_lz` already make in this path. A console readback is not part of this change. +- This is wider than the `gfx2hlsl.py` contract, which takes the form only in pixel stages, on 2D images and with + a bilinear comparison sampler (`pixel_aot.check_gather_sampler`). Here compute stages and 2D arrays are accepted, + as for the comparison samples of this path, and so is the point filter of the existing comparison field checks. + A gather reads the same four texels whatever the filter (D3D11.3 gather rule; not measured on the console). + +Refused by name (`direct image opcode or descriptor modifiers`): other dmasks, cube and 3D images, +`image_gather4_c` with implicit LOD, `_c_l` and `_c_b`. D16 is refused at decode +(`unsupported image dimension or D16`). Offset forms keep their existing refusal (not covered by the fixture). + +## Fixture + +`tests/native_gather_compare_check.py ` +(`ctest --preset dev --no-tests=error -R '^native_gather_compare_warp$' -V`). The programs reuse +`comparison_program()` of `tests/native_direct_container_check.py`: clamp X/Y, point with TRUNC_COORD, LESS. + +- A compute container compiles. `dxc -dumpbin` shows one `textureGatherCmp` with zero offsets, channel 0 and a float + compare value, and no `textureGather` or `sampleCmp`. +- dmask 0x2, a cube image, a 3D image, D16, `image_gather4_c`, `_c_l` and `_c_b` are refused by message; a 2D + array compiles. The module check traces each float operand to its register: u from v1, v from v2 and the + compare value from v0, the reference. +- `native_recording_check --graphics-sampler` creates, on WARP, the graphics pipeline of + `native_graphics_comparison_pso_warp`, with its comparison sample replaced by this gather. It runs cold and from + the cache, and checks the comparison and regular static samplers. + +Measured on 27.11.2026, `cpp-migration` `b260984f` plus this change, Windows 10.0.26100.9711: all three checks passed +(the pipeline on WARP, Microsoft Basic Render Driver 10.0.26100.9711). The gather results themselves are not read +back. diff --git a/docs/experiments/native-direct-global-load.md b/docs/experiments/native-direct-global-load.md new file mode 100644 index 000000000..c71a3d9ba --- /dev/null +++ b/docs/experiments/native-direct-global-load.md @@ -0,0 +1,56 @@ +# Root-pointer global loads in the direct C++ compute path (#2962) + +The direct compute frontend (`src/gfx1013_compute_native.cpp`, `src/gfx1013_direct_compute.inl`) now lowers +`global_load_dword` in the `saddr` form, the form `tools/startup/gfx2hlsl.py` (`op_global_load_dword`) lowers for +the Python path. Before, the frontend refused it with `unsupported instruction global_load_dword` (measured with +`0xdc308000`). + +## The form + +ADDR = SADDR + zext(VADDR) + sext(OFFSET[11:0]) (RDNA 2 ISA, FLAT/GLOBAL addressing). SADDR must be the unadvanced +root address of a root SRV, with its matching high half: the same symbol and binding (`root_buffer_srv`) the +scalar root loads of this path already use. The load becomes a raw buffer load from that view. + +- The 32-bit byte offset zext(VADDR) + OFFSET is guarded to [0, 2^32): a positive offset reads 0 when VADDR is + above 2^32 - 1 - OFFSET, a negative one reads 0 when VADDR is below -OFFSET. Above the range, the unguarded + 32-bit sum would wrap into an in-bounds word of the view; the fixture shows this case. Below it, the wrapped value + lies near 2^32, outside any view under 4 GiB, so that guard does not change a result here. +- The immediate offset must be a multiple of 4. The low two bits of the address are dropped, as for + `buffer_load_dword` in this path, which assumes the DWORD alignment mode. `gfx2hlsl.py` instead refuses a VADDR it + cannot prove 4-byte aligned; the console's `SH_MEM_CONFIG.ALIGNMENT_MODE` is not measured. +- `glc`, `slc` and `dlc` are accepted (compiled, not measured). +- The binding's minimum size grows to the immediate offset plus 4 bytes for a positive offset; other loads keep + the size the scalar loads need. + +Refused by name: the `off` form (no SADDR), the FLAT and scratch segments, other opcodes (wider loads, stores, +atomics), the `lds` form, an SADDR that is not a root address, a replaced high half, and an unaligned immediate +offset. An SADDR advanced by scalar arithmetic is refused earlier, as an unbound numeric SGPR; `gfx2hlsl.py` accepts +a pointer advanced by a known literal. Graphics stages never decode the FLAT encoding and keep +`unsupported instruction` (not covered by the fixture). + +## Limits + +- Addresses outside the bound view read 0. On the console the same address reads whatever memory lies there: + before the buffer for a negative byte offset, or past the end of the view. The translation then differs from + the guest unless the runtime binds a view that covers every address the program reads. `gfx2hlsl.py` has the + same limit. How the runtime sizes the view on `cpp-migration` was not checked here. +- Only the one-dword load is lowered. + +## Fixture + +`tests/native_global_load_check.py ` +(`ctest --preset dev --no-tests=error -R '^native_global_load_hardware$' -V`). Every word was assembled with +LLVM 15.0.7: `clang -cc1as -triple amdgcn -target-cpu gfx1013 -filetype asm -show-encoding`. + +- Eleven refusals are checked by message, and a load with `glc slc dlc` compiles. +- `dxc -dumpbin` of the dispatch program's module must show six raw buffer loads (five global and one scalar root + load), two upper-bound guards and one lower-bound guard. +- The dispatch (two groups of 32 lanes) reads the root SRV that `native_store_replay` fills with + 0x51aa0000 + dword index, sized to 64 dwords by a scalar load at byte 252. Each lane stores five words: offsets 0, + 16 and -8, a VADDR of 0xfffffff0 or above with offset 16 (guarded to 0), and an unaligned VADDR. References with + the offset dropped or the upper guard dropped must differ from the readback. + +Measured on 27.11.2026, `cpp-migration` `e3670100` plus this change, Windows 10.0.26100.9711 (24H2): the refusals +and the module checks passed. The dispatch reported a skip (77) on the NVIDIA Quadro M1000M (driver 32.0.15.7371), +because `native_store_replay` needs shader model 6.6 with wave32. The readback is not measured. With the frontend +change reverted, the first refusal check fails on `unsupported instruction global_load_dword`. diff --git a/docs/experiments/native-direct-sad.md b/docs/experiments/native-direct-sad.md new file mode 100644 index 000000000..65dd82ece --- /dev/null +++ b/docs/experiments/native-direct-sad.md @@ -0,0 +1,40 @@ +# Sum-of-absolute-differences operations in the direct C++ compute path (#2987) + +The direct compute frontend (`src/gfx1013_direct_compute.inl`) now lowers `v_sad_u8`, `v_sad_hi_u8`, `v_sad_u16`, +`v_sad_u32` and `v_msad_u8`, which it refused with `direct DXIL lowering for `. The results are those of +`gfx2hlsl.py`'s `sad_u8`, `sad4_u8`, `sad_u16` and `sad_u32` helpers and of `tools/pixel_aot.py`. Each adds S2 and +wraps modulo 2^32: + +- `v_sad_u8`: the sum of the four unsigned byte differences |S0 byte - S1 byte|. +- `v_sad_hi_u8`: that sum shifted left by 16. +- `v_sad_u16`: the two unsigned halfword differences. +- `v_sad_u32`: the unsigned difference of the dwords. +- `v_msad_u8`: like `v_sad_u8`, but a byte whose S1 byte is zero contributes nothing. + +Source abs/neg, clamp and output modifiers stay refused, with `direct ALU operand modifiers` as for the other +integer VOP3 forms. The fixture checks clamp. + +## Fixture + +`tests/native_sad_check.py controls|hardware` (`ctest --preset dev --no-tests=error -R '^native_sad_' -V`). The +words were assembled with LLVM 15.0.7 (`clang -cc1as -triple amdgcn -target-cpu gfx1013 -filetype asm +-show-encoding`). + +- The dispatch has two groups of 32 lanes. With n = lane + 32 * group: + - S0 = mul_u32_u24(n, 0x050311) ^ 0x80f00a33 + - S1 = mul_u32_u24(n, 0x010203) & 0xffff00ff. Byte 1 is always zero, so `v_msad_u8` skips it. + - S2 = mul_u32_u24(n, 0x1001) + + S0 bytes both above and below the S1 bytes occur. The 320 results and the guard words are compared with a CPU + reference. +- That reference agrees, for all 64 lanes, with the existing references in `tests/startup_gfx2hlsl_sad_check.py` + (`ref_sad_u8`, `ref_sad_u16`, `ref_sad_u32`) and `tests/startup_gfx2hlsl_sad_hi_msad_check.py` (`sad4_u8`). + This was checked once by hand while writing the fixture; the fixture does not import those files. +- The controls compile the program and refuse the `v_sad_u8` form with the clamp bit. They also check that four + mutated references each differ from the expected words: signed byte differences, `v_msad_u8` without its mask, + `v_sad_hi_u8` without its shift, and S2 dropped. + +Measured on 27.11.2026, `cpp-migration` `4ff5e36d` plus this change, Windows 10.0.26100.9711. The controls printed +`compiled; clamp refused; the signed, unmasked, unshifted and S2-dropped references each differ`. The readback +printed `requires shader model 6.6 with wave32` and reported a skip (77) on the NVIDIA Quadro M1000M (driver +32.0.15.7371, debug layer unavailable). The readback is not measured. diff --git a/docs/experiments/native-direct-signed-forms.md b/docs/experiments/native-direct-signed-forms.md new file mode 100644 index 000000000..7aa95187b --- /dev/null +++ b/docs/experiments/native-direct-signed-forms.md @@ -0,0 +1,36 @@ +# v_ashrrev_i64 and v_mad_i32_i24 in the direct C++ compute path (#2991) + +The direct compute frontend (`src/gfx1013_direct_compute.inl`) lowered `v_lshrrev_b64`, `v_lshlrev_b64` and +`v_mad_u32_u24`, but refused their signed counterparts with `direct DXIL lowering for `. It now lowers them: + +- `v_ashrrev_i64`: an arithmetic `ashr i64` of S1 by S0[5:0]. The shifted value takes the operands of the + logical shifts: a VGPR or SGPR pair, an inline integer sign-extended to 64 bits, or a 32-bit literal. Following + `gfx2hlsl.py` `i64_words(signed=True)`, the literal is sign-extended for this form, where the logical shifts + zero-extend it. +- `v_mad_i32_i24`: sext(S0[23:0]) * sext(S1[23:0]) + S2 modulo 2^32, the `gfx2hlsl.py` VOP3-table expression. + +## Fixture + +`tests/native_signed_forms_check.py controls|hardware` +(`ctest --preset dev --no-tests=error -R '^native_signed_forms_' -V`). The words were assembled with LLVM 15.0.7 +(`clang -cc1as -triple amdgcn -target-cpu gfx1013 -filetype asm -show-encoding`). + +- The controls check the modules with `dxc -dumpbin`: exactly one `ashr i64` per shift program, and an arithmetic + shift right with `mul i32` for the multiply-add. +- The shift dispatches reuse `native_shift64_check.compute_program` with the `v_ashrrev_i64` opcode (VOP3 0x301). + They cover shift amounts 0, 1, 31, 32, 33 and 63 and six sources: inline -1, -16, 64 and 1, the literal 0x80000001 + and the negative SGPR pair 0x89abcdef:01234567. References with a zero-extended literal or a logical shift must + differ from the expected words. +- The multiply-add dispatch uses, with n = lane + 32 * group: + - S0 = mul_u32_u24(n, 0x05f3d1) ^ 0xa5800000 + - S1 = mul_u32_u24(n, 0x0371) ^ 0x7f9abcde + - S2 = mul_u32_u24(n, 0x1001) + + Bit 23 is set in many factors and the bits above it are not zero. References with unsigned or unmasked factors + must differ. + +Measured on 27.11.2026, `cpp-migration` `4ff5e36d` plus this change, Windows 10.0.26100.9711. The controls compiled all +programs and printed `compiled six v_ashrrev_i64 sources and v_mad_i32_i24; the zero-extended-literal, logical, +unsigned and unmasked references each differ`. `native_shift64_controls` still passes. The readback printed `requires +shader model 6.6 with wave32` and reported a skip (77) on the NVIDIA Quadro M1000M (driver 32.0.15.7371, debug +layer unavailable). The readback is not measured. diff --git a/docs/experiments/native-dpp-quad-compute.md b/docs/experiments/native-dpp-quad-compute.md new file mode 100644 index 000000000..1329cad34 --- /dev/null +++ b/docs/experiments/native-dpp-quad-compute.md @@ -0,0 +1,41 @@ +# DPP16 quad_perm in the direct C++ compute path + +Issue #2936 covers DPP16 control values 0–255 with full row and bank masks. +The decoder retains the reserved-bit check and decodes FI, BOUND_CTRL, abs and +neg. The compute emitter uses the destination lane's low two bits to select a +two-bit field in the control byte. It adds that field to the base of the +destination lane's quad and reads source 0 from that physical wave32 lane. +Quads fit within each physical half of a split guest wave64. + +Without FI, the guest EXEC bit of the selected source decides whether it can +be read. BOUND_CTRL supplies a zero source for a disabled lane. With +BOUND_CTRL clear, the instruction preserves the old destination. FI reads the +last VGPR value from a disabled source. Destination writes still obey EXEC. +The arithmetic and modifier checks are shared with the row mirror lowering. + +## Refused forms + +Compute requires a group size divisible by four for quad permutations. +Controls above 255 still require a supported row mirror pattern. Row shifts, +rotates, broadcasts, row_share and row_xmask are refused. + +## Verification + +`native_dpp_quad_controls` checks compilation of a valid swap and named +refusals for row_shl:1 and a 30-thread group. +`native_dpp_quad_hardware` compares both workgroups and buffer guards against +an independent CPU model. The fixtures cover integer OR and float add with +pairwise swaps, reverse subtraction with quad-local broadcast, identity, +rotation and the three disabled-source behaviors. The rotation exposes +reversed field order and the sparse EXEC add exposes ignored BOUND_CTRL. +Hardware without shader model 6.6 and wave32 support returns skip code 77. + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_dpp_quad_(controls|hardware)$' +``` + +On an NVIDIA GeForce RTX 5080 (Windows 11, DXC from the Windows SDK 10.0.26100) both tests passed: all eight +hardware programs matched the CPU reference for both groups and the guard words, and the controls refused +`row_shl:1` and a 30-thread group. Reading the permutation in reversed lane order fails the first case, and +ignoring BOUND_CTRL fails the disabled-source zero case. diff --git a/docs/experiments/native-dxil-llvm-ident.md b/docs/experiments/native-dxil-llvm-ident.md new file mode 100644 index 000000000..9ea877b98 --- /dev/null +++ b/docs/experiments/native-dxil-llvm-ident.md @@ -0,0 +1,63 @@ +# Direct DXIL `!llvm.ident` metadata for AMD RDNA 4 pipeline creation (#2915) + +[The fixture](../../tests/native_dxil_llvm_ident_check.py) verifies that every direct DXIL emitter in +`src/dxil_module.h` (`DxilModule::finish_compute`, covering `cs`, `vs`, `gs`, and `ps`) and +`src/gfx1013_pixel.cpp` (`x2w::direct_gfx1013_constant_pixel`) emits `!llvm.ident = !{!}` (`!{!"x2w"}`), +and draws both direct pixel paths on WARP and hardware with negative controls. + +## Cause of the AMD `0xC0000005` PSO crash + +On `cpp-migration` (`40365770`..`ee76dfa8`), all direct-DXIL `_hardware` tests crashed with `0xC0000005` +inside `amdxc64.dll` during `CreateComputePipelineState` and `CreateGraphicsPipelineState` on an +AMD Radeon RX 9070 XT (`1002:7550`, driver `32.0.32029.2010`), even though `IDxcValidator::Validate` +accepted every container and both WARP and NVIDIA passed: + +- `native_scalar_lds_hardware` +- `native_adjacent_srv_hardware` +- `native_mtbuf_hardware` +- `native_indexed_atomic_hardware` +- `native_dpp_mirror_hardware` +- `native_graphics_wqm_hardware` +- `native_graphics_vertex_vcc_join_hardware` + +Comparing disassembled DXIL modules (`dxc.exe -dumpbin`) re-assembled through `IDxcAssembler::AssembleToContainer` +and `IDxcValidator::Validate` isolated the crash to a single missing named metadata entry: + +- Re-assembling DXC's `ps_6_6` output passed (`rc = 0`, `debug_errors=0 debug_warnings=0`). +- Re-assembling `DxilModule` output as-is crashed (`0xC0000005`), and bumping `!dx.valver` to `1.8` or `1.9` + alone still crashed (`0xC0000005`). +- Adding `!llvm.ident = !{!}` (`!{!"x2w"}`) alone made the identical `DxilModule` IR pass (`rc = 0`, + `debug_errors=0 debug_warnings=0`). + +`dxc.exe` always emits `!llvm.ident`; `IDxcValidator` treats it as optional, whereas `amdxc64.dll` queries +`llvm::Module::getNamedMetadata("llvm.ident")` and dereferences the returned `NamedMDNode*` (`[rcx + 0x40]`) +without a null check. + +## Verification and negative controls + +1. **`container` mode (`native_dxil_llvm_ident_controls`):** compiles source-built shaders across + `gfx1013-container-cs`, `gfx1013-container-vs`, `gfx1013-container-ps`, `gfx1013-container-rect` + (`vs`, `gs`, `ps`), and `gfx1013-direct-constant-ps`, checks `dxc.exe -dumpbin` for `!llvm.ident` + resolving to `!"x2w"`, and runs a negative control that strips `!llvm.ident`, re-assembles + validates + through `dxcompiler.dll` / `dxil.dll`, and verifies the `!llvm.ident` check rejects the stripped module. +2. **`draw` mode (`native_dxil_llvm_ident_warp`, `native_dxil_llvm_ident_hardware`):** pairs a direct-DXIL + fullscreen-triangle vertex shader (`gfx1013-container-vs`) with `gfx1013-direct-constant-ps` and + `gfx1013-container-ps` on an `8x2` float target, checks bit-exact RGBA readback and zero D3D12 debug-layer + errors/warnings, and requires mutated-channel negative controls on each path to fail readback. + +```powershell +cmake --build --preset release --target compile_dxil native_store_replay native_recording_check offscreen_check +ctest --preset release --no-tests=error -V -R "^native_dxil_llvm_ident_(controls|warp|hardware)$" +``` + +Verified on Windows 11 (`10.0.26100`), Release build, with the D3D12 debug layer enabled (`0` errors, `0` warnings) +across Microsoft Basic Render Driver (`1414:008c`, driver `10.0.26100.9818`) and AMD Radeon RX 9070 XT (`1002:7550`, +driver `32.0.32029.2010`), alongside all seven direct-DXIL `_hardware` tests listed above. + +## Limits + +- The committed `draw` check does not execute the stripped negative-control container on a GPU adapter, because + triggering an access violation inside a user-mode driver is driver-version-dependent rather than a D3D12 + contract. +- The separate adapter-independent decoder refusal message in `native_wave_request_hardware` is tracked independently + on #2915. diff --git a/docs/experiments/native-global-srv-heap-replay.md b/docs/experiments/native-global-srv-heap-replay.md new file mode 100644 index 000000000..9d8910357 --- /dev/null +++ b/docs/experiments/native-global-srv-heap-replay.md @@ -0,0 +1,139 @@ +# GPU-selected global SRV heap slots: capture and replay of view types + +Issue #2908, branch `cpp-migration`. Builds on the heap read in the direct C++ DXIL path from #2912 +(`ResourceDescriptorHeap[slot]` for a raw buffer read, `src/gfx1013_direct_compute.inl` `heap_resource`). + +## What changed + +- The direct compute translation takes a view contract for a GPU-selected heap slot (`x2w::HeapViewContract`: + `none`, `raw_buffer`, `other`). An SMEM descriptor load from the resource heap is refused unless the contract is + `raw_buffer`; without a contract the existing text stays: "direct resource-heap load requires the selected GPU slot and + its view type". A scalar buffer load from the heap base, a heap descriptor load with an immediate offset or a constant + index (both could address another slot than the captured selection), and a numeric use of a GPU-selected slot's + stride in the direct path are refused with their own texts. The contract is part of the frontend cache key when it is + not `none`. +- Byte-address rewrite (#3023): under `raw_buffer` the direct path tracks the rewrite of the loaded heap descriptor that + `byte_descriptor_field` already models for table descriptors (`s_bfe_u32 ... 0xe0010` stride, `s_max_u32 ... 1`, + `s_mul_i32` byte count, `s_and_b32 ... 0xc000ffff`, `s_and_b32 ... 0xcfffffff`, `s_or_b32 ... 0x30000000`, word 0 + copied). A raw load through the rewritten descriptor reads the same `ResourceDescriptorHeap[slot]` raw view. The words + must all come from one heap load (same pc). As a precaution, a backward branch whose loop contains that heap load + refuses the window, because the loop would run the load again for another selection. Loops elsewhere in the program + do not refuse it. The caller's contract: every slot the + program can select is a raw view of exactly `num_records * max(stride, 1)` bytes; the translator does not check that, + nor the swizzle bits or the other word 3 fields. Without the contract the first refusal stays as before. +- Modules that read `ResourceDescriptorHeap` now also set shader flag `0x40000000`, as DXC does for the HLSL reference. + Without it the validator refuses the module ("Flags must match usage. Validation failed."), measured by removing the + flag and running the hardware test. +- `src/startup_stubs/native_global_srv.h` writes and reads version 2 of the view metadata, which adds the buffer size: + + ``` + x2w-global-srv-views 2 + select + need + slot + ``` + +- `compile_dxil ... gfx1013-container-cs` reads an optional `req_.views` next to the `.cdx` (single file and + `--requests`). It decodes the file, refuses a selection whose slot holds another view type than `need`, refuses a `need` + other than `raw_buffer`, translates with the `raw_buffer` contract and prints `global_srv select= need=`. Every + refusal happens before the `.cso` is published. Without the file a heap-reading shader is refused as before. The + `.views` file is not part of the `.cdx`/`.root` content key: it describes one captured dispatch. + +## Meaning of "native recording" and "runtime path" here + +The issue's reproduction names `native_recording_check` and `native_dispatch_states_warp`, which test +`x2w_startup::NativeRecording` (descriptor-table pages) and `x2w_startup::NativeDispatchStates` (dispatch barriers). On +`cpp-migration` only tests use these classes. The D3D12 stand-in translates slot 67 requests natively since #2958 +(opt-in `X2W_NATIVE_SHADERS`) through `translate_compute` without a heap view contract, so a GPU-selected heap read is +still refused there; passing captured views into that path is follow-up work. The fixture's `record` +mode records the dispatch with both classes and applies the view guard before `Dispatch`; that is the native recording +path checked here, and its unchanged UAV sentinels are the "runtime path" sentinels of the issue. The startup runtime +itself is not covered. + +The slot is selected by GPU data. The `record` mode reads the selector back from its GPU buffer before recording the +dispatch (one copy to a readback buffer and one fence per recorded dispatch) and uses that value as the captured +selection, so the guard checks the slot the GPU input actually selects, before the shader runs. + +## Fixture + +`tests/native_global_srv_heap_replay.cpp` with `tests/native_global_srv_heap_replay_check.py`. A source-built compute +container (two root inputs: a descriptor table in s[0:1], the descriptor heap in s[2:3]; instruction words assembled with +LLVM 15 `clang -cc1as -triple amdgcn-amd-amdhsa -target-cpu gfx1013 -show-encoding`) loads the selector from t0, loads +the descriptor of `ResourceDescriptorHeap[selector]`, reads 64 words through it and stores them to u0. Heap slots: 0 and +1 raw buffers with different data, 2 a Texture2D, 3 a typed buffer. u0 holds 72 words; the last 8 and, on a refused +selection, all 72 must keep the sentinel `0x69696969`. + +The check runs, in order: + +1. `compile_dxil --requests` on the request without `.views`: refused with the heap text, no `.cso`. +2. `record` for selections 0 and 1: fenced output equals the selected slot's data, sentinels intact, `.views` captured. + Selections 2 and 3: "global SRV slot 2 has view type texture, the shader needs raw_buffer" (and `typed_buffer` for 3) + before the dispatch, nothing dispatched, sentinels intact. +3. Discrimination control: `record --no-guard` on slot 0 expecting a refusal sees the changed sentinels (exit 3). A + texture slot is not dispatched without the guard: reading a texture descriptor as a raw buffer is undefined in D3D12. +4. `compile_dxil --requests` on each captured selection: 0 and 1 compile, 2 and 3 are refused with the slot/type text + and publish no `.cso`. +5. `replay` of the compiled `.cso` for 0 and 1 matches the CPU reference; the `.views` of 2 and 3 are refused before the + dispatch with sentinels intact. +6. Mutation control: replaying selection 0 against the slot 1 reference reports a mismatch. +7. Negative controls on both `compile_dxil` and `replay`: slot 0 rewritten to `texture`, no `need` line, no `select` + line, no line for the selected slot, `select 7`, and (replay) a missing `.views` file. Each gives an explicit + diagnostic, no `.cso`, and intact sentinels. +8. Shader shapes refused by `compile_dxil` even with valid metadata: a constant heap index, a heap descriptor load with + an immediate offset, a stride read used as a number (`unbound numeric SGPR s24`), and four byte-address rewrites the + raw slot view cannot stand for: a wrong stride mask (`unbound numeric SGPR s21`), word 0 from a second heap load + (`non-contiguous resource descriptor`), a store through the rewritten descriptor (`a GPU-selected heap slot is read + as a raw buffer SRV only`) and a never-taken backward branch to (or before) the heap load (`heap byte window loaded + inside a loop`). +9. The byte-address rewrite: a stride read that nothing uses compiles, a never-taken backward branch after the heap + load (the loop does not contain the load) compiles, and the program with the full rewrite is recorded + for selections 0 and 1 (output equals the slot's data), compiled by `compile_dxil --requests`, replayed with the + same result, and replaying selection 0 against the slot 1 reference reports a mismatch. + +## Result + +``` +cmake --preset dev +cmake --build --preset dev +ctest --preset dev --no-tests=error -R "^native_global_srv_heap_replay(_warp|_hardware)?$" -V +``` + +- `native_global_srv_heap_replay_hardware`: passed, 70 assertions (NVIDIA GeForce RTX 3080, driver 32.0.16.2124, + Windows 11 build 26200, MSVC toolset 14.51.36231, Windows SDK 10.0.26100 DXC, D3D12 debug layer not enabled). +- `native_global_srv_heap_replay_warp`: skipped (77), "adapter has no 32-lane waves (4..4)". The native module declares + `WaveSize=32`; WARP offers 4-lane waves only. The skip is not evidence for the fixture. +- `ctest --preset dev --no-tests=error -R ^native_ -j 1`: same result as before the change apart from the two new tests + (one known failure, `native_wave_request_hardware`, #2915, addressed by #2928). +- Revert control: with the heap refusal restored for every contract, `record` for selection 0 exits 4 with "direct + resource-heap load requires the selected GPU slot and its view type". +- Byte-address rewrite (#3023): `native_global_srv_heap_replay_hardware` passed, 83 assertions, on the same machine and + driver. The check run against `compile_dxil` and the fixture built at `999e17cd` (before the change) fails at + `stride_read` (old text "a GPU-selected heap slot stride read is not translated with a view contract") and, with the + shapes skipped, at "an unused stride read compiles" (the run stops there, so the full-rewrite record step was not + reached on that build). `ctest --preset dev --no-tests=error -R + "native_|startup_compute_dispatch|compute_heap" -j 6`: 147 tests, 142 passed, 4 skipped (77, WARP), 1 failed + (`native_cvt_pk_u8_hardware`, failing before the change as well). `compile_dxil --refusals` on a local start-up + capture gives the same output as before (it translates without a contract). +- Loop guard narrowed: the first version of the guard refused the window for any backward branch in the program. + With the contract forced locally (an uncommitted switch), it refused 921 of the 2,689 requests of the same capture. + With the guard limited to loops around the heap load, none of these is refused for a loop; 906 then stop at a typed + load (`buffer_load_format_*`) through the heap descriptor. After the change, the test passes with 84 assertions. The + run against the earlier commit `7582c01d` fails at the `window_loop` shape (old text "heap byte window in a program + with a backward branch"). The run stops there. + +## Limits + +- Only raw buffer heap reads are translated; other view classes are refused with a named diagnostic. +- The selected slot's index is per-lane VGPR data in general; reads stay inside the raw buffer view, which returns 0 + out of bounds. No static index bound is checked. +- Replay regenerates the slot contents deterministically from the slot index; `.views` captures type, stride and size, + not contents. +- In the direct DXIL path a GPU-selected slot's stride is never a number: it is tracked symbolically and only the + byte-address rewrite consumes it. The fixture's descriptor words are never evaluated, so a stride above 1 and the + size rule of the contract are not exercised. The HLSL path's `heap_stride_srv` (`src/gfx1013_compute_native.cpp`, + used by `tests/native_compute_grid.cpp`) is unchanged. +- Typed loads (`buffer_load_format_*`) through a heap descriptor and scalar loads through the rewritten descriptor stay + refused. The startup runtime + does not pass a contract yet, so none of this reaches a title run (#3023). +- The captured `select` must be the slot index the dispatch addresses; producing it from a title capture is outside this + fixture. diff --git a/docs/experiments/native-graphics-wqm-cross-quad.md b/docs/experiments/native-graphics-wqm-cross-quad.md new file mode 100644 index 000000000..74d4946d3 --- /dev/null +++ b/docs/experiments/native-graphics-wqm-cross-quad.md @@ -0,0 +1,110 @@ +# Cross-quad WQM/EXECZ in a native pixel draw (#2907) + +[The fixture](../../tests/native_graphics_wqm_check.py) draws source-built gfx1013 pixel stages through the +direct DXIL frontend. In each one, an `s_cbranch_execz` under WQM decides a scalar that every surviving pixel +exports. The branch is skipped only when EXEC is zero in the whole guest wave. A quad with no EXEC bit at the +branch therefore still sees whether another quad of its wave kept the wave from skipping. + +## The accepted form + +``` +s_mov sE, exec ; s_wqm exec, exec +v_cmp_* vcc, ... ; s_andn2 sE, sE, vcc one or more coverage filters +v_cmp_* vcc, ... ; s_andn2 sM, sE|exec, vcc the branch mask, from the survivors or the whole-quad EXEC +v_cmp_* vcc, ... ; s_andn2 sM, sM, vcc optional further terms +s_wqm exec, sM ; s_cbranch_execz J the region writes only scalars +J: s_mov exec, sE then a terminal colour export +``` + +Following the maintainers' decision on the issue, the branch condition is `WaveActiveAnyTrue` of the +quad-complete EXEC bit: +- the modelled mask predicate is OR-ed with its `QuadReadAcrossX`, `QuadReadAcrossY` and + `QuadReadAcrossDiagonal`; +- quad reads see helper lanes, so a quad whose EXEC bits sit only on helpers or on covered pixels that did + not survive still votes, as it does on the guest; +- all of this uses Shader Model 6.0 operations, with no `[WaveOpsIncludeHelperLanes]`. + +The calls are emitted before the first conditional branch, where the whole quad still runs. The IR test checks +this, and checks that their declarations carry the attributes DXC gives the HLSL intrinsics. + +These still keep a refusal by name: +- inside the region: a vector or DPP instruction, an EXEC or VCC read, a hardware register access + (`s_setreg`/`s_getreg`), a branch, or an EXEC write other than the restore; +- a restore that is not the branch target; +- a second branch; +- anything after the restore other than lane-local ALU and colour exports. + +`raster_program(2.5, cross=True)` keeps its existing refusal. + +## Contract and what this shows + +The lowering decides the branch once per **desktop** wave. It relies on the packing contract of #2835 and +#2854: a correct program cannot depend on which quads the console puts in one wave. A program can only see the +branch outcome through an effect outside EXEC, here an SGPR. This fixture builds such a dependency on purpose, +so its reference comes from the measured desktop layout. + +**The draws show that the lowering votes over the desktop wave. They do not show equivalence with the console +for an output that depends on another quad.** + +## Measured layout + +Two HLSL pixel stages on the same draw report, for every covered pixel: +- its wave: the smallest covered id in it; +- the ids of its three quad peers; +- whether each peer is a helper (`IsHelperLane`, SM 6.6). + +Wave operations leave helpers out, so the helper flags come from quad reads. The fixture checks that every +desktop quad is the aligned 2x2 block, and that all covered lanes of a quad report the same quad. Quads are +per primitive. On WARP the two middle quads of the 8x2 target are each shaded twice, once with each row covered +and the other row as helpers, as if the full-screen triangle were drawn as two primitives. The layout is +measured in separate draws with the same vertex stage and target. The reference follows the measured quads. + +| Adapter | Lanes | Full draw | Diagonal draw | +|---|---|---|---| +| NVIDIA GeForce RTX 3070, driver 32.0.16.2101 | 32 | 4 quads in 1 wave, no helpers | 3 quads in 1 wave, 3 helpers | +| Microsoft Basic Render Driver, 10.0.26100.9818 | 4 | 6 quads in 6 waves, 8 helpers | 5 quads in 5 waves, 11 helpers | + +## Cases and controls + +| Draw | Mask | Shows | +|---|---|---| +| full | survivors with x <= 1 (14 survivors) | another quad's survivors keep the wave from skipping | +| full | survivors with x <= 4.5 (all 16) | as above, one quad without bits | +| full | x <= -1 | empty wave: the branch is taken, every vote agrees | +| full | whole-quad EXEC with x >= 4.5, survivors x <= 3.5 | bits only on covered pixels that did not survive | +| full | survivors with x >= 4.5 | no bits: WQM never makes a zero mask non-zero | +| diagonal | whole-quad EXEC, x >= 5, y >= 1 | the bit only on the diagonal helper of (4,0) | +| diagonal | whole-quad EXEC, x >= 5, y <= 1 | the bit only on the horizontal helper | +| diagonal | whole-quad EXEC, x = 4..5, y >= 1 | the bit only on the vertical helper | + +Each case is drawn against the measured-layout reference. Each control redraws the same program against a +different reference and must differ: +- a quad-local vote; +- a wave vote without the quad OR; +- a vote over surviving pixels only. + +Pixels outside exact coverage keep the clear value -1.0. + +## Command and result + +```powershell +cmake --build --preset dev --target compile_dxil offscreen_check native_store_replay native_pixel_ir_dump +ctest --preset dev --no-tests=error -V -R '^native_graphics_wqm_(hardware|warp|ir)$' +``` + +See the pull request for the measured counts. +- **On the RTX 3070** every control differs. +- **On WARP** (one quad per wave), the quad-local control cannot differ, and the test prints + `SKIPPED cross-quad quad-local control`. The three helper cases still differ from the no-OR and survivor + votes, at pixel (4,0). +- On a physical adapter with no wave holding two quads, the hardware entry exits 77 after the other checks. + +## Limits + +- **Helper lanes after the vote:** wave intrinsics are undefined on helper lanes, so the branch may diverge for + them. That is safe only while nothing after the branch reads another lane. +- **Adapters:** a 64-lane adapter has not been run. The RX 9070 XT is blocked by #2915. AMD and Intel have + not been run. +- **Programs:** only the form above is accepted. Real programs and captures have not been run. +- **Clipping:** a console that clips or splits primitives differently from the desktop forms different quads. + This holds for the existing quad-local path too. diff --git a/docs/experiments/native-lane-access-compute.md b/docs/experiments/native-lane-access-compute.md new file mode 100644 index 000000000..d6767e2ca --- /dev/null +++ b/docs/experiments/native-lane-access-compute.md @@ -0,0 +1,32 @@ +# Lane access in direct compute DXIL + +This experiment covers numeric SGPR spill and refill through VGPR lanes +(#2940). A lane selector is masked to the guest wave width. Split guest +wave64 reads exchange the values from the two physical wave32 halves. +Lane writes select a guest lane independently of EXEC. Scalar lane reads +can target `vcc_lo` and `vcc_hi` in direct compute. In wave32, `vcc_hi` +(SGPR 107) holds ordinary scalar data and VCC uses only `vcc_lo`. A +wave32 scalar pair read of VCC reads s106 and s107, as the hardware does. In +wave64, `vcc_hi` holds the high half of the VCC mask. Refills carry +numeric values and clear the destination's symbolic provenance. + +The source-built hardware fixture compares two 32-thread workgroups with +a CPU reference and checks the untouched buffer words. It covers constant +and SGPR selectors, writes to an EXEC-disabled lane, and lane reads feeding +VCC. It also reads back wave32 `vcc_hi` after both lane-read instructions +and a scalar move, and checks the high word of a pair move from VCC. +Compile controls exercise partial waves, out-of-range direct lane-read +destinations, and HLSL-native lane reads targeting either VCC register. +Graphics lane reads also reject both VCC destinations. + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_lane_access_hardware$' +``` + +On an NVIDIA GeForce RTX 5080 (Windows 11, DXC from the Windows SDK 10.0.26100) the test +matched all 768 lane-access words and the guards in both workgroups. Reading lane `lane ^ 1`, +letting `v_writelane_b32` honour EXEC, reading `vcc_hi` as zero in wave32, and reading the high word of a +wave32 VCC pair as zero each fail it. +The fixture is one 32-thread wave32 group per workgroup; the wave64 half selection and the +accepted partial-wave constant lane are not exercised. diff --git a/docs/experiments/native-rtv-variant-requests.md b/docs/experiments/native-rtv-variant-requests.md new file mode 100644 index 000000000..37abd967f --- /dev/null +++ b/docs/experiments/native-rtv-variant-requests.md @@ -0,0 +1,148 @@ +# RTV variant requests in `compile_dxil --requests` (#2980) + +[The fixture](../../tests/native_rtv_variant_check.py) gives `compile_dxil gfx1013-container-pair --requests` a +directory with one source-built VS/PS base request and RTV variant requests that share its base key. It checks the +published entries, their format metadata and, through the stand-in, a fenced readback of a target of each format. + +## What changed + +1. **Reader (`src/shader_compute_request.cpp`).** `read_graphics_request` accepts `req_.rtv`. The text is + checked as `tools/startup/gfx2hlsl.py::request_source` checks it: at most 256 bytes, `rtv1 + ...` in decimal with one to eight formats and nothing else, and the FNV-1a hash of the text equal to + the key in the file name (`invalid RTV variant request`); the base key at most 64 bits and each format at most + 32 bits (`invalid RTV variant values`). The base parts `req_.{a,b,root}` and the optional `.ia` and + `.psin` are then read and checked against the base key by the existing base path. Its refusals are prefixed + with `RTV variant source: `. +2. **Translation (`src/direct_compute_cache.cpp`, `src/gfx1013_direct_graphics.inl`).** The ordered formats type + the pixel stage's color targets as `mrt_kind` does in `gfx2hlsl.py`: `u32` or `i32` for the integer formats, + `f32` for every other format. `R32G32B32_UINT` (7) and `R32G32B32_SINT` (8) have no verified readback there + and are refused as `unverified UINT RTV format 7` and `unverified SINT RTV format 8`, as there only when the + pixel stage exports to that target. A float32 target needs no extra mechanism: the pixel stage stores the + register bits as a float. +3. **Cache and manifest.** The target types are part of the `.pairir` key, so formats of one type share a + frontend entry. A base request adds nothing to its key, and its translation takes the same path as before. + (The frontend sources feed `X2W_NATIVE_SHADER_REVISION`, so existing `.pairir` entries are rekeyed once, as + with any frontend change.) The runtime manifest accepts an integer target only for the variant whose format + asked for it, and ends with the request text, which the runtime compares with the request it made. The entry + is published as `.vs.cso`, `.ps.cso` and then `.txt`. +4. **Tool (`tools/startup/compile_dxil.cpp`).** The pair profile scans `req_.rtv` next to `req_.a`. The + report line is `rtv_variant types=,...`. A variant whose pair has no runtime manifest (an + input layout or vertex fetch, for example) is refused as `RTV variant has no runtime manifest`, where a base + pair still publishes its stages. A key with both markers is one request, the variant, as in `request_source`. + The rectangle profile does not take variants. + +Two differences from `gfx2hlsl.py`, both refusals where it translates: it types a target by the format alone, +while a container whose own output signature gives another type is refused here (`RTV variant format disagrees +with the pixel signature of target N`); and it has no runtime-manifest condition. + +The stand-in is not changed. It already publishes `req_.rtv` and loads `.txt`. + +## Pair, formats and expected values + +The vertex container covers the viewport from the vertex index. The pixel container moves the words `ffff7ffe`, +`15`, `eb` and `68` into `v0..v3` and exports them to MRT0. + +| Request formats | Target types | `SV_Target0` in the compiled stage | Expected MRT0 bytes | +|---|---|---|---| +| `R16G16B16A16_UINT` (12), `R8G8B8A8_UNORM` (28) | `u32,f32` | `uint` | `ffff 1500 eb00 6800`: the first word clamps to 65535 | +| `R16G16B16A16_SINT` (14), `R8G8B8A8_UNORM` (28) | `i32,f32` | `int` | `0080 1500 eb00 6800`: the first word, -32770, clamps to -32768 | +| `R32G32B32A32_FLOAT` (2) | `f32` | `float` | `fe7fffff 15000000 eb000000 68000000`: all four words bit for bit, the first a NaN with a payload | + +For the two integer formats the consumer binds a second RGBA8 target, which the pixel stage does not write. It +keeps the clear value `0000ffff`. The base pair drawn to an RGBA8 target stores `00000000` over the blue clear +(a NaN and three denormals as UNORM). + +## Controls + +`native_rtv_variant_controls` needs no device: + +1. The base, the three variants of the table and a fourth, `R16G16_UINT` (36) with RGBA8, compile from an empty + compiler cache with `--jobs 4` (`requests=5 compiled=5 refused=0`). The two UINT variants have the same target + types and share one frontend entry. Each variant manifest is the base manifest plus the request line, the + report names the types, and `dxc -dumpbin` shows `SV_Target0` as `uint`, `int` and `float`. The base manifest + has no `rtv1` line and its pixel stage is `float`. A second run reports a frontend cache hit and two bytecode + cache hits for every request and publishes the same bytes. `gfx2hlsl.pending_keys` then lists nothing. +2. Refusals, each leaving only `.fail` with the reason under the variant key (the `.fail` lifecycle of + [#2984](native-compile-dxil-refusals.md)): a forged variant key, base content that no longer + matches the base key, no format, nine formats, a format above 32 bits, a trailing newline, a missing base, + format 7 and format 8 in the exported slot, and a forged variant file under the base's own key. Where the + base request is intact, it still compiles (`compiled=1 refused=1`). Format 7 in the slot the pixel stage does + not export to compiles (`types=u32,u32`); moved to the exported slot it is refused although the frontend entry + of those types is cached by then. A base with an input layout publishes its stages without a manifest, as + before; its variant is refused for having none, and again when the layout no longer matches the base key. +3. A published variant whose base then changes is refused on the next run (`requests=5 compiled=0 refused=5`) + and no `.txt` is left in the directory. +4. With a pixel container whose output signature says `uint`, the UINT variant compiles, the FLOAT variant is + refused by name, and the base pair publishes no manifest, as before. + +`native_rtv_variant_{warp,hardware}`: the consumer creates the pair through device slot 86 and draws one pixel +into a target of each format, so the stand-in publishes the base request and the three variant requests. The +tool compiles the directory cold and warm with the checks of step 1. The consumer then draws each format in a +new process. The log names the desktop pipeline for the variant key with the bound formats (`0x00000000`) and the +drawn call, and the readback after the fence equals the table above. The base pair is drawn last. + +## Command and result + +```powershell +cmake --preset dev # run here with -DINTAKE_PYTHON=, the worktree having none +cmake --build --preset dev +ctest --preset dev --no-tests=error -V -R '^native_rtv_variant_' +``` + +Commit `be9a0706` on `cpp-migration` at `4ff5e36d`, Windows 11 build 26300.9974, Debug build, Windows SDK +10.0.26100 DXC, D3D12 debug layer enabled. + +| Test | Adapter, driver | Result | +|---|---|---| +| `native_rtv_variant_controls` | none (no device) | PASS. | +| `native_rtv_variant_hardware` | NVIDIA GeForce RTX 4090, 32.0.16.1088 | PASS. The three readbacks match the table. No debug-layer error message. | +| `native_rtv_variant_warp` | Microsoft Basic Render Driver, 10.0.26100.9818 | PASS. The three readbacks match the table. No debug-layer error message. | + +Release: the same commit built with the `release` preset (`cmake --preset release`, `cmake --build --preset +release`, `ctest --preset release` with the same filters; MSVC 19.44.35230) on the same machine. The three tests +pass on both adapters with the same readbacks and no debug-layer error message, the controls pass 12 runs in a +row, and the first regression set below gives the same 45 passes and 3 capability skips. The pull request +preset is a Debug preset and was not run in Release. + +Baseline: at `05438d65` the tool does not scan `.rtv` files. A directory with a base request and one variant +request gives `requests=1 compiled=1 refused=0` and nothing under the variant key (run with a format 2 request +published by the stand-in on each of the two adapters). + +Mutation: with the format ignored where the target is typed, `native_rtv_variant_controls` and +`native_rtv_variant_warp` fail. This was run on an earlier state of the branch, on `05438d65`; the mutated line +is the same in `be9a0706`. + +Regression runs at the same commit, same machine: + +```powershell +ctest --preset dev --no-tests=error -R '^(native_rtv_variant_|native_compile_dxil_refusals|native_startup_request_cache|startup_mrt_|native_direct_container|native_sampled_replay|native_global_srv_heap_replay|native_recording|native_graphics|native_dxil_llvm_ident|native_.*_pso_|startup_stream_|startup_compute_dispatch_native)' +ctest --preset pr --no-tests=error +``` + +- The first set: 45 of 48 pass. Capability skips, not passes: `native_comparison_pso_warp`, + `native_global_srv_heap_replay_warp` and `startup_compute_dispatch_native_warp`. +- The pull request preset: 36 of 40 pass. Capability skips, not passes: `spirv_minlod_warp`, + `spirv_minlod_exact_warp`, `spirv_minlod_levels_warp` and `spirv_minlod_fractional_warp`. + +These two sets were not run at `4ff5e36d` without the change, so whether the seven skips predate it was not +measured here. + +## Limits + +- Three formats were drawn: 12, 14 and 2. The other integer formats take the same two types and were compiled + by no fixture here. The readback sets of `gfx2hlsl.py` were verified with that translator's output, not with + this one. +- One pair: no resources, no samplers, no root constants, a pixel stage that writes MRT0 only. A variant whose + pixel stage writes two typed targets was not run. +- The readbacks use containers without an output signature. The signature branch is compiled by the controls + and was not drawn. +- The controls ran the directory with four workers 12 times in a row without a failure. That is the only + evidence for two requests publishing one frontend entry side by side, beyond reading the cache code. +- The variants came from slot 86 containers. A raw slot 57 pair with a `.psin` goes through the same reader + path, and no fixture ran one as a variant. +- A format that is not an integer format is typed `f32` without a check that it is a renderable format, as in + `gfx2hlsl.py`. +- The runtime's `mrtbits` entry value is not used: the native pixel stage keeps float32 bits without it. This + was measured for the four words above on the two adapters only. +- Only the two adapters above were run, in Debug and Release builds on one machine. No start-up run used a + variant compiled this way. diff --git a/docs/experiments/native-salu64-ops.md b/docs/experiments/native-salu64-ops.md new file mode 100644 index 000000000..a48b40ad1 --- /dev/null +++ b/docs/experiments/native-salu64-ops.md @@ -0,0 +1,31 @@ +# 64-bit scalar operations in the direct C++ compute path + +Issue #2957 adds `s_bfm_b64`, `s_cselect_b64` and `s_not_b64`. +`s_bfm_b64` uses the low six bits of each 32-bit source as its width and +offset, writes both words of an aligned SGPR pair, and preserves SCC. +`s_cselect_b64` selects both words using SCC and preserves SCC. +`s_not_b64` complements both words and sets SCC when either result word +is nonzero. Both take aligned SGPR pairs or constants, with sign extension +for inline negatives and zero extension for other integers. They can +write VCC as a pair. EXEC destinations are refused. + +## Verification + +`native_salu64_controls` checks that compiling `s_cselect_b64 exec, -1, 0` +fails. `native_salu64_hardware` checks both result words, SCC, and the +buffer guards across two 32-thread groups. It covers mask widths 0, 1, 31, +32, 33, 63 and 64, including the captured width and offset of 32, with +the raw width 64 wrapping to 0. The select cases cover both SCC values, +an SGPR pair, inline -1 and the literal `0x80000001`. The complement +cases include zero output and output with only the high word nonzero. +Hardware without shader model 6.6 and wave32 support returns skip code 77. + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_salu64_(controls|hardware)$' +``` + +Results: on an NVIDIA GeForce RTX 5080 (Windows 11, DXC from the Windows SDK 10.0.26100) all fifteen cases +matched their 64-bit words and SCC in both workgroups, with the guards intact, and the control refused an EXEC +destination. A 32-bit `s_bfm_b64`, a zero-extended `-1` in `s_cselect_b64` and an `s_not_b64` SCC taken +from the low word only each fail the hardware check. diff --git a/docs/experiments/native-sdwa-f16.md b/docs/experiments/native-sdwa-f16.md new file mode 100644 index 000000000..e04c273a9 --- /dev/null +++ b/docs/experiments/native-sdwa-f16.md @@ -0,0 +1,48 @@ +# SDWA binary16 arithmetic in direct compute + +Issue #2963 adds SDWA to `v_add_f16`, `v_sub_f16`, `v_subrev_f16` and `v_mul_f16`. +Each source must be a VGPR. WORD_0 and DWORD read the low half, and WORD_1 reads the +high half. Source abs clears the binary16 sign bit before neg toggles it. The compiler +widens the halves to binary32, performs the operation, and rounds once to binary16 +using the integer nearest-even path from the [plain forms](f16-alu-direct.md). +The binary16 rounding and denormal mode requirements apply to both forms. + +WORD_0 and WORD_1 destinations accept UNUSED_PAD, which zeroes the other half, +and UNUSED_PRESERVE, which copies it from the old destination. DWORD and byte +destinations, UNUSED_SEXT, byte sources, source sext, scalar and constant sources, +clamp, and output modifiers are refused. SDWA min and max remain refused. + +## Fixture + +The fixture compares the IR and hardware results against the same exact binary16 +model as the plain-form fixture. The hardware run dispatches two wave32 groups, +with one lane per group writing the case words. Every untouched word must keep +the guard value `69696969`. An adapter without wave32 support returns skip code 77. + +| Destination and sources | Add | Sub | Subrev | Mul | +|---|---|---|---|---| +| WORD_0 preserve, WORD_1 and DWORD | a55a4200 | a55abc00 | a55a3c00 | a55a4000 | +| WORD_0 pad, DWORD and WORD_0 | 00004400 | 00004000 | 0000c000 | 00004200 | +| WORD_1 preserve, neg(abs(WORD_0)) and WORD_1 | 3c001357 | c2001357 | 42001357 | c0001357 | + +The add of `3c01` and `1000` rounds its tie to `a55a3c02` with low-half preserve. +The product of `0003` and `3800` rounds to the subnormal word `00000002`. +The product of `7bff` and `4000` overflows to `7c000000` with high-half pad. +The add of `7e01` and `3c00` expects a NaN in the low half and exactly `a55a` +in the preserved high half. The NaN payload and sign may vary. + +Compile-only controls cover DWORD destination, BYTE_1 source, SGPR source, +inline constant source, source sext, UNUSED_SEXT, clamp, omod, min and max. +Swapping WORD_0 and WORD_1 on either source and forcing UNUSED_PRESERVE to pad +are manual lowering mutations that must fail the readback comparison. + +```powershell +cmake --preset dev +cmake --build --preset dev --target native_compute_ir_dump native_store_replay +ctest --preset dev --no-tests=error -R "^native_sdwa_f16_(ir|hardware)$" -V -j 1 +``` + +Results: on an NVIDIA GeForce RTX 5080 (Windows 11, DXC from the Windows SDK 10.0.26100) the IR check matched all +17 results and the 10 refusals, and the GPU check matched 34 results in two workgroups with 2,030 guard words +intact. Reading the other half of a WORD_0/WORD_1 source, and writing the result without its SDWA placement, +each fail both checks, and so does dropping abs or dropping neg. diff --git a/docs/experiments/native-shift64-sources.md b/docs/experiments/native-shift64-sources.md new file mode 100644 index 000000000..758446dc0 --- /dev/null +++ b/docs/experiments/native-shift64-sources.md @@ -0,0 +1,32 @@ +# Logical 64-bit shift sources in the direct C++ compute path + +Issue #2951 covers the shifted value for `v_lshrrev_b64` and `v_lshlrev_b64`. +Inline integers supply their 32-bit value as the low word and all ones as the +high word for negative values. Nonnegative integers and 32-bit literals +supply a zero high word. An even SGPR pair from `s[0:1]` through `s[104:105]` +supplies the low and high words in register order. Both SGPRs must be numeric. +VGPR pairs and inline zero remain accepted. The shift amount uses its low six +bits. + +Inline floats, odd or out-of-range SGPR pairs and special registers are +refused with `direct 64-bit shift operand`. + +## Verification + +`native_shift64_controls` checks that an inline float is refused during +compilation. `native_shift64_hardware` uses source-built programs and checks +both words and the buffer guards across two 32-thread groups against an +independent masked Python integer reference. The fixture shifts inline +`-1`, `-16`, `64` and `1`, literal `0x80000001`, and SGPR pair +`0x01234567_89abcdef` in both directions by 0, 1, 31, 32, 33 and 63. +Hardware without shader model 6.6 and wave32 support returns skip code 77. + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_shift64_(controls|hardware)$' +``` + +Results: on an NVIDIA GeForce RTX 5080 (Windows 11, DXC from the Windows SDK 10.0.26100) the controls refused the +inline float, and every source matched its 64-bit reference for both directions and all six shift amounts, in both +workgroups, with the guards intact. Zero-extending the inline values, sign-extending the literal and swapping the +SGPR pair's words each fail the hardware check. diff --git a/docs/experiments/native-startup-request-cache.md b/docs/experiments/native-startup-request-cache.md new file mode 100644 index 000000000..b946aab35 --- /dev/null +++ b/docs/experiments/native-startup-request-cache.md @@ -0,0 +1,59 @@ +# 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-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-29` or the archived revision 28 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(".vs.cso` / + `.ps.cso`, `.gs.cso` for `gfx1013-container-rect`, and `.cs.cso` for compute), withdraws any + prior `.txt` before rewriting stages or on refusal, records `.psdep` when `.psin` was used, and + atomically publishes `.txt` after all stage `.cso` files are in place. + +## Verification and negative controls + +1. **`controls` mode (`native_startup_request_cache_controls`):** + - Compiles two `.psin`-described VS/PS requests (`(0x8002, 0x8003)` placing `POS_FIXED_PT` in `v4` after an + allocated-only `PERSP_SAMPLE` pair, and `(0x8002, 0x8002)` placing `POS_FIXED_PT` in `v2`) and a `.c67` + compute request in place, checks that `.txt` is written after stage `.cso` files and recognised as + complete by `gfx2hlsl.pending_keys`, and verifies that mutating a stage blob behind an existing `.psin` + withdraws `.txt`. + - Exercises eight fresh-directory refusal controls (graphics key mismatch, compute key mismatch, `.psin` + naming another pipeline, missing `addr`, missing `ena`, contradictory `ena`/`addr`, malformed `.psin`, and + reading an allocated-but-disabled pixel input VGPR), requiring a clear diagnostic on `stderr` and no + `.txt` or stage `.cso` output. +2. **`e2e` mode (`native_startup_request_cache_warp`, `native_startup_request_cache_hardware`):** + - Draws both `.psin` pairs through `offscreen_check --startup-packed-position` (all 91 pixels match, while a + mismatched-mask control fails readback). + - Drives a runtime-published graphics pair and a runtime-published slot-67 `.c67` compute request through + `startup_stream_consumer` -> `compile_dxil --requests` -> `d3d12_xs` (`load_translation` / `draw_translated` + and `load_compute_translation` / `record_translated_dispatch`) with the D3D12 debug layer enabled (`0` + errors), checking all 32 RGBA pixels and all 320 compute output dwords. + +```powershell +cmake --preset release +cmake --build --preset release --target compile_dxil startup_stream_consumer offscreen_check +ctest --preset release --no-tests=error -V -R "^native_startup_request_cache_(controls|warp|hardware)$" +``` + +## Limits + +- Startup runtime manifests are emitted only for stage bindings that the existing `d3d12_xs` manifest loaders + bind directly (for example, pairs without IA `InputLayout` vertex elements and compute shaders using raw table + buffers, 2D textures, 2D/2D-array float image UAVs, static non-comparison samplers, and root constants). +- Direct compute shaders carry `[WaveSize(32)]`; on Wave-4 WARP (`10.0.26100`), `load_compute_translation` + verifies the manifest, loads `.cs.cso`, and creates the desktop root signature before `CreateComputePipelineState` + declines `[WaveSize(32)]`, while full GPU dispatch and 320-word readback run on Wave-32 hardware (`AMD Radeon RX 9070 XT`). diff --git a/docs/experiments/native-vertex-vcc-join.md b/docs/experiments/native-vertex-vcc-join.md new file mode 100644 index 000000000..c23853f96 --- /dev/null +++ b/docs/experiments/native-vertex-vcc-join.md @@ -0,0 +1,46 @@ +# Per-vertex VCC across a vertex-stage join in the direct DXIL frontend (#2906) + +[The fixture](../../tests/native_graphics_vertex_vcc_join_check.py) draws two source-built gfx1013 vertex +stages through the direct DXIL frontend and compares the readback with a per-vertex CPU model. + +## The two programs + +1. A root word that the harness supplies at draw time picks the arm, so the branch is uniform but not known + to the compiler. Each arm runs its own `SV_VertexID` compare into VCC and writes its own constant. After + the join one CNDMASK selects that constant or 0.5 per vertex. Both outcomes are drawn. The emitted IR + joins the two compares in a `phi` that feeds the select, and the test requires that. +2. One compare writes VCC and also splits the vertices between a THEN and an ELSE arm under saved EXEC. + After EXEC is restored a CNDMASK on the same VCC keeps the arm's constant or its negation, so one draw + holds both VCC values and both arm values. The frontend lowers these guest arms to per-vertex selects in + one block, so this program has a guest join and no IR join. + +## Readback and controls + +A desktop pixel stage reads the three vertex values with `GetAttributeAtVertex`, so each of the 8 pixels +reports every vertex without interpolation. The comparison is bit-exact. + +Each control redraws a changed program against the unchanged reference and must differ at all 8 pixels: + +- arm B of the first program loses its compare, so that edge carries the stale mask of an earlier compare. + Arm A still matches with the same change; +- a uniform `v0 == v0` compare overwrites the joined mask, in both arms of the first program and in the + second. + +## Command and result + +```powershell +cmake --build --preset dev --target compile_dxil offscreen_check +ctest --preset dev --no-tests=error -V -R '^native_graphics_vertex_vcc_join_(warp|hardware)$' +``` + +On Windows 11 build 26300, Debug build, both tests passed with the debug layer enabled and no debug errors +or warnings: Microsoft Basic Render Driver (driver 10.0.26100.9818) and NVIDIA GeForce RTX 4090 +(driver 32.0.16.1088). Neither reported a capability skip. + +## Limits + +- Branches that need a whole-wave VCC vote are not drawn. Neither is a compare inside a per-vertex masked + arm, whose VCC on the other lanes depends on the rest of the guest wave. +- An adapter without per-vertex attribute support fails pipeline creation instead of reporting a skip. That + path has not been observed. +- The pixel stage is desktop HLSL. A translated pixel stage linked to this vertex stage is not covered. diff --git a/docs/experiments/pack-b32-f16-direct.md b/docs/experiments/pack-b32-f16-direct.md new file mode 100644 index 000000000..5e36a62e9 --- /dev/null +++ b/docs/experiments/pack-b32-f16-direct.md @@ -0,0 +1,43 @@ +# v_pack_b32_f16 in the direct C++ DXIL path + +Covers the lowering of VOP3 `v_pack_b32_f16` (0x311) in `src/gfx1013_direct_compute.inl` (Fixes #2909) and +what was and was not verified. + +## Semantics + +- For each of the two sources, `op_sel` bit 11 (source 0) or 12 (source 1) picks the low or high half. +- abs clears bit 15 of the half, then neg toggles it, so neg after abs. +- D[15:0] is source 0 and D[31:16] is source 1. +- Only `lshr`/`and`/`xor`/`shl`/`or` on i32 are emitted. Signed zero and NaN payloads keep their exact bits. +- Both sources are read before the destination is written, so the destination may overlap a source. +- VGPR and SGPR sources are supported. + +## Refused forms + +Each is refused with a named diagnostic, with no approximation: clamp, omod, a destination `op_sel` bit (14), +`op_sel` bit 13 (third source), abs/neg on the third source, inline constants, a literal source. + +## Linux IR verification + +`python -B tests/native_pack_b32_f16_check.py ir ` evaluates the emitted IR and compares it +with `ref()` of `tests/startup_gfx2hlsl_pack_b32_f16_check.py`: 261 results match (issue words, control, 64 +`op_sel`/abs/neg forms x 4 value pairs, overlap, SGPR sources, refusals). The swapped-half and neg-before-abs +variants differ from the emitted bits. The dumper was built on Linux from the C++ sources with the Wine d3d12 +headers and a stub `wrl/client.h`. + +## Windows result (review of PR #2917) + +Windows 11 build 26300.9974, AMD Radeon RX 9070 XT, driver 32.0.32029.2010, MSVC 19.44.35221, `release` +preset, Windows SDK 10.0.26100 DXC, D3D12 debug layer not enabled. + +- `native_pack_b32_f16_ir`: passed. +- `compile_dxil ... gfx1013-container-ps` on the issue words: rc 0, and `dxc -dumpbin` reads the `.cso`. +- `native_pack_b32_f16_hardware`: not verified. `native_store_replay --direct` exits `0xC0000005` with no output, + the crash tracked in #2915. + +## GPU readback: no run yet + +`native_pack_b32_f16_check.py gpu` has not produced a result on any machine. Workgroups are 128 words apart so +that the 66 results of one group (64 forms, the SGPR case, the overlap case) never share a word with another +group; `group_offsets` asserts this. There is no WARP variant because `native_store_replay` takes the default +adapter. A hardware result is still needed once #2915 is fixed or on an adapter that does not crash. diff --git a/docs/experiments/startup-compute-native-dispatch.md b/docs/experiments/startup-compute-native-dispatch.md new file mode 100644 index 000000000..bafceee39 --- /dev/null +++ b/docs/experiments/startup-compute-native-dispatch.md @@ -0,0 +1,98 @@ +# In-process compute translation in the stand-in (#2934) + +[The fixture](../../tests/startup_compute_dispatch_native_check.py) dispatches a source-built gfx1013 compute +program through the stand-in's device slot 67 and Dispatch path with `X2W_NATIVE_SHADERS` set, an empty shader +cache and no offline translator, and compares all 320 output words with a CPU reference. + +## Route + +1. Slot 67 creation publishes the request as before. +2. On the first Dispatch of the pipeline, `translate_compute_natively` + (`src/startup_stubs/d3d12_compute_dispatch.inl`) reads the request back with `x2w::read_compute_request`, + which checks the six parts against the key in the file name. It then runs the C++ frontend + (`x2w::translate_compute`, entry 0) and compiles the module with `ShaderDxilCompiler::runtime_worker`. +3. The entry values and views fill the same `ComputeTranslation` a published `.txt` fills. The existing + dispatch path then resolves the table descriptors, sets the resource states and records the Dispatch. + +Accepted: root constants, a raw table buffer loaded per lane and a raw table buffer stored to. These are the +bindings the fixture runs. Refused: every other view kind (a scalar buffer load included), a sampler, more than +32 entry values or inputs or 8 outputs, an adapter without 32-lane waves, and whatever the frontend refuses. The +stand-in logs the first 16 refusals of a process with their reason. A refused key is left to a published +translation. The in-process translation is tried once per key and before a published `.txt`. + +`NativeRecording` and `NativeDispatchStates` are not used. The dispatch path already allocates the descriptors +and tracks the states of these buffers. + +## Program and controls + +The program is case A of [`startup_gfx2hlsl_compute_check.py`](../../tests/startup_gfx2hlsl_compute_check.py): +two root constants, group size 2x3x4, 3x2x2 groups, one input word read and one word stored per thread. Its +`s_load_dwordx8` is replaced by two `s_load_dwordx4`, at table bytes 0 and 32. The C++ frontend reads a table as +32-byte records. It refuses case A as written (`unaligned descriptor table entry`), because that program takes +its second descriptor from table byte 16. The fixture checks the two replaced instructions with the Python +decoder, and the consumer's `dispatch-records32` mode writes the table with the output's descriptor at byte 32. + +1. Native: all 320 words match the case's CPU expectation (288 written, 32 left at the sentinel). The log names + the native translation. Afterwards the cache holds the request files and the compiler's own cache, and no + `.txt`, `.cs.cso` or `.fail`. +2. The same program over the plain table layout has no descriptor at byte 32. Its Dispatch is refused when it is + bound and every word keeps the sentinel, so the record at byte 32 is what the first run bound. +3. Unsupported workload: case A as written. The stand-in logs the frontend's reason, the Dispatch is refused with + `no translation` and every word keeps the sentinel. +4. Fallback: `gfx2hlsl.py --pending` then publishes both requests. With native translation still on, the next + run dispatches case A through the published translation and all 320 words match. +5. Order: the first program runs again with its published translation in the cache. The log still names the + native translation, and all 320 words match. + +Without 32-lane waves, step 1 instead checks that the native translation is refused by that name with every word +untouched. Step 2 is left out, steps 3 and 4 run, step 5 runs the first program through its published +translation, and the check exits 77. + +## Command and result + +```powershell +cmake --build --preset dev --target d3d12_xs_shim startup_stream_consumer compile_dxil native_wave_request_gpu offscreen_check +ctest --preset dev --no-tests=error -V -R '^startup_compute_dispatch_(native_)?(warp|hardware)$' +ctest --preset dev --no-tests=error -V -R '^native_wave_request_hardware$' +``` + +Commit `a58e08f9` on `cpp-migration` at `e3670100`, Windows 11 build 26300.9974, Debug build, D3D12 debug layer +enabled. + +| Test | Adapter, driver | Result | +|---|---|---| +| `startup_compute_dispatch_native_hardware` | NVIDIA GeForce RTX 4090, 32.0.16.1088 | PASS. All 320 words match after the in-process translation from an empty cache and again with a published translation in the cache. The plain table layout and case A are refused with every word untouched. No debug-layer error message. | +| `startup_compute_dispatch_hardware` | NVIDIA GeForce RTX 4090, 32.0.16.1088 | PASS (the published-translation route, unchanged). | +| `native_wave_request_hardware` | the same machine (the test prints no adapter line) | PASS. | +| `startup_compute_dispatch_warp` | Microsoft Basic Render Driver, 10.0.26100.9818 | PASS. | + +Capability skip, not a pass: `startup_compute_dispatch_native_warp` exits 77 on the Microsoft Basic Render +Driver 10.0.26100.9818, which reports no 32-lane waves. Before it exits, the check confirms that the native +translation is refused by that name with every word untouched, that case A is refused and then runs through a +published translation, and that the first program matches all 320 words through its published translation. + +The other WARP dispatch tests were run as a regression check and pass (9 tests): + +```powershell +ctest --preset dev --no-tests=error -V -R '^(startup_compute_dispatch(_.*)?|startup_slot67_indirect_dispatch|startup_compute_translate_e2e)_warp$' +``` + +## Limits + +- Compute only. Graphics pipelines are not translated in-process. +- A scalar buffer load, a texture, a sampler and the typed, half and indexed views are refused. +- One descriptor shape was dispatched: stride 4 and 320 records, for the input and for the output. +- An indirect Dispatch of a natively translated program was not run. +- A captured request starts with a 36-byte prefix of `v_nop` words before `s_inst_prefetch`. The route passes + entry 0. With `compile_dxil`, a synthetic prefix translates to the same bindings from entry 0 and from entry + 36. The fixture does not dispatch a prefixed program. +- Only the two adapters above were run, in a Debug build. `run.ps1` takes its stand-ins from the release build + directory by default, and no start-up run used the switch. The launcher switch was checked with stubs. +- An adapter whose lane range excludes 32 refuses every program. +- The result is not published, so each process translates a key again. The compiler's DXIL cache under + `\native` is reused. +- The GPU-check package ships `offscreen_check.exe`, which compiles the stand-in source without + `X2W_NATIVE_SHADERS`. That variant builds and `offscreen_warp` passes. The package script (`tools/package-gpu-check.ps1`) was run at + `89a75318` (the same code): the extracted package passes its WARP run on the Microsoft Basic Render Driver + 10.0.26100.9818 with 11 tests passing and 68 of 68 recorded shader cases. `bvh_wave64_warp` reports a capability + skip there (no 64-lane waves). diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 886a6dc4f..c8e239f24 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -929,6 +929,30 @@ print the same results and write the same failures as one, an unexpected transla `startup_run_ps1` checks that `-Translate` starts the watcher on the cache and stops it together with a child process. +### Translating compute programs in the stand-in + +With `X2W_NATIVE_SHADERS=` (`run.ps1 -Render -NativeShaders `), +the stand-in translates a device slot 67 request itself, with the C++ compiler in +`src/gfx1013_compute_native.cpp`, on the first Dispatch of its pipeline. No watcher is needed for those +pipelines, and the cache can start empty: the request files the stand-in wrote are read back, checked +against their key, translated and compiled to DXIL in the process. The compiler's own cache goes to +`\native`. Nothing is published as `.txt`. + +The existing dispatch path records the result, and a program is accepted only with the bindings a +fixture has run through it: root constants, raw table buffers loaded per lane (`buffer_load_dword`) +and raw table buffers stored to, with their descriptors in 32-byte table records. Anything else (a +scalar buffer load, a texture, a sampler, a typed or indexed view, an instruction the compiler does +not lower) is refused. The first 16 refusals of a process are logged as +`compute pipeline not translated natively: `. A refused key is left to the +published translations, so `-Translate` can run beside it for those pipelines. A direct module declares +wave size 32, so an adapter without 32-lane waves refuses every program by that name. The in-process +translation is tried once per key and before a published `.txt`. It covers compute only; graphics +pipelines still need a published translation. + +Check with `ctest --preset dev -R '^startup_compute_dispatch_native_(warp|hardware)$' -V` +([`tests/startup_compute_dispatch_native_check.py`](../tests/startup_compute_dispatch_native_check.py); +[route, controls and results](experiments/startup-compute-native-dispatch.md)). + ### Compute pipeline requests Device slot 67 creates a pipeline from a console compute program. The stand-in reads 12 64-bit words of the @@ -1500,6 +1524,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_D3D12_PERMISSIVE=1` | wraps the device: recording command lists, console present, view tracking; on a runtime without shader model 6.6 (in-box Windows 10), root signatures with the heap-indexing flags (`0xC00`) are serialized again without them, and the copy kept for shader translation gets that call's bits back when `CreateRootSignature` receives the returned blob's own buffer (a copy of the bytes keeps the desktop flags; `d3d12_xs_shim_heap_indexing`). The retry runs only on runtimes that refuse the flags (before shader model 6.6); where the runtime accepts them, `d3d12_xs_shim_heap_indexing` reports a capability skip (77) | | `X2W_D3D12_RENDER=1` | draws through translated pipelines from `X2W_SHADER_CACHE` and forwards [single-record indirect Dispatch](experiments.md#gpu-written-indirect-dispatch-arguments), [DrawIndexed](experiments.md#gpu-written-indirect-indexed-draw-arguments), [Draw](experiments.md#gpu-written-indirect-draw-arguments), and [DispatchMesh](experiments.md#gpu-written-indirect-mesh-dispatch-arguments) for supported desktop pipelines and tracked placed buffers | | `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}`, when needed RTV variants `req_.rtv`, and for device slot 67 compute pipelines `req_.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. | +| `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) | diff --git a/src/direct_compute_cache.cpp b/src/direct_compute_cache.cpp new file mode 100644 index 000000000..e633a50b2 --- /dev/null +++ b/src/direct_compute_cache.cpp @@ -0,0 +1,912 @@ +#include "direct_compute_cache.h" +#include "guest_shader_container.h" +#include "gfx1013_isa.h" +#include "native_graphics_bindings.h" +#include "shader_compute_request.h" +#include "native_shader_revision.h" +#include "shader_dxil_compiler.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace x2w { +namespace { +namespace fs = std::filesystem; +using Bytes = std::string; +void word(Bytes &data, uint32_t value) { data.append(reinterpret_cast(&value), sizeof(value)); } +bool embedded_graphics_id(std::string_view raw) { + // Alternative compiler variants can share the embedded ID encoded in two + // literal-bearing V_NOPs. A common executable prologue is not an ID. + if (raw.size() < 24) return false; + for (unsigned pc : {0u,12u}) { + if (static_cast(raw[pc+2]) != 0x80 || static_cast(raw[pc+3]) != 0xd5) return false; + const auto op = gfx1013::instruction(raw,pc); + if (op.form != gfx1013::Form::vop3 || op.name != "v_nop" || op.size != 12) return false; + } + return true; +} +GuestShaderStage match_graphics_stage(std::string_view raw, const Bytes &blob, bool &exact) { + auto stages = read_guest_shader_container(blob); + int best = 0; + size_t selected = 0; + bool tie = false; + for (size_t i = 0; i < stages.size(); ++i) { + const auto &stage = stages[i]; + if (stage.stage != GpuStage::vs && stage.stage != GpuStage::ps) continue; + // A pixel container can carry materialized export instructions in a + // patch table. The running PS already contains the selected export. + int rank = 0; + if (raw == stage.code) rank = stage.exports.empty() ? 3 : 2; + if (!stage.exports.empty() && raw == stage.full_precision_code()) rank = 3; + if (!rank && raw.substr(0,24) == std::string_view(stage.code).substr(0,24) && embedded_graphics_id(raw)) + rank = 1; + if (rank > best) { best = rank; selected = i; tie = false; } + else if (rank && rank == best) tie = true; + } + if (!best) throw UnsupportedComputeShader("raw stage and interface identity disagree"); + if (tie) throw UnsupportedComputeShader("ambiguous native stage in graphics interface"); + exact = best == 3; + return std::move(stages[selected]); +} +struct Reader { + std::string_view remaining; + std::string_view take(size_t size) { + if (size > remaining.size()) + throw std::runtime_error("short frontend cache"); + auto bytes = remaining.substr(0, size); + remaining.remove_prefix(size); + return bytes; + } + uint32_t word() { + uint32_t n; + std::memcpy(&n, take(sizeof n).data(), sizeof n); + return n; + } + uint32_t count(uint32_t max) { + auto n = word(); + if (n > max) + throw std::runtime_error("invalid frontend cache count"); + return n; + } +}; + +Bytes encode(const NativeComputeShader &program) { + Bytes out; + word(out, program.instruction_count); + for (unsigned n : program.group) + word(out, n); + word(out, static_cast(program.bindings.size())); + for (const auto &b : program.bindings) { + word(out, static_cast(b.kind)); + for (unsigned n : {b.root_parameter, b.byte_offset, b.shader_register, b.required_bytes, b.array_count, + b.array_position, b.image_dimension, unsigned(b.scalar_table)}) + word(out, n); + } + word(out, static_cast(program.constants.size())); + for (const auto &c : program.constants) + for (unsigned n : {c.root_parameter, c.first_sgpr, c.count}) + word(out, n); + word(out, static_cast(program.samplers.size())); + for (const auto &s : program.samplers) { + for (auto n : s.words) + word(out, n); + word(out, s.explicit_lod); + word(out, s.comparison); + } + for (const auto *signature : {&program.inputs, &program.outputs}) { + word(out, static_cast(signature->size())); + for (const auto &row : *signature) { + word(out, static_cast(row.name.size())); + out += row.name; + for (auto field : + {row.index, row.row, row.first, row.width, row.component, row.used, row.kind, row.interpolation}) + word(out, field); + } + } + word(out, program.vertex_fetch); + for (auto mask : program.pixel_writes) + word(out, mask); + out += program.dxil_ir; + return out; +} +NativeComputeShader decode(std::string_view bytes) { + Reader in{bytes}; + NativeComputeShader shader{}; + shader.instruction_count = in.count(1 << 18); + shader.group = {in.count(1024), in.count(1024), in.count(64)}; + unsigned n = in.count(1000000); + shader.bindings.reserve(n); + for (unsigned j = 0; j < n; ++j) { + auto kind = static_cast(in.count(static_cast(ComputeViewKind::heap_buffer_srv))); + ComputeViewBinding b{kind, in.word(), in.word(), in.word(), in.word(), in.word(), in.word(), in.count(7)}; + b.scalar_table = static_cast(in.count(unsigned(ComputeViewBinding::ScalarTable::srv))); + if (!b.array_count || b.array_position >= b.array_count || + (b.root_parameter >= 16 && b.root_parameter != compute_resource_heap)) + throw std::runtime_error("invalid cached binding"); + shader.bindings.push_back(b); + } + n = in.count(32); + for (unsigned j = 0; j < n; ++j) { + ComputeConstants c{in.count(15), in.count(105), in.count(32)}; + if (!c.count || c.count > 106 - c.first_sgpr) + throw std::runtime_error("invalid cached constants"); + shader.constants.push_back(c); + } + n = in.count(2048); + for (unsigned j = 0; j < n; ++j) { + ComputeSampler sampler{}; + for (auto &w : sampler.words) + w = in.word(); + sampler.explicit_lod = in.count(1) != 0; + sampler.comparison = in.count(1) != 0; + shader.samplers.push_back(sampler); + } + for (auto *signature : {&shader.inputs, &shader.outputs}) { + unsigned count = in.count(128); + for (unsigned j = 0; j < count; ++j) { + GraphicsLinkage row{}; + row.name = in.take(in.count(4096)); + row.index = in.word(); + row.row = in.word(); + row.first = in.count(3); + row.width = in.count(4); + row.component = in.word(); + row.used = in.count(15); + row.kind = in.count(31); + row.interpolation = in.count(7); + const bool unpacked = row.row == UINT_MAX && (signature == &shader.outputs || + (row.name == "SV_Barycentrics" && row.kind == 28 && row.component == 9 && + row.width == 3 && !row.first && row.index < 2 && row.interpolation >= 2)); + if (row.row >= 32 && !unpacked) + throw std::runtime_error("invalid cached signature register"); + if (row.name.empty() || !row.width || row.first + row.width > 4 || row.used >= (1u << row.width)) + throw std::runtime_error("invalid cached signature"); + signature->push_back(std::move(row)); + } + } + shader.vertex_fetch = in.count(1) != 0; + for (auto &mask : shader.pixel_writes) + mask = in.count(15); + if (in.remaining.empty()) + throw std::runtime_error("missing cached DXIL IR"); + shader.dxil_ir = in.remaining; + return shader; +} +bool lookup(const fs::path &path, const Bytes &key, Bytes &payload) { + HANDLE handle = CreateFileW(path.c_str(), GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (handle == INVALID_HANDLE_VALUE) + return false; + LARGE_INTEGER size{}; + bool ok = false; + if (GetFileSizeEx(handle, &size) && size.QuadPart > 128 && size.QuadPart <= 256ll * 1024 * 1024) { + Bytes id(64, 0), checksum(64, 0); + payload.resize(static_cast(size.QuadPart) - 128); + DWORD got_id = 0, got_sum = 0, got_body = 0; + ok = ReadFile(handle, id.data(), 64, &got_id, nullptr) && got_id == 64 && id == key && + ReadFile(handle, checksum.data(), 64, &got_sum, nullptr) && got_sum == 64 && + ReadFile(handle, payload.data(), static_cast(payload.size()), &got_body, nullptr) && + got_body == payload.size() && shader_digest(payload) == checksum; + } + CloseHandle(handle); + return ok; +} +void publish(const fs::path &path, const Bytes &key, const Bytes &payload) { + fs::create_directories(path.parent_path()); + static std::atomic serial{}; + auto temp = path; + temp += L"." + std::to_wstring(GetCurrentProcessId()) + L"." + std::to_wstring(serial++) + L".tmp"; + try { + std::ofstream file(temp, std::ios::binary); + file.exceptions(std::ios::badbit | std::ios::failbit); + file << key << shader_digest(payload); + file.write(payload.data(), payload.size()); + file.close(); + if (!MoveFileExW(temp.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING)) { + Bytes winner; + if (!lookup(path, key, winner) || winner != payload) + throw std::runtime_error("could not publish direct frontend cache"); + std::error_code ignored; + fs::remove(temp, ignored); + } + } catch (...) { + std::error_code ignored; + fs::remove(temp, ignored); + throw; + } +} +using InterfaceMap = std::map; +const Bytes &catalog_version() { + static const Bytes version = shader_digest("x2w graphics interface catalog 1"); + return version; +} +bool digest_text(std::string_view s) { + return s.size() == 64 && s.find_first_not_of("0123456789abcdef") == s.npos; +} +std::shared_ptr load_interfaces(const fs::path &dir) { + auto marker = dir / "catalog"; + if (!fs::exists(marker)) return {}; + Bytes generation; + if (!lookup(marker, catalog_version(), generation) || !digest_text(generation)) + throw std::runtime_error("invalid graphics interface catalog marker"); + static std::mutex lock; + static Bytes resident_id; + static std::shared_ptr resident; + std::lock_guard guard(lock); + if (resident && generation == resident_id) return resident; + Bytes index; + if (!lookup(dir / (generation + ".index"), generation, index) || shader_digest(index) != generation) + throw std::runtime_error("invalid graphics interface catalog index"); + auto entries = std::make_shared(); + Reader reader{index}; + while (!reader.remaining.empty()) { + auto key = reader.take(65), value = reader.take(64); + if ((key.front() != 'F' && key.front() != 'I') || !digest_text(key.substr(1)) || + (!digest_text(value) && value != Bytes(64,'-')) || !entries->emplace(key,value).second) + throw std::runtime_error("invalid graphics interface catalog entry"); + } + resident_id = generation; + resident = entries; + return resident; +} +Bytes indexed_interface(const fs::path &dir, const InterfaceMap &entries, std::string_view raw, const Bytes &hash) { + auto it = entries.find("F" + hash); + if (it == entries.end() && embedded_graphics_id(raw)) + it = entries.find("I" + shader_digest(raw.substr(0,24))); + if (it == entries.end()) return {}; + if (it->second.front() == '-') throw UnsupportedComputeShader("ambiguous reviewed graphics interfaces"); + Bytes container; + if (!lookup(dir / (it->second + ".stage"), it->second, container) || shader_digest(container) != it->second) + throw std::runtime_error("invalid indexed graphics interface container"); + return container; +} +} // namespace + +size_t index_graphics_interfaces(const fs::path &source, const fs::path &cache) { + const auto dir = cache / "interfaces" / "library"; + InterfaceMap index; + size_t count = 0; + for (const auto &entry : fs::recursive_directory_iterator(source)) { + if (!entry.is_regular_file() || entry.path().extension() != L".cdxil") continue; + auto blob = read_shader_container_bytes(entry.path()); + auto stages = read_guest_shader_container(blob); + const auto id = shader_digest(blob); + auto add = [&](const Bytes &key) { + auto [it, fresh] = index.emplace(key,id); + if (!fresh && it->second != id) it->second.assign(64,'-'); + }; + bool graphics = false; + for (const auto &stage : stages) { + if (stage.stage != GpuStage::vs && stage.stage != GpuStage::ps) continue; + graphics = true; + add("F" + shader_digest(stage.code)); + if (!stage.exports.empty()) add("F" + shader_digest(stage.full_precision_code())); + if (embedded_graphics_id(stage.code)) add("I" + shader_digest(std::string_view(stage.code).substr(0,24))); + } + if (!graphics) continue; + publish(dir / (id + ".stage"), id, blob); + ++count; + } + if (!count) throw std::runtime_error("no graphics .cdxil containers in interface directory"); + Bytes encoded; + for (const auto &[key,id] : index) { encoded += key; encoded += id; } + const auto generation = shader_digest(encoded); + publish(dir / (generation + ".index"), generation, encoded); + publish(dir / "catalog", catalog_version(), generation); + return count; +} +NativeComputeShader prepare_direct_compute(const std::filesystem::path &input, unsigned entry, bool container, + const std::filesystem::path &cache, bool &cache_hit, + HeapViewContract heap_view) { + if (!container && heap_view != HeapViewContract::none) + throw std::runtime_error("a heap view contract needs a container request"); + ComputeRequest request{}; + ComputeContainer packed; + Bytes identity = X2W_NATIVE_SHADER_REVISION; + identity += container ? "/container/cs_6_6" : "/slot67/cs_6_6"; + word(identity, container ? 0 : entry); + if (heap_view != HeapViewContract::none) + identity += heap_view == HeapViewContract::raw_buffer ? "/heap-view/raw_buffer" : "/heap-view/other"; + if (container) { + packed = read_compute_container(input); + identity += shader_digest(packed.bytes) + shader_digest(packed.root); + } else { + request = read_compute_request(input); + for (auto *part : {&request.code, &request.data, &request.root, &request.description, &request.sa, &request.sb}) + identity += shader_digest(*part); + } + const auto key = shader_digest(identity); + const auto path = cache / (key + ".csir"); + NativeComputeShader program{}; + Bytes payload; + cache_hit = lookup(path, key, payload); + if (cache_hit) { + try { + program = decode(payload); + } catch (const std::runtime_error &) { + cache_hit = false; + } + } + if (!cache_hit) { + program = container ? translate_compute_container(std::move(packed), heap_view) : translate_compute(request, entry, true); + publish(path, key, encode(program)); + } + return program; +} + +unsigned dxil_io_component(unsigned format) { + switch (format) { + case DXGI_FORMAT_R32_FLOAT: + case DXGI_FORMAT_R32G32_FLOAT: + case DXGI_FORMAT_R32G32B32_FLOAT: + case DXGI_FORMAT_R32G32B32A32_FLOAT: + case DXGI_FORMAT_R16_FLOAT: + case DXGI_FORMAT_R16G16_FLOAT: + case DXGI_FORMAT_R16G16B16A16_FLOAT: + case DXGI_FORMAT_R16_UNORM: + case DXGI_FORMAT_R16G16_UNORM: + case DXGI_FORMAT_R16G16B16A16_UNORM: + case DXGI_FORMAT_R16_SNORM: + case DXGI_FORMAT_R16G16_SNORM: + case DXGI_FORMAT_R16G16B16A16_SNORM: + case DXGI_FORMAT_R8_UNORM: + case DXGI_FORMAT_R8G8_UNORM: + case DXGI_FORMAT_R8G8B8A8_UNORM: + case DXGI_FORMAT_R8_SNORM: + case DXGI_FORMAT_R8G8_SNORM: + case DXGI_FORMAT_R8G8B8A8_SNORM: + case DXGI_FORMAT_R10G10B10A2_UNORM: + return 9; + case DXGI_FORMAT_R8_UINT: + case DXGI_FORMAT_R8G8_UINT: + case DXGI_FORMAT_R8G8B8A8_UINT: + case DXGI_FORMAT_R16_UINT: + case DXGI_FORMAT_R16G16_UINT: + case DXGI_FORMAT_R16G16B16A16_UINT: + case DXGI_FORMAT_R32_UINT: + case DXGI_FORMAT_R32G32_UINT: + case DXGI_FORMAT_R32G32B32_UINT: + case DXGI_FORMAT_R32G32B32A32_UINT: + case DXGI_FORMAT_R10G10B10A2_UINT: + return 5; + case DXGI_FORMAT_R8_SINT: + case DXGI_FORMAT_R8G8_SINT: + case DXGI_FORMAT_R8G8B8A8_SINT: + case DXGI_FORMAT_R16_SINT: + case DXGI_FORMAT_R16G16_SINT: + case DXGI_FORMAT_R16G16B16A16_SINT: + case DXGI_FORMAT_R32_SINT: + case DXGI_FORMAT_R32G32_SINT: + case DXGI_FORMAT_R32G32B32_SINT: + case DXGI_FORMAT_R32G32B32A32_SINT: + return 4; + } + return 0; +} + +// The capture writer serializes the guest's D3D12_INPUT_ELEMENT_DESC array as ia1. +// Keep APPEND_ALIGNED_ELEMENT intact so D3D12 uses the preceding element of its slot. +static std::vector vertex_layout(std::string_view text, const NativeComputeShader &vs) { + std::vector elements; + std::set> names; + auto upper = [](std::string name) { + for (char &c : name) + if (c >= 'a' && c <= 'z') + c -= 'a' - 'A'; + return name; + }; + if (!text.empty()) { + std::istringstream in{std::string(text)}; + std::string token; + auto number = [&]() { + unsigned value = 0; + if (!(in >> token)) + throw UnsupportedComputeShader("truncated input layout"); + const auto end = token.data() + token.size(); + auto parsed = std::from_chars(token.data(), end, value); + if (parsed.ec != std::errc{} || parsed.ptr != end) + throw UnsupportedComputeShader("invalid input layout number"); + return value; + }; + if (!(in >> token) || token != "ia1") + throw UnsupportedComputeShader("invalid input layout version"); + const unsigned count = number(); + if (!count || count > 32) + throw UnsupportedComputeShader("invalid input element count"); + for (unsigned i = 0; i < count; ++i) { + NativeVertexElement e{}; + if (!(in >> e.semantic) || e.semantic.empty() || e.semantic.size() > 63 || + e.semantic.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") != + std::string::npos || + (e.semantic.front() >= '0' && e.semantic.front() <= '9')) + throw UnsupportedComputeShader("invalid input semantic"); + e.semantic = upper(e.semantic); + e.index = number(); + e.format = number(); + e.slot = number(); + e.offset = number(); + e.classification = number(); + e.step_rate = number(); + if (!dxil_io_component(e.format)) + throw UnsupportedComputeShader("unsupported vertex input format"); + if (e.slot >= 8 || e.classification > 1 || (!e.classification && e.step_rate) || + (e.offset != UINT_MAX && e.offset >= D3D12_REQ_MULTI_ELEMENT_STRUCTURE_SIZE_IN_BYTES)) + throw UnsupportedComputeShader("unsupported vertex input slot, offset or classification"); + if (!names.emplace(e.semantic, e.index).second) + throw UnsupportedComputeShader("duplicate input semantic"); + for (const auto &prior : elements) + if (e.slot == prior.slot && + (e.classification != prior.classification || e.step_rate != prior.step_rate)) + throw UnsupportedComputeShader("inconsistent input slot classification"); + elements.push_back(std::move(e)); + } + if (in >> token) + throw UnsupportedComputeShader("trailing input layout elements"); + } + for (const auto &row : vs.inputs) { + const auto name = upper(row.name); + if (name.rfind("SV_", 0) == 0) + continue; + auto it = std::find_if(elements.begin(), elements.end(), + [&](const auto &e) { return e.semantic == name && e.index == row.index; }); + if (it == elements.end()) + throw UnsupportedComputeShader("missing vertex input element " + name); + if (dxil_io_component(it->format) != row.component) + throw UnsupportedComputeShader("vertex format disagrees with shader input " + name); + it->used = true; + } + return elements; +} + +DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view b, const fs::path &cache, + bool &cache_hit, std::string_view root, std::string_view input_layout, + std::string_view pixel_entry, bool write_cache, + const std::vector &rtv_formats) { + // An RTV variant types each color target by its format, as tools/startup/gfx2hlsl.py mrt_kind does: u32 or i32 + // for the integer formats, f32 for every other format. + std::array targets{}; + if (rtv_formats.size() > targets.size()) throw UnsupportedComputeShader("invalid RTV variant values"); + for (size_t i = 0; i < rtv_formats.size(); ++i) { + const unsigned component = dxil_io_component(rtv_formats[i]); + targets[i] = static_cast(component == 5 || component == 4 ? component : 9); + } + // The two three-channel 32-bit integer formats have no verified readback there. As there, one is refused by + // name only when the pixel stage exports to its target; the stage's cached form does not depend on which + // format of a type was asked for, so this is checked on a cache hit too. + const auto verified = [&](DirectGraphicsPair pair) { + for (size_t i = 0; i < rtv_formats.size(); ++i) + if (pair.pixel.pixel_writes[i] && + (rtv_formats[i] == DXGI_FORMAT_R32G32B32_UINT || rtv_formats[i] == DXGI_FORMAT_R32G32B32_SINT)) + throw UnsupportedComputeShader(std::string("unverified ") + (targets[i] == 5 ? "UINT" : "SINT") + + " RTV format " + std::to_string(rtv_formats[i])); + return pair; + }; + // A fixed PSO can expose a shorter serialized desktop root than the + // guest's hardware descriptor table. An explicitly supplied companion + // describes the guest ABI. Never use its executable code in the pair. + std::array companions; + const std::array raw{a, b}; + const std::array digests{shader_digest(a), shader_digest(b)}; + Bytes identity = Bytes(X2W_NATIVE_SHADER_REVISION) + "/linked/vs_ps_6_6/"; + if (!cache.empty() && a.substr(0,4) != "DXBC" && b.substr(0,4) != "DXBC") { + for (size_t i = 0; i < raw.size(); ++i) { + auto file = cache / "interfaces" / (digests[i] + ".cdxil"); + if (std::filesystem::exists(file)) companions[i] = read_shader_container_bytes(file); + } + if (companions[0].empty() || companions[1].empty()) { + const bool pinned = !companions[0].empty() || !companions[1].empty(); + const auto library = cache / "interfaces" / "library"; + if (auto index = load_interfaces(library)) { + for (size_t i = 0; i < raw.size(); ++i) + if (companions[i].empty()) companions[i] = indexed_interface(library,*index,raw[i],digests[i]); + // An incomplete library must still allow a self-describing raw pair. + if (!pinned && (companions[0].empty() || companions[1].empty())) companions = {}; + } + } + } + for (size_t i = 0; i < raw.size(); ++i) { + identity += digests[i]; + identity += shader_digest(companions[i]); + } + const bool reflected = !companions[0].empty(); + if (reflected != !companions[1].empty()) throw UnsupportedComputeShader("incomplete raw graphics interface pair"); + if (reflected && root.empty()) throw UnsupportedComputeShader("missing captured root for reflected graphics"); + // The base pair keeps its key. A variant adds its target types, so formats of one type share an entry. + const Bytes typed = rtv_formats.empty() ? Bytes{} + : shader_digest(std::string_view(reinterpret_cast(targets.data()), targets.size())); + const auto key = shader_digest(identity + shader_digest(root) + shader_digest(input_layout) + shader_digest(pixel_entry) + typed); + const auto path = cache / (key + ".pairir"); + Bytes payload; + cache_hit = write_cache && !cache.empty() && lookup(path, key, payload); + auto effective_layout = [&](const NativeComputeShader &vs) { + if (!input_layout.empty() || (pixel_entry.empty() && !reflected) || !vs.vertex_fetch) return std::string(input_layout); + unsigned count = 0; + std::ostringstream elements; + for (const auto &r : vs.inputs) { + if (r.name != "X2W_RAW_VERTEX") continue; + unsigned format = 0; + if (r.component == 5 && r.width == 2) format = DXGI_FORMAT_R32G32_UINT; + if (r.component == 5 && r.width == 3) format = DXGI_FORMAT_R32G32B32_UINT; + if (r.component == 9 && r.width == 4) format = DXGI_FORMAT_R8G8B8A8_UNORM; + if (!format) throw UnsupportedComputeShader("unsupported fixed vertex format"); + elements << " X2W_RAW_VERTEX " << r.index << ' ' << format << " 0 " << r.index << " 0 0"; + ++count; + } + return count ? "ia1 " + std::to_string(count) + elements.str() : std::string{}; + }; + if (cache_hit) { + try { + Reader in{payload}; + auto vertex = decode(in.take(in.word())); + auto elements = vertex_layout(effective_layout(vertex), vertex); + return verified({std::move(vertex), decode(in.remaining), std::move(elements), targets}); + } catch (const UnsupportedComputeShader &) { + throw; + } catch (const std::runtime_error &) { + cache_hit = false; + } + } + D3D12_VERSIONED_ROOT_SIGNATURE_DESC empty{}; + const D3D12_VERSIONED_ROOT_SIGNATURE_DESC *desc = ∅ + Microsoft::WRL::ComPtr sig; + if (!root.empty()) { + if (FAILED(D3D12CreateVersionedRootSignatureDeserializer(root.data(), root.size(), IID_PPV_ARGS(&sig))) || + FAILED(sig->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &desc))) + throw UnsupportedComputeShader("invalid captured graphics root signature"); + } + const auto &layout = desc->Desc_1_1; + std::map interfaces; + std::optional first_stage; + bool exact_pair = reflected; + Bytes entry; + if (reflected) { + for (size_t i = 0; i < companions.size(); ++i) { + bool exact = false; + auto matched = match_graphics_stage(raw[i],companions[i],exact); + exact_pair &= exact; + auto stage = matched.stage; + if (i == 0) first_stage = stage; + if (!interfaces.emplace(stage, std::move(matched)).second) + throw UnsupportedComputeShader("duplicate reflected graphics stage"); + } + if (!interfaces.count(GpuStage::vs) || !interfaces.count(GpuStage::ps)) + throw UnsupportedComputeShader("missing vertex or pixel interface"); + if (exact_pair && !pixel_entry.empty()) { + auto &ps = interfaces.at(GpuStage::ps); + uint32_t enable_mask = 0, address_mask = 0; + if (pixel_entry.size() != 13 || pixel_entry.substr(0, 5) != "psin1") + throw UnsupportedComputeShader("invalid raw pixel entry record"); + std::memcpy(&enable_mask, pixel_entry.data() + 5, 4); + std::memcpy(&address_mask, pixel_entry.data() + 9, 4); + if (enable_mask > 0xffff || address_mask > 0xffff || (enable_mask & ~address_mask)) + throw UnsupportedComputeShader("contradictory pixel input enable/address masks"); + exact_pair = ps.pixel_input_address == address_mask; + if (exact_pair) + ps.pixel_input_enable = enable_mask; + } + if (pixel_entry.empty() && !exact_pair) { + const auto &ps = interfaces.at(GpuStage::ps); + if (ps.pixel_input_address != 2 || ps.attributes.empty() || ps.attributes.size() > 7) + throw UnsupportedComputeShader("raw graphics requires its captured pixel entry"); + entry = "psin1"; + word(entry, ps.pixel_input_address); + word(entry, ps.pixel_input_address); + pixel_entry = entry; + } + } + DirectGraphicsPair pair; + if (exact_pair) { + for (size_t i = 0; i < raw.size(); ++i) { + auto type = i == 0 ? *first_stage : *first_stage == GpuStage::vs ? GpuStage::ps : GpuStage::vs; + auto &stage = interfaces.at(type); + stage.code.assign(raw[i]); + stage.exports.clear(); + } + interfaces.at(GpuStage::ps).target_components = targets; + pair = translate_reflected_graphics(interfaces.at(GpuStage::vs),interfaces.at(GpuStage::ps),layout); + } else pair = translate_graphics_pair(a, b, layout, pixel_entry, first_stage, targets); + pair.target_components = targets; + if (!entry.empty()) { + const auto &attrs = interfaces.at(GpuStage::ps).attributes; + std::vector channels(attrs.size()); + for (const auto &r : pair.pixel.inputs) { + if (r.kind == 28 && r.interpolation == 2) continue; + if (r.name != "TEXCOORD" || r.index / 4 >= channels.size() || r.interpolation != 2 || + r.width != 1 || r.first != r.index % 4) + throw UnsupportedComputeShader("raw and reflected interpolation inputs disagree"); + channels[r.index / 4] |= 1u << r.first; + } + for (const auto &attr : attrs) { + if (attr.usage != 6 || attr.location >= channels.size() || attr.flags != 2 || + attr.mask != channels[attr.location] || !attr.mask) + throw UnsupportedComputeShader("raw and reflected interpolation channels disagree"); + channels[attr.location] = 0; + } + } + pair.input_layout = vertex_layout(effective_layout(pair.vertex), pair.vertex); + if (!root.empty()) { + for (auto *stage : {&pair.vertex, &pair.pixel}) { + const bool vertex = stage == &pair.vertex; + const auto visibility = vertex ? D3D12_SHADER_VISIBILITY_VERTEX : D3D12_SHADER_VISIBILITY_PIXEL; + auto parameter = [&](unsigned index) -> const D3D12_ROOT_PARAMETER1 & { + if (index >= layout.NumParameters || + layout.Flags & (vertex ? D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS + : D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS)) + throw UnsupportedComputeShader("graphics root parameter inaccessible"); + const auto &p = layout.pParameters[index]; + if (p.ShaderVisibility != D3D12_SHADER_VISIBILITY_ALL && p.ShaderVisibility != visibility) + throw UnsupportedComputeShader("graphics root parameter stage visibility mismatch"); + return p; + }; + for (const auto &c : stage->constants) { + const auto &p = parameter(c.root_parameter); + if (p.ParameterType != D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS || + c.count > p.Constants.Num32BitValues) + throw UnsupportedComputeShader("graphics root constant span mismatch"); + } + for (auto &binding : stage->bindings) { + const auto &p = parameter(binding.root_parameter); + if (binding.kind == ComputeViewKind::root_buffer_srv) { + if (p.ParameterType != D3D12_ROOT_PARAMETER_TYPE_CBV && p.ParameterType != D3D12_ROOT_PARAMETER_TYPE_SRV) + throw UnsupportedComputeShader("graphics scalar load requires a root CBV or SRV"); + continue; + } + if (p.ParameterType != D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE || binding.byte_offset % 32) + throw UnsupportedComputeShader("graphics binding is outside a descriptor table"); + const auto slot = binding.byte_offset / 32; + const auto kind = + compute_uav(binding.kind) ? D3D12_DESCRIPTOR_RANGE_TYPE_UAV : D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + uint64_t next = 0; + bool found = false; + for (unsigned i = 0; i < p.DescriptorTable.NumDescriptorRanges; ++i) { + const auto &range = p.DescriptorTable.pDescriptorRanges[i]; + const uint64_t first = + range.OffsetInDescriptorsFromTableStart == D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND + ? next + : range.OffsetInDescriptorsFromTableStart; + next = first + range.NumDescriptors; + // Scalar buffer loads also consume CBV table records. The + // resolver supplies a raw SRV over the recorded CBV window. + if (first <= slot && slot < next && (kind == range.RangeType || + (binding.kind == ComputeViewKind::buffer_srv && range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_CBV))) + found = true; + } + if (reflected && binding.array_count == 1) { + const auto &iface = interfaces.at(vertex ? GpuStage::vs : GpuStage::ps); + unsigned sgpr = 8; + for (unsigned k = 0; k < binding.root_parameter; ++k) { + const auto &prev = layout.pParameters[k]; + sgpr += prev.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE ? 1 : + prev.ParameterType == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS ? prev.Constants.Num32BitValues : 2; + } + const bool used = apply_reflected_table_use(binding, iface, + exact_pair ? std::optional{} : std::optional{sgpr}); + const bool needs_record = !found || (!exact_pair && (binding.kind == ComputeViewKind::buffer_srv || + binding.kind == ComputeViewKind::texture_srv || + binding.kind == ComputeViewKind::d16_sample_srv)); + if (!used && needs_record && binding.kind != ComputeViewKind::heap_stride_srv) + throw UnsupportedComputeShader("raw load disagrees with reflected table record"); + found |= used; + } + apply_scalar_table_layout(binding, p.DescriptorTable); + if (!found) + throw UnsupportedComputeShader(std::string("graphics descriptor range does not cover resource: ") + + (vertex ? "VS" : "PS") + " root " + std::to_string(binding.root_parameter) + + " byte offset " + std::to_string(binding.byte_offset) + " slot " + std::to_string(slot)); + } + } + } + if (write_cache && !cache.empty()) { + auto vertex = encode(pair.vertex); + payload.clear(); + word(payload, static_cast(vertex.size())); + payload += vertex; + payload += encode(pair.pixel); + publish(path, key, payload); + } + return verified(std::move(pair)); +} + +std::optional format_compute_runtime_manifest(const NativeComputeShader &program) { + if (!program.group[0] || !program.group[1] || !program.group[2]) + return std::nullopt; + unsigned ud_count = 0; + for (const auto &block : program.constants) { + if (block.root_parameter >= 16 || block.count > 8) + return std::nullopt; + ud_count += block.count; + } + if (ud_count > 32) + return std::nullopt; + + auto sorted = program.bindings; + std::sort(sorted.begin(), sorted.end(), [](const auto &a, const auto &b) { + const bool ua = compute_uav(a.kind), ub = compute_uav(b.kind); + if (ua != ub) + return !ua; + return a.shader_register < b.shader_register; + }); + + unsigned srv_count = 0, uav_count = 0; + std::ostringstream srv_lines, uav_lines, sampler_lines; + for (const auto &b : sorted) { + if (b.root_parameter >= 16) + return std::nullopt; + if (!compute_uav(b.kind)) { + if (b.shader_register != srv_count++) + return std::nullopt; + if (b.kind == ComputeViewKind::buffer_srv || b.kind == ComputeViewKind::raw_vector_srv || + b.kind == ComputeViewKind::byte_window_srv) { + srv_lines << "srv " << b.shader_register << " buf table " << b.root_parameter << ' ' << b.byte_offset + << '\n'; + } else if (b.kind == ComputeViewKind::texture_srv && b.image_dimension == 1 && b.array_count == 1) { + srv_lines << "srv " << b.shader_register << " tex2d table " << b.root_parameter << ' ' << b.byte_offset + << '\n'; + } else { + return std::nullopt; + } + } else { + if (b.shader_register != uav_count++) + return std::nullopt; + if (b.kind == ComputeViewKind::raw_buffer_uav) { + uav_lines << "uav " << b.shader_register << " table " << b.root_parameter << ' ' << b.byte_offset + << '\n'; + } else if ((b.kind == ComputeViewKind::texture_uav || b.kind == ComputeViewKind::half4_texture_uav) && + (b.image_dimension == 1 || b.image_dimension == 5) && b.array_count == 1) { + uav_lines << "uav " << b.shader_register << (b.image_dimension == 5 ? " tex2da" : " tex2d") + << " float table " << b.root_parameter << ' ' << b.byte_offset << " channels 4\n"; + } else { + return std::nullopt; + } + } + } + if (srv_count > 32 || uav_count > 8) + return std::nullopt; + + for (size_t i = 0; i < program.samplers.size(); ++i) { + const auto &s = program.samplers[i]; + if (s.comparison) + return std::nullopt; + char line[64]; + std::snprintf(line, sizeof(line), "%s %zu %08x %08x %08x %08x\n", s.explicit_lod ? "smpl" : "smp", i, + s.words[0], s.words[1], s.words[2], s.words[3]); + sampler_lines << line; + } + + std::ostringstream out; + out << "x2w-manifest 2\nstage cs\ngroup " << program.group[0] << ' ' << program.group[1] << ' ' << program.group[2] + << "\nud " << ud_count << '\n'; + unsigned ud_index = 0; + for (const auto &block : program.constants) + for (unsigned j = 0; j < block.count; ++j) + out << "udsrc " << ud_index++ << " rootconst " << block.root_parameter << ' ' << j << '\n'; + out << srv_lines.str() << uav_lines.str() << sampler_lines.str(); + return out.str(); +} + +std::optional format_graphics_runtime_manifest(const DirectGraphicsPair &pair, std::string_view rtv_request) { + if (pair.vertex.vertex_fetch || !pair.input_layout.empty()) + return std::nullopt; + for (const auto &in : pair.vertex.inputs) + if (in.name != "SV_VertexID" && in.name != "SV_InstanceID") + return std::nullopt; + // An integer target is published only for the RTV variant whose format asked for that type. + for (const auto &out : pair.pixel.outputs) + if (out.name == "SV_Target" && out.component != 9 && + (out.index >= pair.target_components.size() || out.component != pair.target_components[out.index])) + return std::nullopt; + + std::optional maybe_bindings; + GraphicsConstantLayout constants; + try { + maybe_bindings.emplace(pair); + constants = pair.constant_layout(); + } catch (const std::exception &) { + return std::nullopt; + } + const auto &bindings = *maybe_bindings; + const unsigned uav_count = static_cast(bindings.views.size()) - bindings.srv_count; + if (bindings.srv_count > 32 || uav_count > 8) + return std::nullopt; + for (unsigned count : constants.counts) + if (count > 8) + return std::nullopt; + const unsigned total_constants = constants.offset(static_cast(constants.counts.size())); + if (total_constants > 32) + return std::nullopt; + + std::ostringstream srv_lines, uav_lines, sampler_lines; + for (unsigned i = 0; i < bindings.srv_count; ++i) { + const auto &b = bindings.views[i]; + if (b.root_parameter >= 16) + return std::nullopt; + if (b.kind == ComputeViewKind::buffer_srv || b.kind == ComputeViewKind::raw_vector_srv || + b.kind == ComputeViewKind::byte_window_srv) { + srv_lines << "srv " << i << " buf table " << b.root_parameter << ' ' << b.byte_offset << '\n'; + } else if (b.kind == ComputeViewKind::root_buffer_srv && b.byte_offset == 0 && b.array_count == 1) { + srv_lines << "srv " << i << " buf root " << b.root_parameter << '\n'; + } else if ((b.kind == ComputeViewKind::texture_srv || b.kind == ComputeViewKind::comparison_texture_srv) && + b.array_count == 1) { + const char *tex = b.image_dimension == 0 ? "tex1d" + : b.image_dimension == 1 ? "tex2d" + : b.image_dimension == 2 ? "tex3d" + : b.image_dimension == 5 ? "tex2da" + : nullptr; + if (!tex) + return std::nullopt; + srv_lines << "srv " << i << ' ' << tex << " table " << b.root_parameter << ' ' << b.byte_offset << '\n'; + } else { + return std::nullopt; + } + } + for (unsigned j = 0; j < uav_count; ++j) { + const auto &b = bindings.views[bindings.srv_count + j]; + if (b.root_parameter >= 16 || b.array_count != 1) + return std::nullopt; + if (b.kind != ComputeViewKind::texture_uav && b.kind != ComputeViewKind::half4_texture_uav) + return std::nullopt; + if (b.image_dimension != 1 && b.image_dimension != 5) + return std::nullopt; + uav_lines << "uav " << j << (b.image_dimension == 5 ? " tex2da table " : " tex2d table ") << b.root_parameter + << ' ' << b.byte_offset << '\n'; + } + for (size_t i = 0; i < bindings.samplers.statics.size(); ++i) { + const auto &w = bindings.samplers.statics[i]; + const bool cmp = i < bindings.samplers.comparison.size() && bindings.samplers.comparison[i]; + const bool lod = !cmp && i < bindings.samplers.lod_limits.size() && bindings.samplers.lod_limits[i]; + char line[64]; + std::snprintf(line, sizeof(line), "%s %zu %08x %08x %08x %08x\n", cmp ? "smpc" : lod ? "smpl" : "smp", i, w[0], + w[1], w[2], w[3]); + sampler_lines << line; + } + + unsigned params = 0; + for (const auto &out : pair.vertex.outputs) + if (out.name == "TEXCOORD") + params = (std::max)(params, out.index / 4 + 1); + + std::ostringstream out; + out << "x2w-manifest " << (uav_count ? 2 : 1) << "\nud " << (total_constants ? total_constants : 1u) << '\n'; + if (!total_constants) { + out << "udsrc 0 rect\n"; + } else { + unsigned ud_index = 0; + for (unsigned r = 0; r < constants.counts.size(); ++r) + for (unsigned j = 0; j < constants.counts[r]; ++j) + out << "udsrc " << ud_index++ << " rootconst " << r << ' ' << j << '\n'; + } + out << srv_lines.str() << uav_lines.str() << sampler_lines.str() << "params " << params << "\ntargets"; + bool any_target = false; + for (unsigned t = 0; t < pair.pixel.pixel_writes.size(); ++t) { + if (!pair.pixel.pixel_writes[t]) + continue; + out << ' ' << t; + any_target = true; + } + if (!any_target) + out << ' '; + out << '\n'; + for (unsigned t = 0; t < pair.pixel.pixel_writes.size(); ++t) { + const unsigned mask = pair.pixel.pixel_writes[t]; + if (mask > 0 && mask < 0xf) { + char line[16]; + std::snprintf(line, sizeof(line), "wmask %u 0x%x\n", t, mask); + out << line; + } + } + if (!rtv_request.empty()) + out << rtv_request << '\n'; + return out.str(); +} +} // namespace x2w diff --git a/src/direct_compute_cache.h b/src/direct_compute_cache.h new file mode 100644 index 000000000..f52d82336 --- /dev/null +++ b/src/direct_compute_cache.h @@ -0,0 +1,22 @@ +#pragma once + +#include "gfx1013_compute_native.h" + +// The result includes the emitted DXIL module and its exact desktop/guest binding layout. +namespace x2w { +size_t index_graphics_interfaces(const std::filesystem::path &source, const std::filesystem::path &cache); +// Signature component (f32/u32/i32) for supported typed IA and RTV formats. +unsigned dxil_io_component(unsigned dxgi_format); +NativeComputeShader prepare_direct_compute(const std::filesystem::path &input, unsigned entry, bool container, + const std::filesystem::path &cache, bool &cache_hit, + HeapViewContract heap_view = HeapViewContract::none); +DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view b, + const std::filesystem::path &cache, bool &cache_hit, + std::string_view root = {}, std::string_view input_layout = {}, + std::string_view pixel_entry = {}, bool write_cache = true, + const std::vector &rtv_formats = {}); +std::optional format_compute_runtime_manifest(const NativeComputeShader &program); +// rtv_request: the "rtv1 ..." text of an RTV variant, written as the manifest's last line for the runtime to match. +std::optional format_graphics_runtime_manifest(const DirectGraphicsPair &pair, + std::string_view rtv_request = {}); +} diff --git a/src/dxil_module.h b/src/dxil_module.h new file mode 100644 index 000000000..c0f79867f --- /dev/null +++ b/src/dxil_module.h @@ -0,0 +1,301 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace x2w { +// LLVM's DXIL dialect. Resource declarations, handle annotations and entry metadata +// are produced together so the bytecode and the runtime binding contract agree. +class DxilModule { + public: + using Text = std::string; + struct Resource { + unsigned cls, reg, kind, component, width, bytes; + unsigned count = 1; + bool comparison = false; + }; + std::ostringstream body, setup, globals; + bool uses_wave = false; + bool heap_used = false; + unsigned features = 0; + struct Signature { + Text name; + unsigned semantic_index, kind, component, row, first, width, interpolation, used = 0; + }; + // The final bit marks rasterizer inputs without a packed signature row. + // They vary between lanes but occupy no slot in the ViewID matrix. + using InputMask = std::bitset<129>; + bool track_inputs = false; + bool loop_dependencies = false; + std::map dependencies; + std::map> consumers; + std::map> output_values; + std::vector inputs, outputs; + std::map output_dependencies; + Text value(const Text &instruction) { + auto name = "%t" + std::to_string(sequence++); + if (track_inputs) { + InputMask sources; + for (size_t at = 0; (at = instruction.find('%', at)) != Text::npos;) { + size_t end = at + 1; + while (end < instruction.size() && + (std::isalnum(static_cast(instruction[end])) || instruction[end] == '_')) + ++end; + auto operand = instruction.substr(at, end - at); + if (loop_dependencies && + (operand.rfind("%t", 0) == 0 || operand.rfind("%p", 0) == 0 || operand.rfind("%indexed", 0) == 0)) + consumers[operand].push_back(name); + auto found = dependencies.find(operand); + if (found != dependencies.end()) + sources |= found->second; + at = end; + } + if (sources.any()) + dependencies.emplace(name, sources); + } + body << " " << name << " = " << instruction << "\n"; + return name; + } + void finish_loop_dependencies() { + std::deque pending; + for (const auto &[name, mask] : dependencies) + if (mask.any()) + pending.push_back(name); + while (!pending.empty()) { + auto source = std::move(pending.front()); + pending.pop_front(); + auto it = consumers.find(source); + if (it == consumers.end()) + continue; + const auto mask = dependencies.at(source); + for (const auto &user : it->second) { + auto &dest = dependencies[user]; + if ((mask & ~dest).none()) + continue; + dest |= mask; + pending.push_back(user); + } + } + for (const auto &[channel, values] : output_values) + for (const auto &value : values) + output_dependencies[channel] |= dependencies[value]; + } + Text binary(const Text &op, const Text &a, const Text &b) { return value(op + " i32 " + a + ", " + b); } + Text invoke(const Text &type, const Text &name, unsigned opcode, const std::vector> &args, + const Text &attr) { + Text decl = "declare " + type + " @dx.op." + name + "(i32", + call = "call " + type + " @dx.op." + name + "(i32 " + std::to_string(opcode); + for (auto &[t, v] : args) { + decl += ", " + t; + call += ", " + t + " " + v; + } + decl += ") " + attr; + call += ")"; + auto [it, ok] = declarations.emplace(name, decl); + if (!ok && it->second != decl) + throw std::logic_error("inconsistent DXIL declaration"); + if (type != "void") + return value(call); + body << " " << call << "\n"; + return {}; + } + Text handle(Resource r, const Text &offset = {}) { + const Text reg = std::to_string(r.reg), cls = std::to_string(r.cls); + const auto found = std::find_if(resources.begin(), resources.end(), [&](const Resource &other) { + return other.cls == r.cls && other.reg == r.reg; + }); + Text h = "%h" + cls + "_" + reg; + if (found != resources.end()) { + if (found->kind != r.kind || found->width != r.width || found->component != r.component || + found->bytes != r.bytes || found->count != r.count || found->comparison != r.comparison) + throw std::logic_error("incompatible DXIL binding declarations"); + } else + resources.push_back(r); + if (offset.empty() && !static_handles.insert(h).second) + return h; + Text index = reg; + auto &out = offset.empty() ? setup : body; + if (!offset.empty()) { + index = r.reg ? binary("add", reg, offset) : offset; + h = "%indexed" + std::to_string(sequence++); + if (track_inputs) { + if (auto it = dependencies.find(index); it != dependencies.end()) + dependencies[h] = it->second; + if (loop_dependencies) + consumers[index].push_back(h); + } + } + const unsigned props = r.cls == 2 ? r.bytes : r.component + r.width * 256; + out << " " << h << "b = call %dx.types.Handle @dx.op.createHandleFromBinding(i32 217, %dx.types.ResBind { i32 " + << reg << ", i32 " << r.reg + r.count - 1 << ", i32 0, i8 " << cls << " }, i32 " << index << ", i1 " + << (offset.empty() ? "false" : "true") << ")\n" + << " " << h << " = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle " << h + << "b, %dx.types.ResourceProperties { i32 " << (r.kind + (r.cls == 1 ? 4096 : 0) + (r.comparison ? 32768 : 0)) << ", i32 " << props + << " })\n"; + return h; + } + // A handle taken from the descriptor heap at a run-time index (SM 6.6 ResourceDescriptorHeap[index]), annotated with + // the view class the shader reads: `kind` is the DXIL resource kind (11 raw buffer, 2 Texture2D) and `props` the + // second ResourceProperties word. No resource record is declared: the binding is the whole heap. + Text heap_handle(const Text &index, unsigned kind, unsigned props, bool uav = false) { + heap_used = true; + const Text h = "%heap" + std::to_string(sequence++); + body << " " << h << "b = call %dx.types.Handle @dx.op.createHandleFromHeap(i32 218, i32 " << index + << ", i1 false, i1 true)\n" + << " " << h << " = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle " << h + << "b, %dx.types.ResourceProperties { i32 " << (kind + (uav ? 4096 : 0)) << ", i32 " << props << " })\n"; + return h; + } + Text finish_compute(unsigned x, unsigned y, unsigned z, const Text &stage = "cs") { + std::ostringstream out; + out << "target datalayout = " + "\"e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64\"\n" + "target triple = \"dxil-ms-dx\"\n" + "%dx.types.Handle = type { i8* }\n%dx.types.ResBind = type { i32, i32, i32, i8 }\n" + "%dx.types.ResourceProperties = type { i32, i32 }\n%dx.types.ResRet.i32 = type " + "{i32,i32,i32,i32,i32}\n" + "%dx.types.ResRet.f32 = type {float,float,float,float,i32}\n%dx.types.CBufRet.i32 = type " + "{i32,i32,i32,i32}\n" + "%dx.types.fouri32 = type {i32,i32,i32,i32}\n" + "%dx.types.Dimensions = type {i32,i32,i32,i32}\n"; + std::vector metadata; + auto node = [&](const Text &content) { + auto id = "!" + std::to_string(metadata.size()); + metadata.push_back(content); + return id; + }; + auto list = [&](const std::vector &ids) { + Text content; + for (auto &id : ids) { + if (!content.empty()) + content += ", "; + content += id; + } + return ids.empty() ? Text("null") : node(content); + }; + std::vector groups[4]; + std::sort(resources.begin(), resources.end(), + [](const auto &a, const auto &b) { return std::pair{a.cls, a.reg} < std::pair{b.cls, b.reg}; }); + for (auto &r : resources) { + const Text type = "%res" + std::to_string(r.cls) + "_" + std::to_string(r.reg); + Text scalar = r.component == 9 ? "float" : "i32"; + Text member = r.cls == 2 ? "[" + std::to_string(r.bytes / 16) + " x <4 x i32>]" + : r.width > 1 ? "<" + std::to_string(r.width) + " x " + scalar + ">" + : scalar; + out << type << " = type { " << member << " }\n"; + const Text symbol = r.count == 1 ? type : "[" + std::to_string(r.count) + " x " + type + "]"; + Text md = "i32 " + std::to_string(groups[r.cls].size()) + ", " + symbol + "* undef, !\"\", i32 0, i32 " + + std::to_string(r.reg) + ", i32 " + std::to_string(r.count) + ", i32 " + + std::to_string(r.cls == 2 ? r.bytes + : r.cls == 3 ? unsigned(r.comparison) + : r.kind); + if (r.cls == 0) + md += ", i32 0"; + if (r.cls == 1) + md += ", i1 false, i1 false, i1 false"; + md += ", " + (r.component ? node("i32 0, i32 " + std::to_string(r.component)) : Text("null")); + groups[r.cls].push_back(node(md)); + } + Text res = "null"; + if (!resources.empty()) + res = node(list(groups[0]) + ", " + list(groups[1]) + ", " + list(groups[2]) + ", " + list(groups[3])); + // AMD's DXIL compiler (amdxc64.dll) dereferences Module::getNamedMetadata("llvm.ident") without a null check. + const auto ident = node("!\"x2w\""), version = node("i32 1, i32 6"), + model = node("!\"" + stage + "\", i32 6, i32 6"); + const unsigned flags = features | (uses_wave ? 524288 : 0); + Text properties = "null", signature = "null", view_state; + if (stage == "cs") { + const auto size = + node("i32 " + std::to_string(x) + ", i32 " + std::to_string(y) + ", i32 " + std::to_string(z)); + const auto wave = node("i32 32"); + properties = node((flags ? "i32 0, i64 " + std::to_string(flags) + ", " : "") + "i32 4, " + size + + ", i32 11, " + wave); + } else { + if (flags) + properties = node("i32 0, i64 " + std::to_string(flags)); + if (stage == "gs") + properties = node("i32 1, " + node("i32 3, i32 6, i32 1, i32 5, i32 1")); + auto signature_list = [&](const std::vector &rows, unsigned &scalars) { + std::vector ids; + for (const auto &r : rows) { + if (r.name.empty() || + r.name.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") != + Text::npos || + (r.row >= 32 && r.row != UINT_MAX) || !r.width || r.first + r.width > 4) + throw std::runtime_error("invalid graphics signature"); + if (r.row != UINT_MAX) + scalars = (std::max)(scalars, r.row * 4 + r.first + r.width); + auto index = node("i32 " + std::to_string(r.semantic_index)); + auto used = r.used ? node("i32 3, i32 " + std::to_string(r.used)) : Text("null"); + ids.push_back(node("i32 " + std::to_string(ids.size()) + ", !\"" + r.name + "\", i8 " + + std::to_string(r.component) + ", i8 " + std::to_string(r.kind) + ", " + index + + ", i8 " + std::to_string(r.interpolation) + ", i32 1, i8 " + + std::to_string(r.width) + ", i32 " + + (r.row == UINT_MAX ? "-1" : std::to_string(r.row)) + ", i8 " + + (r.row == UINT_MAX ? "-1" : std::to_string(r.first)) + ", " + used)); + } + return list(ids); + }; + unsigned in_count = 0, out_count = 0; + const auto in_sig = signature_list(inputs, in_count), out_sig = signature_list(outputs, out_count); + signature = node(in_sig + ", " + out_sig + ", null"); + std::vector matrix{in_count, out_count}; + unsigned stride = (out_count + 31) / 32; + matrix.resize(2 + in_count * stride); + for (const auto &[output, mask] : output_dependencies) + for (unsigned i = 0; i < in_count; ++i) + if (mask.test(i)) + matrix.at(2 + i * stride + output / 32) |= 1u << (output % 32); + if (stage == "gs") + matrix.resize(matrix.size() + 3); // no outputs on streams 1 to 3 + Text values; + for (auto word : matrix) { + if (!values.empty()) + values += ", "; + values += "i32 " + std::to_string(word); + } + auto id = "!" + std::to_string(metadata.size()); + metadata.push_back("[" + std::to_string(matrix.size()) + " x i32] [" + values + "]"); + view_state = "!dx.viewIdState = !{" + id + "}\n"; + } + const auto entry = node("void ()* @main, !\"main\", " + signature + ", " + res + ", " + properties); + out << view_state; + out << globals.str() << "define void @main() {\nentry:\n" << setup.str() << body.str() << "}\n"; + for (auto &[name, decl] : declarations) + out << decl << "\n"; + if (heap_used) { + out << "declare %dx.types.Handle @dx.op.createHandleFromHeap(i32,i32,i1,i1) nounwind readnone\n"; + if (resources.empty()) + out << "declare %dx.types.Handle " + "@dx.op.annotateHandle(i32,%dx.types.Handle,%dx.types.ResourceProperties) nounwind readnone\n"; + } + if (!resources.empty()) + out << "declare %dx.types.Handle @dx.op.createHandleFromBinding(i32,%dx.types.ResBind,i32,i1) nounwind " + "readnone\n" + "declare %dx.types.Handle " + "@dx.op.annotateHandle(i32,%dx.types.Handle,%dx.types.ResourceProperties) nounwind readnone\n"; + out << "!llvm.ident = !{" << ident << "}\n!dx.version = !{" << version << "}\n!dx.valver = !{" << version + << "}\n!dx.shaderModel = !{" << model << "}\n"; + if (res != "null") + out << "!dx.resources = !{" << res << "}\n"; + out << "!dx.entryPoints = !{" << entry << "}\n"; + for (size_t i = 0; i < metadata.size(); ++i) + out << "!" << i << " = !{" << metadata[i] << "}\n"; + return out.str(); + } + + private: + unsigned sequence = 0; + std::vector resources; + std::set static_handles; + std::map declarations; +}; +} // namespace x2w diff --git a/src/gfx1013_compute_alu.inl b/src/gfx1013_compute_alu.inl new file mode 100644 index 000000000..5cc4a835b --- /dev/null +++ b/src/gfx1013_compute_alu.inl @@ -0,0 +1,53 @@ +// One native lowering rule per supported register ALU operation. +static const std::map alu_rules = { + {"v_xor_b32",{2,AluType::Bits,"{0} ^ {1}"}}, + {"v_add_f32",{2,AluType::Float,"{0} + {1}"}}, + {"v_add_lshl_u32",{3,AluType::Bits,"({0} + {1}) << ({2} & 31)"}}, + {"v_add_nc_u32",{2,AluType::Bits,"{0} + {1}"}}, + {"v_and_b32",{2,AluType::Bits,"{0} & {1}"}}, + {"v_and_or_b32",{3,AluType::Bits,"({0} & {1}) | {2}"}}, + {"v_ashrrev_i32",{2,AluType::Bits,"uint(int({1}) >> ({0} & 31))"}}, + {"v_bfe_u32",{3,AluType::Bits,"({0} >> ({1} & 31)) & ((1u << ({2} & 31)) - 1)"}}, + {"v_bfi_b32",{3,AluType::Bits,"({0} & {1}) | (~{0} & {2})"}}, + {"v_cvt_f32_i32",{1,AluType::ToFloat,"float(int({0}))"}}, + {"v_cvt_f32_u32",{1,AluType::ToFloat,"float({0})"}}, + {"v_cvt_f32_ubyte0",{1,AluType::ToFloat,"float({0} & 255)"}}, + {"v_cvt_i32_f32",{1,AluType::Bits,"uint(int(asfloat({0})))"}}, + {"v_exp_f32",{1,AluType::Float,"exp2({0})"}}, + {"v_rndne_f32",{1,AluType::Float,"round({0})"}}, + {"v_rsq_f32",{1,AluType::Float,"rsqrt({0})"}}, + {"v_cvt_u32_f32",{1,AluType::Bits,"(!(asfloat({0})>0.0f)?0u:(asfloat({0})>=4294967296.0f?0xffffffffu:uint(asfloat({0}))))"}}, + {"v_mul_hi_u32",{2,AluType::Bits,"uint((uint64_t({0})*uint64_t({1}))>>32)"}}, + {"v_min_u32",{2,AluType::Bits,"min({0},{1})"}}, + {"v_max_u32",{2,AluType::Bits,"max({0},{1})"}}, + {"v_floor_f32",{1,AluType::Float,"floor({0})"}}, + {"v_fma_f32",{3,AluType::Float,"mad({0},{1},{2})"}}, + {"v_fmaak_f32",{3,AluType::Float,"mad({0},{1},{2})"}}, + {"v_fmac_f32",{3,AluType::Float,"mad({0},{1},{2})"}}, + {"v_fmamk_f32",{3,AluType::Float,"mad({0},{1},{2})"}}, + {"v_log_f32",{1,AluType::Float,"log2({0})"}}, + {"v_lshl_add_u32",{3,AluType::Bits,"({0} << ({1} & 31)) + {2}"}}, + {"v_lshl_or_b32",{3,AluType::Bits,"({0} << ({1} & 31)) | {2}"}}, + {"v_lshlrev_b32",{2,AluType::Bits,"{1} << ({0} & 31)"}}, + {"v_lshrrev_b32",{2,AluType::Bits,"{1} >> ({0} & 31)"}}, + {"v_max3_f32",{3,AluType::Float,"max({0}, max({1}, {2}))"}}, + {"v_max_f32",{2,AluType::Float,"max({0}, {1})"}}, + {"v_mbcnt_hi_u32_b32",{2,AluType::Bits,"{1}"}}, + {"v_mbcnt_lo_u32_b32",{2,AluType::Bits,"({1}+countbits({0}&(laneBit-1u)))"}}, + {"v_med3_f32",{3,AluType::Float,"med3({0}, {1}, {2})"}}, + {"v_med3_i32",{3,AluType::Bits,"uint(max(min(int({0}), int({1})), min(max(int({0}), int({1})), int({2}))))"}}, + {"v_min3_f32",{3,AluType::Float,"min({0}, min({1}, {2}))"}}, + {"v_min_f32",{2,AluType::Float,"min({0}, {1})"}}, + {"v_mov_b32",{1,AluType::Bits,"{0}"}}, + {"v_mul_f32",{2,AluType::Float,"{0} * {1}"}}, + {"v_mul_hi_i32",{2,AluType::Bits,"uint((int64_t(asint({0}))*int64_t(asint({1})))>>32)"}}, + {"v_mul_lo_u32",{2,AluType::Bits,"{0} * {1}"}}, + {"v_mul_u32_u24",{2,AluType::Bits,"({0} & 0xffffffu) * ({1} & 0xffffffu)"}}, + {"v_or_b32",{2,AluType::Bits,"{0} | {1}"}}, + {"v_rcp_f32",{1,AluType::Float,"1.0 / {0}"}}, + {"v_sin_f32",{1,AluType::Float,"sin({0} * 6.283185307)"}}, + {"v_sqrt_f32",{1,AluType::Float,"sqrt({0})"}}, + {"v_sub_f32",{2,AluType::Float,"{0} - {1}"}}, + {"v_sub_nc_u32",{2,AluType::Bits,"{0} - {1}"}}, + {"v_subrev_f32",{2,AluType::Float,"{1} - {0}"}}, +}; diff --git a/src/gfx1013_compute_clear.cpp b/src/gfx1013_compute_clear.cpp new file mode 100644 index 000000000..3783079fa --- /dev/null +++ b/src/gfx1013_compute_clear.cpp @@ -0,0 +1,118 @@ +#include "gfx1013_compute_clear.h" +#include "shader_compute_request.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; +namespace { +using Bytes = std::string; +template T read(const Bytes& data,size_t offset) { + if(offset>data.size() || sizeof(T)>data.size()-offset) throw std::runtime_error("truncated compute request"); + T value; + std::memcpy(&value,data.data()+offset,sizeof(value)); + return value; +} +enum class Kind { unknown, zero, table, descriptor, tg_size, wave_base, low_count, bin }; +struct Value { + Kind kind{}; + unsigned parameter{},offset{}; +}; +} + +x2w::ComputeClear x2w::replay_group_clear(const fs::path& marker,unsigned entry_offset) { + const auto request=read_compute_request(marker); + const auto& code=request.code; + const auto& root=request.root; + const auto& sa=request.sa; + if(entry_offset%4) throw std::runtime_error("unaligned entry offset"); + const unsigned xy=read(sa,12),x=xy&65535,y=xy>>16,z=read(sa,16)&65535; + if(!x || !y || !z || uint64_t(x)*y*z!=256 || read(sa,24)!=((6u<<1)|(1u<<10))) + throw std::runtime_error("unsupported group-clear entry layout"); + Microsoft::WRL::ComPtr signature; + if(FAILED(D3D12CreateVersionedRootSignatureDeserializer(root.data(),root.size(),IID_PPV_ARGS(&signature)))) + throw std::runtime_error("invalid compute root signature"); + const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* layout=nullptr; + if(FAILED(signature->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1,&layout)) || + layout->Desc_1_1.NumParameters!=2) throw std::runtime_error("expected two descriptor tables"); + std::array scalar{}; + std::array vector{}; + // A descriptor occupies four SGPRs. Updating any component makes the old base unusable. + auto write_scalar=[&](unsigned reg,Value value) { + auto& base=scalar[reg & ~3u]; + if(base.kind==Kind::descriptor) base={}; + scalar[reg]=value; + }; + for(unsigned i=0;i<2;++i) { + if(layout->Desc_1_1.pParameters[i].ParameterType!=D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) + throw std::runtime_error("compute parameter is not a descriptor table"); + scalar[4+i]={Kind::table,i}; + } + scalar[6]={Kind::tg_size}; + unsigned pc=entry_offset; + auto word=[&](){ auto v=read(code,pc);pc+=4;return v; }; + ComputeClear result; + std::vector stores; + for(;;) { + unsigned at=pc; + uint32_t op=word(); + auto require=[&](bool ok){if(!ok) throw std::runtime_error("unsupported group-clear operand or instruction at byte "+std::to_string(at));}; + if(op==0xbf810000) break; + if((op>>16)==0xbfa0 || (op>>16)==0xbfa1 || op==0xbf8cc07f) continue; // prefetch, clause, wait for scalar loads + if((op&0xff80ff00)==0xbe800300) { + unsigned source=op&255; + require(((op>>16)&127)<102 && (source==128 || source<102)); + require(source==128 || (scalar[source].kind!=Kind::descriptor && scalar[source].kind!=Kind::unknown)); + write_scalar((op>>16)&127,source==128?Value{Kind::zero}:scalar[source]); + } else if((op&~0x1fffu)==0xf4080000) { // s_load_dwordx4 + unsigned base=(op&63)*2,dst=(op>>6)&127; + auto imm=word(); + require((imm&0xfff00000)==0xfa000000 && dst+3<102 && !(dst%4) && scalar[base].kind==Kind::table && scalar[base+1].kind==Kind::zero); + auto table=scalar[base]; + std::fill_n(scalar.begin()+dst,4,Value{}); + scalar[dst]={Kind::descriptor,table.parameter,imm&0xfffff}; + } else if((op&0xff80ff00)==0x8700ff00) { // s_and_b32 with literal wave-base mask + require(((op>>16)&127)<102 && (op&255)<102 && scalar[op&255].kind==Kind::tg_size && word()==0xfc0); + write_scalar((op>>16)&127,{Kind::wave_base}); + } else if((op&0xffffff00)==0xd7000000) { + unsigned dst=op&255; + require(dst<255 && word()==0x10080); // v_lshrrev_b64 with zero shift and zero source + vector[dst]=vector[dst+1]={Kind::zero}; + } else if((op>>8)==0xd76500 || (op>>8)==0xd76600) { + auto operands=word(); + require((operands&0xfffc01ff)==193); + unsigned source=(operands>>9)&511; + bool low=(op>>8)==0xd76500; + require(low ? source<128 && scalar[source].kind==Kind::wave_base : + source>=256 && vector[source-256].kind==Kind::low_count); + vector[op&255]={low?Kind::low_count:Kind::bin}; + } else if(op==0xe2102000) { // buffer_store_format_d16_x, idxen only, offset zero + auto args=word(); + require((args&0xffe00000)==0x80000000); + auto resource=scalar[((args>>16)&31)*4]; + require(vector[args&255].kind==Kind::bin && vector[(args>>8)&255].kind==Kind::zero && + resource.kind==Kind::descriptor && !(resource.offset%32)); + stores.push_back(resource); + } else require(false); + } + if(stores.empty()) throw std::runtime_error("compute program has no clears"); + std::sort(stores.begin(),stores.end(),[](Value a,Value b){return std::tie(a.parameter,a.offset)(result.bindings.size()); + result.bindings.push_back({value.parameter,value.offset}); + auto id=std::to_string(reg); + result.hlsl+="RWBuffer out"+id+" : register(u"+id+");\n"; + } + result.hlsl+="[numthreads("+std::to_string(x)+","+std::to_string(y)+","+std::to_string(z)+")]\nvoid main(uint bin:SV_GroupIndex){\n"; + for(unsigned reg=0;reg +#include +#include +#include + +namespace x2w { +struct ClearBinding { + unsigned parameter; + unsigned byte_offset; +}; +struct ComputeClear { + std::string hlsl; + // Entry i must bind the guest's 256-element R32_UINT UAV to register ui. + std::vector bindings; +}; +ComputeClear replay_group_clear(const std::filesystem::path& marker, unsigned entry_offset); +} diff --git a/src/gfx1013_compute_ir.cpp b/src/gfx1013_compute_ir.cpp new file mode 100644 index 000000000..a5c7d795b --- /dev/null +++ b/src/gfx1013_compute_ir.cpp @@ -0,0 +1,163 @@ +#include "gfx1013_compute_ir.h" +#include +#include +#include +#include +#include + +namespace x2w { +LocalDataAccess decode_local_data(uint32_t instruction, uint32_t operands) { + if ((instruction & 0xfc030000u) != 0xd8000000u) + throw std::runtime_error("expected a local DS instruction with GDS clear"); + const unsigned op = (instruction >> 18) & 255, offset = instruction & 65535; + const unsigned addr = operands & 255, data0 = (operands >> 8) & 255, data1 = (operands >> 16) & 255, + dst = operands >> 24; + LocalDataAccess access{offset, addr, data0, data1, dst, 1}; + // The DS opcode/tuple layout follows Victory 9376fd6 gfx10/{opcodes,fields}.rs. + // The 32-bit read-modify-write operations follow compute_store_aot.py LDS_RMW. + switch (op) { + case 0x00: case 0x20: case 0x01: case 0x21: + access.atomic_ir = "add"; access.atomic_hlsl = "Add"; access.subtract = (op & 1) != 0; + break; + case 0x07: case 0x27: access.atomic_ir = "umin"; access.atomic_hlsl = "Min"; break; + case 0x08: case 0x28: access.atomic_ir = "umax"; access.atomic_hlsl = "Max"; break; + case 0x09: case 0x29: access.atomic_ir = "and"; access.atomic_hlsl = "And"; break; + case 0x0a: case 0x2a: access.atomic_ir = "or"; access.atomic_hlsl = "Or"; break; + case 0x0b: case 0x2b: access.atomic_ir = "xor"; access.atomic_hlsl = "Xor"; break; + case 0x2d: access.atomic_ir = "xchg"; access.atomic_hlsl = "Exchange"; break; + case 0x36: access.read = true; break; // read_b32 + case 0x76: access.read = true; access.count = 2; break; + case 0xfe: access.read = true; access.count = 3; break; + case 0xff: access.read = true; access.count = 4; break; + case 0x0d: break; // write_b32 + case 0x4d: access.count = 2; break; + case 0xde: access.count = 3; break; + case 0xdf: access.count = 4; break; + case 0x0e: case 0x0f: case 0x37: case 0x38: + case 0x4e: case 0x4f: case 0x77: case 0x78: + access.pair_words = op >= 0x40 ? 2 : 1; + access.count = 2 * access.pair_words; + access.read = (op & 0x3f) >= 0x37; + access.stride64 = (op & 0x3f) == 0x0f || (op & 0x3f) == 0x38; + break; + default: + throw std::runtime_error("unsupported local DS opcode " + std::to_string(op)); + } + access.return_old = access.atomic_ir && op >= 0x20; + const unsigned first_width = access.pair_words ? access.pair_words : access.count; + if (access.read ? data0 || data1 || dst + access.count > 256 : + (!access.return_old && dst) || (!access.pair_words && data1) || + data0 + first_width > 256 || data1 + access.pair_words > 256) + throw std::runtime_error("invalid local DS register tuple"); + return access; +} + +static std::string lower_lds(uint32_t instruction, uint32_t operands) { + const auto access = decode_local_data(instruction, operands); + // Preserve the input address when a read writes back to the address VGPR. + std::string out = "if (exec & 1u) { uint ds_addr = v" + std::to_string(access.address) + "; "; + for (unsigned i = 0; i < access.count; ++i) { + auto location = "lds[(ds_addr + " + std::to_string(access.byte_offset(i)) + "u) >> 2]"; + auto reg = "v" + std::to_string(access.read ? access.destination + i : access.data_register(i)); + if (access.atomic_ir) { + auto value = access.subtract ? "(0u - " + reg + ")" : reg; + out += std::string("Interlocked") + access.atomic_hlsl + "(" + location + ", " + value; + if (access.return_old) + out += ", v" + std::to_string(access.destination); + out += "); "; + } else + out += access.read ? reg + " = " + location + "; " : location + " = " + reg + "; "; + } + return out + "}"; +} + +// Single-word VOP2 with an optional 32-bit literal. SGPR and lane-special +// operands require provenance from the entry layout and stay in the frontend. +static std::string lower_vop2(uint32_t word, std::optional literal) { + const auto src0 = word & 511u; + if ((word >> 31) || (src0 == 255) != literal.has_value()) + throw std::runtime_error("invalid VOP2 word or literal length"); + std::string a; + if (src0 >= 256) + a = "v" + std::to_string(src0 - 256); + else if (literal) + a = std::to_string(*literal) + "u"; + else if (src0 >= 128 && src0 <= 192) + a = std::to_string(src0 - 128) + "u"; + else if (src0 >= 193 && src0 <= 208) + a = std::to_string(192u - src0) + "u"; + else + throw std::runtime_error("unsupported VOP2 source"); + const std::string b = "v" + std::to_string((word >> 9) & 255); + const std::string dst = "v" + std::to_string((word >> 17) & 255); + std::string expr; + switch (word >> 25) { + case 3: + expr = "asuint(asfloat(" + a + ") + asfloat(" + b + "))"; + break; + case 4: + expr = "asuint(asfloat(" + a + ") - asfloat(" + b + "))"; + break; + case 5: + expr = "asuint(asfloat(" + b + ") - asfloat(" + a + "))"; + break; + case 8: + expr = "asuint(asfloat(" + a + ") * asfloat(" + b + "))"; + break; + case 11: + expr = "(" + a + " & 0xffffffu) * (" + b + " & 0xffffffu)"; + break; + case 26: + expr = b + " << (" + a + " & 31u)"; + break; + case 37: + expr = a + " + " + b; + break; + default: + throw std::runtime_error("unsupported VOP2 opcode"); + } + return "if (exec & 1u) " + dst + " = " + expr + ";"; +} + +std::string expand_gfx1013_compute(const std::string &source) { + constexpr std::string_view lds = "#pragma x2w_lds ", alu = "#pragma x2w_vop2 "; + std::string output; + size_t pos = 0; + while (pos < source.size()) { + auto end = source.find('\n', pos); + if (end == source.npos) + end = source.size(); + std::string_view line(source.data() + pos, end - pos); + auto first = line.find_first_not_of(" \t"); + const auto trimmed = first == line.npos ? std::string_view{} : line.substr(first); + const bool ds = trimmed.substr(0, lds.size()) == lds; + if (ds || trimmed.substr(0, alu.size()) == alu) { + auto args = trimmed.substr(ds ? lds.size() : alu.size()); + if (!args.empty() && args.back() == '\r') + args.remove_suffix(1); + if ((args.size() != 17 || args[8] != ' ') && (ds || args.size() != 8)) + throw std::runtime_error("invalid native compute instruction length"); + auto parse = [](std::string_view token) { + uint32_t word{}; + auto r = std::from_chars(token.data(), token.data() + token.size(), word, 16); + if (r.ec != std::errc{} || r.ptr != token.data() + token.size()) + throw std::runtime_error("invalid compute word"); + return word; + }; + auto instruction = parse(args.substr(0, 8)); + std::optional second; + if (args.size() == 17) + second = parse(args.substr(9)); + output += ds ? lower_lds(instruction, *second) : lower_vop2(instruction, second); + } else { + if (trimmed.substr(0, 12) == "#pragma x2w_") + throw std::runtime_error("unknown native compute pragma"); + output.append(line); + } + if (end < source.size()) + output += '\n'; + pos = end + 1; + } + return output; +} +} // namespace x2w diff --git a/src/gfx1013_compute_ir.h b/src/gfx1013_compute_ir.h new file mode 100644 index 000000000..eab66f7d9 --- /dev/null +++ b/src/gfx1013_compute_ir.h @@ -0,0 +1,26 @@ +#pragma once +#include +#include + +namespace x2w { +struct LocalDataAccess { + unsigned offset, address, data0, data1, destination, count; + unsigned pair_words; // Width of each independently offset element; zero for a single address. + bool read, stride64, return_old; + const char *atomic_ir, *atomic_hlsl; + bool subtract; + unsigned byte_offset(unsigned element) const { + if (!pair_words) return offset + 4 * element; + unsigned encoded = (offset >> (8 * (element / pair_words))) & 255; + return 4 * (encoded * pair_words * (stride64 ? 64 : 1) + element % pair_words); + } + unsigned data_register(unsigned element) const { + return pair_words && element >= pair_words ? data1 + element - pair_words : data0 + element; + } +}; +LocalDataAccess decode_local_data(uint32_t instruction, uint32_t operands); + +// Expand compute instruction words in the register-based HLSL frontend. +// Bit zero of exec is the current lane's EXEC bit. lds is groupshared uint[]. +std::string expand_gfx1013_compute(const std::string &source); +} // namespace x2w diff --git a/src/gfx1013_compute_mtbuf.inl b/src/gfx1013_compute_mtbuf.inl new file mode 100644 index 000000000..9c8ff1312 --- /dev/null +++ b/src/gfx1013_compute_mtbuf.inl @@ -0,0 +1,116 @@ +// MTBUF uses the instruction's explicit format and the descriptor's byte range. +// Format numbers follow tools/disasm_rdna2.py MTBUF_FORMATS. Conversion and +// unaligned addressing follow gfx2hlsl.tbuffer / ldu, cross-checked against +// Victory 9376fd6 format_load. Only the runtime-checked identity raw SRV is used. +enum class ChannelNumber { unorm, snorm, uscaled, sscaled, uint_, sint, float_ }; +struct MtbufFamily { + unsigned first, last, bits, components; + ChannelNumber first_number; +}; +string normalized_channel(const string &field, unsigned width, bool snorm) { + // p/(2^k-1) has binary expansion 0.ppp... (p padded to k bits). + // Rotate the first set bit to the top, repeat at least 25 bits, then + // round a 24-bit significand. A nonzero repeating tail is never a tie. + const unsigned k = width - unsigned(snorm); + const auto max = to_string((1u << k) - 1); + string p = field, sign = "0"; + if (snorm) { + sign = ir.binary("and", field, "2147483648"); + p = select(cmp("slt", field, "0"), ir.binary("sub", "0", field), field); + p = select(cmp("ugt", p, max), max, p); + } + // p has at most 16 bits; converting it to binary32 is exact. + auto exp = ir.binary("lshr", ir.value("bitcast float " + ir.value("uitofp i32 " + p + " to float") + " to i32"), "23"); + auto distance = ir.binary("and", ir.binary("sub", to_string(126 + k), exp), "31"); + auto right = ir.binary("and", ir.binary("sub", to_string(k), distance), "31"); + auto period = ir.binary("and", ir.binary("or", ir.binary("shl", p, distance), ir.binary("lshr", p, right)), max); + unsigned periods = (25 + k - 1) / k, precision = periods * k; + unsigned repeats = 0; + for (unsigned i = 0; i < periods; ++i) + repeats |= 1u << (i * k); + auto digits = ir.binary("mul", period, to_string(repeats)); + auto rounded = ir.binary("add", ir.binary("lshr", digits, to_string(precision - 24)), + ir.binary("and", ir.binary("lshr", digits, to_string(precision - 25)), "1")); + auto base = ir.binary("shl", ir.binary("sub", exp, to_string(k + 1)), "23"); + auto magnitude = select(cmp("eq", p, "0"), "0", ir.binary("add", base, rounded)); + return snorm ? ir.binary("or", magnitude, sign) : magnitude; +} +void formatted_byte_load(const Inst &i, const State &s) { + constexpr MtbufFamily families[] = { + {1, 6, 8, 1, ChannelNumber::unorm}, {7, 13, 16, 1, ChannelNumber::unorm}, + {14, 19, 8, 2, ChannelNumber::unorm}, {20, 22, 32, 1, ChannelNumber::uint_}, + {23, 29, 16, 2, ChannelNumber::unorm}, {56, 61, 8, 4, ChannelNumber::unorm}, + {62, 64, 32, 2, ChannelNumber::uint_}, {65, 71, 16, 4, ChannelNumber::unorm}, + {72, 74, 32, 3, ChannelNumber::uint_}, {75, 77, 32, 4, ChannelNumber::uint_} + }; + const unsigned format = (i.a >> 19) & 127, count = i.op + 1; + const auto family = std::find_if(std::begin(families), std::end(families), [&](const auto &f) { + return format >= f.first && format <= f.last; + }); + if (family == std::end(families) || count > family->components) + refuse(i.pc, "unsupported MTBUF format or absent component"); + if (i.dst + count > 256) + refuse(i.pc, "MTBUF destination tuple overflow"); + const unsigned width = family->bits; + const auto numeric = static_cast(unsigned(family->first_number) + format - family->first); + const auto handle = resource(i, s, (i.b >> 16 & 31) * 4, ComputeViewKind::raw_vector_srv, 4); + const unsigned scalar_offset = i.b >> 24; + auto addr = to_string(i.a & 4095); + if (scalar_offset != 125 && scalar_offset != 128) + addr = ir.binary("add", addr, operand32(i, scalar_offset)); + if (i.a & 0x1000) + addr = ir.binary("add", addr, read(256 + (i.b & 255))); + // RDNA2 checks the whole formatted element. Desktop raw loads by + // themselves can return some in-range components from a truncated element. + auto dimensions = ir.invoke("%dx.types.Dimensions", "getDimensions", 72, + {{"%dx.types.Handle", handle}, {"i32", "undef"}}, "nounwind readonly"); + auto bytes = ir.value("extractvalue %dx.types.Dimensions " + dimensions + ", 0"); + auto size = to_string(width * family->components / 8); + auto valid = ir.value("and i1 " + cmp("uge", bytes, size) + ", " + + cmp("ule", addr, ir.binary("sub", bytes, size))); + const auto aligned = ir.binary("and", addr, "4294967292"); + const auto shift_bits = ir.binary("shl", ir.binary("and", addr, "3"), "3"); + const unsigned word_count = (count * width + 31) / 32; + const auto chunk = load_buffer(handle, aligned, true, word_count); + std::array words; + for (unsigned j = 0; j < word_count; ++j) + words[j] = ir.value("extractvalue %dx.types.ResRet.i32 " + chunk + ", " + to_string(j)); + if (count * width > 8) { + const auto next = ir.binary("add", aligned, to_string(word_count * 4)); + const auto high = load_buffer(handle, next, true, 1); + words[word_count] = select(cmp("ult", next, aligned), "0", + ir.value("extractvalue %dx.types.ResRet.i32 " + high + ", 0")); + } + // Snapshot all address-derived values before writing destinations: OFFEN's + // VGPR can be any member of the output tuple. + const auto aligned_access = cmp("eq", shift_bits, "0"); + const auto inverse = ir.binary("and", ir.binary("sub", "0", shift_bits), "31"); + for (unsigned j = 0; j < word_count; ++j) { + const auto low = ir.binary("lshr", words[j], shift_bits); + words[j] = words[j + 1].empty() ? low : + ir.binary("or", low, select(aligned_access, "0", ir.binary("shl", words[j + 1], inverse))); + } + for (unsigned j = 0; j < count; ++j) { + auto field = words[j * width / 32]; + if (width < 32) { + field = ir.binary("lshr", field, to_string(j * width % 32)); + field = ir.binary("and", field, to_string((1u << width) - 1)); + } + const bool signed_field = numeric == ChannelNumber::sint || numeric == ChannelNumber::snorm || + numeric == ChannelNumber::sscaled; + if (signed_field && width < 32) { + auto distance = to_string(32 - width); + field = ir.binary("ashr", ir.binary("shl", field, distance), distance); + } + if (numeric == ChannelNumber::float_ && width == 16) { + auto f = ir.invoke("float", "legacyF16ToF32", 131, {{"i32", field}}, "nounwind readnone"); + field = ir.value("bitcast float " + f + " to i32"); + } else if (numeric == ChannelNumber::unorm || numeric == ChannelNumber::snorm) { + field = normalized_channel(field, width, signed_field); + } else if (numeric == ChannelNumber::uscaled || numeric == ChannelNumber::sscaled) { + auto f = ir.value(string(signed_field ? "sitofp" : "uitofp") + " i32 " + field + " to float"); + field = ir.value("bitcast float " + f + " to i32"); + } + vector_write(256 + i.dst + j, select(valid, field, "0")); + } +} diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp new file mode 100644 index 000000000..d37bf7517 --- /dev/null +++ b/src/gfx1013_compute_native.cpp @@ -0,0 +1,1890 @@ +#include "gfx1013_compute_native.h" +#include "gfx1013_compute_ir.h" +#include "dxil_module.h" +#include "guest_shader_container.h" +#include "gfx1013_isa.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace x2w; +using std::string; +using std::to_string; +using Word = uint32_t; +using Name = std::string_view; + +static bool binary16_alu(std::string_view name) { + return name == "v_add_f16" || name == "v_sub_f16" || name == "v_subrev_f16" || name == "v_mul_f16"; +} + +[[noreturn]] void refuse(unsigned pc, const string &reason) { + std::ostringstream out; + out << "native compute +0x" << std::hex << pc << ": " << reason; + throw UnsupportedComputeShader(out.str()); +} +Word word(const string &bytes, unsigned at) { + if (at > bytes.size() || bytes.size() - at < 4) + refuse(at, "truncated word"); + Word n; + std::memcpy(&n, bytes.data() + at, 4); + return n; +} +string hexword(Word n) { + char s[12]; + snprintf(s, sizeof(s), "0x%08xu", n); + return s; +} +enum class Encoding { Sopp, Sop1, Sop2, Sopc, Sopk, Vop1, Vop2, Vopc, Vop3, Mix, Smem, Image, Mubuf, Lds, Export, Interp, Fetch, FixedSetup, FixedFetch }; +#include "gfx1013_compute_opcodes.inl" +struct Inst { + unsigned pc = 0, next = 0, op = 0, dst = 0; + Encoding enc{}; + Word a = 0, b = 0, literal = 0; + std::array image_address_words{}; + std::array src{}; + Name name; + unsigned abs = 0, neg = 0, scale = 0; + bool clamp = false, wide = false, subword = false; + // 0..255 selects within a quad. The two mirror controls cross quads. + std::optional dpp_control; + bool dpp_fetch_inactive = false; + bool dpp_bound_zero = false; + unsigned mirror_mask() const { return dpp_control == 0x141 ? 7 : dpp_control == 0x140 ? 15 : 0; } + std::array src_select{6, 6}; + std::array src_sext{}; + unsigned dst_select = 6, dst_unused = 0; + bool branch() const { + return enc == Encoding::Sopp && (op == 2 || op == 4 || op == 5 || op == 6 || op == 7 || op == 8 || op == 9); + } + unsigned target() const { return next + 4 * static_cast(a & 65535); } +}; +Inst decode(const string &bytes, unsigned pc,bool direct=false, bool graphics=false) { + const auto encoded=gfx1013::instruction(bytes,pc); + Inst i; + i.pc = pc; + i.next = pc; + auto take = [&]() { + auto n = word(bytes, i.next); + i.next += 4; + return n; + }; + Word a = i.a = take(); + if (graphics && (encoded.form == gfx1013::Form::exp || encoded.form == gfx1013::Form::vintrp || + a == 0xbe842104)) { + if (encoded.form == gfx1013::Form::exp) { + i.enc = Encoding::Export; + i.b = take(); + } else i.enc = encoded.form == gfx1013::Form::vintrp ? Encoding::Interp : Encoding::Fetch; + i.name = encoded.name; + return i; + } + auto form = a & 0xff800000u; + bool lit = false; + if (form == 0xbf800000) { + i.enc = Encoding::Sopp; + i.op = (a >> 16) & 127; + } else if (form == 0xbe800000) { + i.enc = Encoding::Sop1; + i.op = (a >> 8) & 255; + i.dst = (a >> 16) & 127; + i.src[0] = a & 255; + lit = i.src[0] == 255; + } else if (form == 0xbf000000) { + i.enc = Encoding::Sopc; + i.op = (a >> 16) & 127; + i.src = {a & 255, (a >> 8) & 255, 0}; + lit = i.src[0] == 255 || i.src[1] == 255; + } else if ((a >> 28) == 11) { + i.enc = Encoding::Sopk; + i.op = (a >> 23) & 31; + i.dst = (a >> 16) & 127; + // s_setreg_imm32_b32 carries the written value in a literal word. + lit = i.op == 0x15; + } else if ((a >> 30) == 2) { + i.enc = Encoding::Sop2; + i.op = (a >> 23) & 127; + i.dst = (a >> 16) & 127; + i.src = {a & 255, (a >> 8) & 255, 0}; + lit = i.src[0] == 255 || i.src[1] == 255; + } else if ((a >> 31) == 0) { + auto k = a >> 25; + i.dst = 256 + ((a >> 17) & 255); + i.src = {a & 511, 256 + ((a >> 9) & 255), 106}; + if (k == 63) { + i.enc = Encoding::Vop1; + i.op = (a >> 9) & 255; + } else if (k == 62) { + i.enc = Encoding::Vopc; + i.op = (a >> 17) & 255; + i.dst = 106; + } else { + i.enc = Encoding::Vop2; + i.op = k; + } + lit = i.src[0] == 255 || + (i.enc == Encoding::Vop2 && (k == 0x20 || k == 0x21 || k == 0x2c || k == 0x2d || k == 0x37 || k == 0x38)); + } else if ((a & 0xfc000000u) == 0xf4000000) { + i.enc = Encoding::Smem; + i.b = take(); + i.op = (a >> 18) & 255; + i.dst = (a >> 6) & 127; + i.src[0] = (a & 63) * 2; + const unsigned soffset = i.b >> 25; + if ((i.b & 0x01f00000u) || (a & 0x14000) || (i.op & ~8u) > 4 || + (soffset != 125 && ((!direct && i.op < 8 && i.op != 2) || soffset > 105))) + refuse(pc, "unsupported scalar memory addressing"); + i.name = "smem"; + } else if ((a & 0xfc000000u) == 0xf0000000) { + i.enc = Encoding::Image; + i.b = take(); + i.op = ((a >> 18) & 127) | ((a & 1) << 7); + i.dst = (i.b >> 8) & 255; + unsigned extra = (a >> 1) & 3; + if (!direct && extra > 1) + refuse(pc, "image NSA count"); + for (unsigned j = 0; j < extra; ++j) + i.image_address_words[j] = take(); + const bool sample_d16 = direct && (i.op == 32 || i.op == 34 || i.op == 36 || i.op == 37 || i.op == 39) && + ((a >> 3) & 7) != 3; + if ((!direct && ((a >> 3) & 7) != 1) || ((i.b & 0x80000000u) && !sample_d16 && + (i.op != 8 || (!direct && ((a >> 8) & 15) != 1)))) + refuse(pc, "unsupported image dimension or D16"); + i.name = "image"; + } else if ((a & 0xfc000000u) == 0xe0000000u) { + i.b = take(); + i.op = (a >> 18) & 127; + i.op |= (a >> 18) & 0x80; + if (direct && encoded.name.substr(0, 14) == "buffer_atomic_") { + // Byte offset plus optional VGPR address and GLC old-value return. + // Indexed atomics currently access the first dword of the chosen element. + if ((a & 0x00038000u) || (i.b & 0x00e00000u)) + refuse(pc, "unsupported buffer atomic addressing or cache policy"); + if ((a & 0x2000u) && (graphics || (a & 0x1fffu) || + ((i.b >> 24) != 128 && (i.b >> 24) != 125))) + refuse(pc, "indexed compute atomic requires zero byte offsets"); + i.name = encoded.name; + } else if ((i.op >= 4 && i.op <= 7) || (i.op >= 0x84 && i.op <= 0x87)) { + if ((a & 0x3ffffu) != 0x2000u || (i.b & 0xffe00000u) != 0x80000000u || i.op == 0x86) + refuse(pc, "formatted store needs an index-only linear view and supported component count"); + i.name = "buffer_store_format"; + } else if (i.op >= 0x1c && i.op <= 0x1f) { + if ((a & 0x3e000u) || (i.b & 0xe00000u)) + refuse(pc, "raw store needs a linear byte offset"); + i.name = "buffer_store_raw"; + } else if (i.op >= 0x0c && i.op <= 0x0f) { + if ((a & 0x0203f000u) != 0x1000u || (i.b & 0xffe00000u) != 0x80000000u) + refuse(pc, "raw buffer load needs offen with zero scalar offset and no modifiers"); + i.name = "buffer_load_dword"; + } else { + if (i.op > 3) + refuse(pc, "unsupported buffer operation"); + const auto addressing = a & 0x3ffffu; + if ((addressing != 0x2000u && !(direct && addressing == 0)) || + (a & 0x02000000u) || (i.b & 0xffe00000u) != 0x80000000u) + refuse(pc, "formatted load requires zero or a single linear index"); + i.name = "buffer_load_format"; + } + i.enc = Encoding::Mubuf; + i.dst = (i.b >> 8) & 255; + } else if (direct && !graphics && encoded.form == gfx1013::Form::mtbuf) { + i.b = take(); + i.op = encoded.opcode; + if (i.op > 3 || (a & 0xe000u) || (i.b & 0xe00000u)) + refuse(pc, "MTBUF requires a non-D16 load without index, cache modifiers or TFE"); + i.enc = Encoding::Mubuf; + i.name = encoded.name; + i.dst = (i.b >> 8) & 255; + } else if (direct && !graphics && (a & 0xfc000000u) == 0xdc000000u) { + // FLAT encoding, segment 2 (GLOBAL). Only the one-dword load with an SGPR-pair base (the saddr form, + // ADDR = SADDR + zext(VADDR) + sext(OFFSET)) is lowered, as gfx2hlsl.py op_global_load_dword does. + // SADDR 125 is `off` on gfx10. LDS, the other segments and opcodes stay refused. + i.b = take(); + i.op = (a >> 18) & 127; + const unsigned saddr = (i.b >> 16) & 127; + if (((a >> 14) & 3) != 2 || i.op != 12 || (a & 0x2000u) || saddr == 125 || saddr == 127) + refuse(pc, "direct global memory supports only global_load_dword with a scalar address pair"); + i.enc = Encoding::Mubuf; + i.name = "global_load_dword"; + i.dst = i.b >> 24; + } else if ((a & 0xfc000000u) == 0xd8000000) { + i.enc = Encoding::Lds; + i.b = take(); + i.name = "lds"; + } else if ((a & 0xfc000000u) == 0xd4000000 || (a & 0xff800000u) == 0xcc000000) { + i.wide = true; + i.b = take(); + i.enc = (a >> 26) == 0x35 ? Encoding::Vop3 : Encoding::Mix; + i.op = (a >> 16) & (i.enc == Encoding::Mix ? 0x7f : 0x3ff); + i.src = {i.b & 511, (i.b >> 9) & 511, (i.b >> 18) & 511}; + i.abs = (a >> 8) & 7; + i.neg = i.b >> 29; + i.scale = (i.b >> 27) & 3; + i.clamp = (a & 0x8000) != 0; + i.dst = 256 + (a & 255); + if (i.enc == Encoding::Vop3 && i.op < 256) { + i.enc = Encoding::Vopc; + i.dst = a & 255; + } else if (i.enc == Encoding::Vop3 && i.op >= 0x100 && i.op < 0x140) { + i.enc = Encoding::Vop2; + i.op -= 0x100; + } else if (i.enc == Encoding::Vop3 && i.op >= 0x180 && i.op < 0x200) { + i.enc = Encoding::Vop1; + i.op -= 0x180; + } + lit = std::find(i.src.begin(), i.src.end(), 255) != i.src.end(); + } else + refuse(pc, "unsupported instruction " + string(encoded.name) + " " + hexword(a)); + if (!i.wide && (i.enc == Encoding::Vop1 || i.enc == Encoding::Vop2 || i.enc == Encoding::Vopc)) { + const bool half_alu = !graphics && i.enc == Encoding::Vop2 && binary16_alu(encoded.name); + if (direct && half_alu && i.src[0] == 250) + refuse(pc, "unsupported " + string(encoded.name) + " DPP form"); + const bool sdwa_logic = i.enc == Encoding::Vop2 && i.op == 0x1d; + const bool sdwa_class = i.enc == Encoding::Vopc && i.op == 0x88; + const bool sdwa_compare = i.enc == Encoding::Vopc && !sdwa_class; + if (direct && i.src[0] == 249 && (sdwa_compare || i.enc == Encoding::Vop1 || i.enc == Encoding::Vop2)) { + // Operand profiles from disasm_rdna2's GFX10 VOP1/VOP2 SDWA + // decoder. Admit only profiles with a direct result placement. + static const std::set bits{ + "v_mov_b32", "v_not_b32", "v_cndmask_b32", "v_bfrev_b32", "v_mul_u32_u24", + "v_add_nc_u32", "v_sub_nc_u32", "v_subrev_nc_u32", + "v_and_b32", "v_or_b32", "v_xor_b32", "v_min_u32", "v_max_u32", + "v_min_i32", "v_max_i32", "v_lshlrev_b32", "v_lshrrev_b32", "v_ashrrev_i32"}; + static const std::set floats{ + "v_add_f32", "v_sub_f32", "v_subrev_f32", "v_mul_f32", "v_min_f32", "v_max_f32", + "v_floor_f32", "v_ceil_f32", "v_fract_f32", "v_trunc_f32", "v_rndne_f32", + "v_exp_f32", "v_log_f32", "v_rcp_f32", "v_rsq_f32", "v_sqrt_f32"}; + const auto name = encoded.name; + const bool fp_input = half_alu || floats.count(name) || name == "v_cvt_u32_f32" || name == "v_cvt_i32_f32" || + name == "v_cvt_f16_f32" || name == "v_cvt_f32_f16" || + (sdwa_compare && (name.substr(name.size()-4) == "_f32" || name.substr(name.size()-4) == "_f16")); + const bool conversion = name == "v_cvt_f32_i32" || name == "v_cvt_f32_u32" || + name.substr(0,15) == "v_cvt_f32_ubyte"; + if (!(fp_input || conversion || bits.count(name) || sdwa_compare)) + refuse(pc, "unimplemented direct SDWA operand profile"); + const Word ext = take(); + const unsigned sources = i.enc == Encoding::Vop1 ? 1 : 2; + if (sdwa_compare) { + if ((ext & 0x8000) && (name.substr(0,7) == "v_cmpx_" || ((ext >> 8) & 127) > 106)) + refuse(pc, "invalid SDWA compare destination"); + i.dst = ext & 0x8000 ? (ext >> 8) & 127 : 106; + } else { + i.dst_select = (ext >> 8) & 7; + i.dst_unused = (ext >> 11) & 3; + i.scale = (ext >> 14) & 3; + i.clamp = (ext & (1u << 13)) != 0; + if (half_alu && ((i.dst_select != 4 && i.dst_select != 5) || + (i.dst_unused != 0 && i.dst_unused != 2))) + refuse(pc, "unsupported SDWA destination modifier"); + if (i.dst_select == 7 || i.dst_unused == 3 || ((i.clamp || i.scale) && !floats.count(name) && !conversion) || + (sources == 1 && (ext & 0xbf000000u))) + refuse(pc, "unsupported SDWA destination modifier"); + } + for (unsigned j = 0; j < sources; ++j) { + const unsigned control = (ext >> (16 + 8*j)) & 255; + i.src_select[j] = control & 7; + i.src_sext[j] = (control & 8) != 0; + if (half_alu && (control & 128)) + refuse(pc, "SDWA binary16 source must be a VGPR"); + if (half_alu && i.src_select[j] < 4) + refuse(pc, "invalid SDWA source modifier"); + if (i.src_select[j] == 7 || (control & 64) || (fp_input && i.src_sext[j]) || (!fp_input && (control & 0x30))) + refuse(pc, "invalid SDWA source modifier"); + i.abs |= ((control >> 5) & 1) << j; + i.neg |= ((control >> 4) & 1) << j; + const unsigned reg = j ? (a >> 9) & 255 : ext & 255; + if ((control & 128) && reg == 255) + refuse(pc, "literal is unavailable in SDWA"); + i.src[j] = reg + ((control & 128) ? 0 : 256); + } + i.subword = true; + lit = false; + } else if (i.src[0] == 249 && (sdwa_logic || sdwa_class)) { + const Word ext = take(); + i.src_select = {(ext >> 16) & 7, (ext >> 24) & 7}; + i.src_sext = {bool(ext & (1u << 19)), bool(ext & (1u << 27))}; + if (sdwa_logic) { + i.dst_select = (ext >> 8) & 7; + i.dst_unused = (ext >> 11) & 3; + if ((ext & 0x7070e000u) || i.dst_select == 7 || i.dst_unused == 3) + refuse(pc, "invalid or unsupported integer SDWA modifiers"); + } else { + // VOPC has a scalar mask destination in the same bits that VOP2 uses for placement. + i.dst = ext & 0x8000 ? (ext >> 8) & 127 : 106; + if ((ext & 0x70480000u) || (i.dst > 105 && i.dst != 106)) + refuse(pc, "invalid SDWA class modifiers or mask destination"); + i.neg = (ext >> 20) & 1; + i.abs = (ext >> 21) & 1; + } + if (i.src_select[0] == 7 || i.src_select[1] == 7) + refuse(pc, "invalid or unsupported integer SDWA modifiers"); + i.src[0] = (ext & 255) + (ext & (1u << 23) ? 0 : 256); + i.src[1] = ((a >> 9) & 255) + (ext & (1u << 31) ? 0 : 256); + if (i.src[0] == 255 || i.src[1] == 255) + refuse(pc, "literal is unavailable in SDWA"); + i.subword = true; + lit = false; + } else if (i.src[0] == 249 && i.enc == Encoding::Vop2 && (i.op == 1 || i.op == 0x25)) { + auto ext = take(); + if ((ext & 0xfff8ff00u) != 0x06000600u || ((ext >> 16) & 7u) > 6) + refuse(pc, "SDWA source or destination modifier"); + i.subword = true; + i.src_select[0] = (ext >> 16) & 7u; + i.src[0] = 256 + (ext & 255); + lit = false; + } else if (direct && i.src[0]==250 && i.enc!=Encoding::Vopc && !lit) { + auto control=take(); + // DPP_CTRL[8] selects patterns outside a quad; bit 17 is + // reserved. FI and BOUND_CTRL are independent of the pattern. + if ((control >> 24) != 0xff) refuse(pc,"DPP requires a full-row, full-bank quad permutation"); + if (control & (1u << 17)) refuse(pc,"reserved DPP16 control bit"); + const auto pattern = (control >> 8) & 0x1ff; + i.dpp_control = pattern; + if (pattern > 255 && !i.mirror_mask()) + refuse(pc,"unsupported DPP lane selection"); + i.dpp_fetch_inactive = (control & (1u << 18)) != 0; + i.dpp_bound_zero = (control & (1u << 19)) != 0; + i.src[0]=256+(control&255); + i.neg=((control>>20)&1)|((control>>21)&2); + i.abs=((control>>21)&1)|((control>>22)&2); + } else if (graphics && (i.src[0] == 233 || i.src[0] == 234) && i.enc != Encoding::Vopc && !lit) { + // pixel_aot.parse_dpp: both halves of an octet must select the + // same local 2x2 permutation to map to desktop quad operations. + const Word control = take(); + unsigned perm = 0; + for (unsigned lane = 0; lane < 4; ++lane) { + const unsigned low = (control >> (8 + 3 * lane)) & 7; + const unsigned high = (control >> (20 + 3 * lane)) & 7; + if (low >= 4 || high != low + 4) refuse(pc, "DPP8 requires repeating quad-local selections"); + perm |= low << (2 * lane); + } + i.dpp_control = perm; + i.dpp_fetch_inactive = i.src[0] == 234; + i.src[0] = 256 + (control & 255); + } else if (i.src[0] == 249 || i.src[0] == 250 || i.src[0] == 233 || i.src[0] == 234) + refuse(pc, "SDWA or DPP vector operands"); + } + if (lit) + i.literal = take(); + if (i.enc == Encoding::Vop1 && !i.op) i.name = "v_nop"; + if (i.name.empty()) { + const char *name = mnemonic(i.enc,i.op); + if (!name && (direct || encoded.name == "v_readlane_b32") && !encoded.name.empty()) + name = encoded.name.data(); + if (!name) + refuse(pc, "unsupported opcode " + hexword(a)); + i.name = name; + if (i.name.substr(0, 7) == "v_cmpx_") + i.dst = 126; + if (i.name == "v_readfirstlane_b32" || i.name == "v_readlane_b32") { + i.dst -= 256; + if (i.dst > (graphics ? 105u : 107u)) + refuse(pc, "invalid scalar lane read destination"); + } + } + if(i.next-pc!=encoded.size)refuse(pc,"instruction extent mismatch for "+string(encoded.name)); + return i; +} +// VOP3B carries a scalar destination in the field used for ABS in VOP3A. +static std::optional carry_destination(const Inst &i) { + if (i.name == "v_add_co_u32" || i.name == "v_sub_co_u32" || i.name == "v_subrev_co_u32" || + i.name == "v_add_co_ci_u32" || i.name == "v_sub_co_ci_u32" || i.name == "v_subrev_co_ci_u32") + return i.wide ? (i.a >> 8) & 127 : 106; + return {}; +} +struct Symbol { + enum class Type { unknown, constant, masked, table, descriptor, indexed_descriptor, root_address, primitive_mask, + stride, byte_stride, zero_stride_word, byte_count, clear_oob, byte_oob, lane_mask, uniform_mask, unbound } type{}; + Word value = 0, offset = 0; + unsigned index_mask = 0, definition = 0; + bool numeric() const { return type == Type::unknown || type == Type::constant || type == Type::masked || type == Type::uniform_mask; } + bool operator==(const Symbol &r) const { return type == r.type && value == r.value && offset == r.offset && + index_mask == r.index_mask && definition == r.definition; } +}; +using State = std::array; +// FSSM root descriptors carry a guest address in two SGPRs. Preserve the +// identity of each half through scalar moves and CFG joins (Victory resource.rs). +void bind_root_address(State &state, const ShaderRootInput &input, unsigned limit) { + const unsigned at = input.user_data; + if (input.sgpr_count != 2 || at >= limit || limit - at < 2 || input.root_parameter >= 16 || + input.offset_dwords || state[at].type != Symbol::Type::unbound || state[at+1].type != Symbol::Type::unbound) + refuse(0, "invalid FSSM root descriptor pair"); + for (unsigned half = 0; half < 2; ++half) + state[at + half] = {Symbol::Type::root_address, input.root_parameter, half}; +} +Symbol source(const Inst &i, unsigned code, const State &s) { + if (code < 128) + return s[code]; + if (code <= 192) + return {Symbol::Type::constant, code - 128}; + if (code <= 208) + return {Symbol::Type::constant, 192u - code}; + if (code == 255) + return {Symbol::Type::constant, i.literal}; + return {}; +} +unsigned memory_count(const Inst &i) { return 1u << (i.op & 7); } +// Derive the rewritten byte-address V# symbolically. Each field carries its +// source table/slot identity. Numeric consumption still requires real bits. +// heap_window: the direct path under HeapViewContract::raw_buffer also rewrites a +// descriptor loaded from the GPU-selected heap slot (its words keep the load pc). +static std::optional byte_descriptor_field(const Inst &i, const State &s, bool heap_window = false) { + using T = Symbol::Type; + if (i.enc != Encoding::Sop2 || i.dst > 105) return {}; + auto a = source(i, i.src[0], s), b = source(i, i.src[1], s); + auto component = [heap_window](const Symbol &v, unsigned ch) { + return v.offset % 32 == ch*4 && ((v.type == T::descriptor && v.value != compute_resource_heap) || + (heap_window && v.type == T::indexed_descriptor && v.value == compute_resource_heap)); + }; + auto field = [](Symbol v, T kind) { + v.type = kind; + v.offset &= ~31u; + return v; + }; + if (i.name == "s_bfe_u32" && component(a, 1) && b.type == T::constant && b.value == 0xe0010) + return field(a, T::stride); + if (i.name == "s_mul_i32") { + if (a.type == T::byte_stride) std::swap(a,b); + if (component(a, 2) && b == field(a,T::byte_stride)) return field(a, T::byte_count); + } + if (a.type == T::constant) std::swap(a,b); + if (b.type != T::constant) return {}; + if (i.name == "s_max_u32" && a.type == T::stride && b.value == 1) return field(a, T::byte_stride); + if (i.name == "s_and_b32" && b.value == 0xc000ffff && component(a,1)) return field(a,T::zero_stride_word); + if (i.name == "s_and_b32" && b.value == 0xcfffffff && component(a,3)) return field(a,T::clear_oob); + if (i.name == "s_or_b32" && b.value == 0x30000000 && (a.type == T::clear_oob || component(a,3))) + return field(a,T::byte_oob); + return {}; +} +State transfer(const Inst &i, State s, bool wave64, bool graphics, bool heap_window = false) { + auto set = [&](unsigned n, Symbol v) { + if (n >= s.size()) + refuse(i.pc, "invalid SGPR"); + s[n] = v; + }; + auto mask = carry_destination(i); + const bool compared = graphics && i.enc == Encoding::Vopc && i.dst < 106 && i.name.substr(0,6) == "v_cmp_"; + if (mask || compared) { + const unsigned dst = mask.value_or(i.dst); + if ((dst > 105 && dst != 106) || (wave64 && (dst & 1))) + refuse(i.pc, compared ? "unsupported comparison mask destination" : "unsupported carry mask destination"); + const bool tagged = graphics && dst != 106; + set(dst, tagged ? Symbol{Symbol::Type::lane_mask,i.pc,0} : Symbol{}); + if (wave64) set(dst + 1, tagged ? Symbol{Symbol::Type::lane_mask,i.pc,1} : Symbol{}); + } else if (graphics && i.name == "s_cselect_b64" && i.dst <= 104 && !(i.dst & 1) && + (i.src[0] == 193 || i.src[0] == 128) && (i.src[1] == 193 || i.src[1] == 128)) { + set(i.dst,{Symbol::Type::uniform_mask,i.pc,0}); + set(i.dst+1,{Symbol::Type::uniform_mask,i.pc,1}); + } else if (auto field = byte_descriptor_field(i,s,heap_window)) { + set(i.dst,*field); + } else if (i.enc == Encoding::FixedSetup) { + for (unsigned r = i.dst; r < i.dst + i.op && r < s.size(); ++r) s[r] = {}; + } else if (i.enc == Encoding::Fetch) { + s[4].type = s[5].type = Symbol::Type::unbound; + } else if (i.enc == Encoding::Smem) { + auto base = s[i.src[0]]; + const unsigned offset_reg = i.b >> 25; + const Symbol index = offset_reg <= 105 ? s[offset_reg] : Symbol{}; + unsigned n = memory_count(i); + for (unsigned j = 0; j < n; ++j) { + Symbol v{}; + if (i.op == 2 && i.b >> 25 != 125 && base.type == Symbol::Type::table) { + v = {Symbol::Type::indexed_descriptor, base.value, (i.b & 0xfffff) + 4*j, + index.type == Symbol::Type::masked || index.type == Symbol::Type::constant ? index.value : ~0u, i.pc}; + } else if (i.op < 8 && base.type == Symbol::Type::table) + v = {Symbol::Type::descriptor, base.value, (i.b & 0xfffff) + 4 * j}; + set(i.dst + j, v); + } + } else if (i.name == "s_mov_b32" || i.name == "s_mov_b64") { + auto v = source(i, i.src[0], s); + Symbol high = i.src[0] < 127 ? s[i.src[0] + 1] + : Symbol{Symbol::Type::constant, (i.src[0] >= 193 && i.src[0] <= 208) ? ~0u : 0u}; + set(i.dst, v); + if (i.name == "s_mov_b64") + set(i.dst + 1, high); + } else if (i.name == "s_and_b32" || i.name == "s_lshl_b32") { + const auto a = source(i, i.src[0], s), b = source(i, i.src[1], s); + Symbol out{}; + if (i.name == "s_and_b32" && (a.type == Symbol::Type::constant || b.type == Symbol::Type::constant)) + out = {Symbol::Type::masked, a.type == Symbol::Type::constant ? a.value : b.value}; + if (i.name == "s_lshl_b32" && b.type == Symbol::Type::constant && a.numeric()) { + const Word mask = a.type == Symbol::Type::masked ? a.value : ~0u; + out = {Symbol::Type::masked, mask << (b.value & 31)}; + } + if (a.type == Symbol::Type::constant && b.type == Symbol::Type::constant) + out = {Symbol::Type::constant,i.name=="s_and_b32" ? a.value & b.value : a.value << (b.value & 31)}; + set(i.dst, out); + } else if (!graphics && i.name == "s_bfm_b64") { + auto a = source(i, i.src[0], s), b = source(i, i.src[1], s); + Symbol lo{}, hi{}; + if (a.type == Symbol::Type::constant && b.type == a.type) { + const auto mask = ((uint64_t{1} << (a.value & 63)) - 1) << (b.value & 63); + lo = {a.type, Word(mask)}; + hi = {a.type, Word(mask >> 32)}; + } + set(i.dst, lo); + set(i.dst + 1, hi); + } else if (i.name == "s_bfm_b32") { + auto a = source(i, i.src[0], s), b = source(i, i.src[1], s); + Symbol v{}; + if (a.type == Symbol::Type::constant && b.type == a.type) + v = {a.type, ((1u << (a.value & 31)) - 1u) << (b.value & 31)}; + set(i.dst, v); + } else if (i.name == "s_movk_i32") { + set(i.dst, {Symbol::Type::constant, Word(int16_t(i.a))}); + } else if (i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2 || i.enc == Encoding::Vopc || + i.name == "s_mulk_i32" || i.name == "s_addk_i32" || i.name == "v_readfirstlane_b32" || + i.name == "v_readlane_b32") + { + set(i.dst, {}); + if ((wave64 && i.enc == Encoding::Vopc) || ((i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2) && + i.name.size() >= 4 && i.name.substr(i.name.size() - 4) == "_b64") || i.name == "s_bitreplicate_b64_b32") + set(i.dst + 1, {}); + } + return s; +} +struct Program { + bool graphics_wave64 = false; + std::vector code; + std::map at; + std::vector before; + std::vector reached; +}; +// Recognize slot-zero vertex-buffer loads as a group. Other scalar table +// loads interleaved by the scheduler stay in the normal instruction stream. +std::map fixed_vertex_loads(const string &code) { + std::map result; + unsigned pc = 0; + while (pc + 12 <= code.size()) { + const Word a = word(code, pc); + if ((a & 0xff80ffffu) == 0xbe800400u) break; + const auto i = decode(code, pc, true, true); + if (!(i.name == "v_nop" || i.name == "s_nop" || i.name == "s_setprio" || + i.name == "s_inst_prefetch" || i.name == "s_clause" || + ((i.name == "s_mov_b32" || i.enc == Encoding::Smem) && i.dst >= 3 && i.dst < 106))) + return {}; + pc = i.next; + } + if (pc + 12 > code.size()) return {}; + const unsigned ptr = (word(code, pc) >> 16) & 127; + if (ptr < 4 || ptr > 104 || (ptr & 1) || word(code,pc+4) != (0x9380ff00u | ((ptr+1)<<16) | (ptr+1)) || + word(code,pc+8) != 0x80000u) return {}; + auto setup = [&](unsigned bytes, unsigned dst, unsigned count) { + Inst i{}; + i.pc = pc; i.next = pc + bytes; i.enc = Encoding::FixedSetup; i.name = "fixed_vertex_setup"; + i.dst = dst; i.op = count; result.emplace(pc,i); pc = i.next; + }; + setup(4, ptr, 2); + setup(8, ptr + 1, 1); + unsigned desc = UINT_MAX; + while (pc + 8 <= code.size()) { + Word a = word(code,pc), b = word(code,pc+4); + if ((a & 0xffff0000u) == 0xbfa10000u) { pc += 4; continue; } + if ((a & 0xffffe000u) != 0xf4080000u) return {}; + const unsigned dst = (a >> 6) & 127, base = (a & 63) * 2; + if (base == ptr && b == 0xfa000000u && !(dst & 3) && dst <= 100) { + desc = dst; + setup(8, dst, 4); + break; + } + if (base == ptr || (b >> 25) != 125 || (dst < ptr + 2 && ptr < dst + 4) || dst < 3) + return {}; + pc += 8; + } + if (desc == UINT_MAX || pc + 8 > code.size() || word(code,pc) != 0x4a000002u || + word(code,pc+4) != 0xbf8cc07fu) return {}; + setup(4, 256, 1); // v0 is the adjusted fetch index, consumed by the IA. + pc += 4; + if (pc + 4 <= code.size() && (word(code,pc) & 0xffff0000u) == 0xbfa10000u) pc += 4; + bool found = false, overwrote_index = false; + while (pc + 8 <= code.size()) { + const Word a = word(code,pc), b = word(code,pc+4); + const Word form = a & ~4095u; + if (form != 0xe0342000u && form != 0xe03c2000u && form != 0xe9c32000u) break; + if (overwrote_index || (b & 0xffff00ffu) != (0x80000000u | ((desc / 4) << 16))) return {}; + Inst i{}; + i.pc = pc; i.next = pc + 8; i.enc = Encoding::FixedFetch; i.name = "fixed_vertex_fetch"; + i.dst = 256 + ((b >> 8) & 255); + i.op = form == 0xe0342000u ? 2 : form == 0xe03c2000u ? 3 : 4; + i.literal = a & 4095u; + if (i.literal % 4 || i.literal >= 2048 || i.dst+i.op > 512) return {}; + result.emplace(pc, i); + found = true; overwrote_index = i.dst == 256; pc += 8; + } + return found ? result : std::map{}; +} +Program parse(const string &code, unsigned entry, const State &initial, bool graph, bool graphics=false, bool wave64=false, bool fixed_vertex=false, + bool heap_window=false) { + Program p; + p.graphics_wave64 = graphics && wave64; + if ((entry & 3) || entry >= code.size() || code.size() > 1u << 20) + refuse(entry, "invalid entry"); + if (graph) { + const auto fixed = fixed_vertex ? fixed_vertex_loads(code) : std::map{}; + std::map instructions; + std::deque pending{entry}; + while (!pending.empty()) { + unsigned pc = pending.front(); + pending.pop_front(); + auto next = instructions.lower_bound(pc); + if (next != instructions.end() && next->first == pc) continue; + if (pc >= code.size() || (next != instructions.begin() && std::prev(next)->second.next > pc)) + refuse(pc, "branch outside code or into an instruction"); + const auto fetch = fixed.find(pc); + auto instruction = fetch != fixed.end() ? fetch->second : decode(code, pc,true,graphics); + if (next != instructions.end() && instruction.next > next->first) + refuse(pc, "overlapping instruction boundaries"); + instructions.emplace_hint(next, pc, instruction); + if (instruction.branch()) pending.push_back(instruction.target()); + if (instruction.name != "s_endpgm" && !(instruction.branch() && instruction.op == 2)) + pending.push_back(instruction.next); + } + for (const auto &[pc, instruction] : instructions) { + p.at.emplace(pc, p.code.size()); + p.code.push_back(instruction); + } + } else { + for (unsigned pc = entry;;) { + auto i = decode(code, pc); + p.at.emplace(pc, p.code.size()); + p.code.push_back(i); + if (i.name == "s_endpgm") break; + pc = i.next; + } + } + // Include the loop's entry and all branch joins when proving descriptor provenance. + p.before.resize(p.code.size()); + p.reached.resize(p.code.size()); + const size_t start = p.at.at(entry); + p.before[start] = initial; + p.reached[start] = true; + std::deque work{start}; + while (!work.empty()) { + auto k = work.front(); + work.pop_front(); + auto &i = p.code[k]; + auto after = transfer(i, p.before[k], wave64, graphics, heap_window); + auto merge = [&](size_t t) { + bool changed = !p.reached[t]; + auto &in = p.before[t]; + if (changed) { + in = after; + p.reached[t] = true; + } else + for (unsigned n = 0; n < in.size(); ++n) + if (!(in[n] == after[n])) { + Symbol merged{}; + if (!in[n].numeric() || !after[n].numeric()) + merged.type = Symbol::Type::unbound; + if (!(in[n] == merged)) { + in[n] = merged; + changed = true; + } + } + if (changed) + work.push_back(t); + }; + if (i.branch()) { + auto t = p.at.find(i.target()); + if (t == p.at.end()) + refuse(i.pc, "invalid branch target"); + merge(t->second); + } + if (i.name != "s_endpgm" && !(i.branch() && i.op == 2)) + merge(p.at.at(i.next)); + } + return p; +} +string reg(unsigned n) { return n >= 256 ? "v" + to_string(n - 256) : "s" + to_string(n); } +string operand(const Inst &i, unsigned n) { + if ((n <= 105) || n == 106 || n == 126 || n >= 256) + return reg(n); + if (n >= 128 && n <= 208) + return hexword(n <= 192 ? n - 128 : 192u - n); + if (n == 253) + return "uint(scc)"; + if (n == 255) + return hexword(i.literal); + constexpr Word f[] = {0x3f000000, 0xbf000000, 0x3f800000, 0xbf800000, 0x40000000, + 0xc0000000, 0x40800000, 0xc0800000, 0x3e22f983}; + if (n >= 240 && n <= 248) + return hexword(f[n - 240]); + refuse(i.pc, "unsupported operand " + to_string(n)); +} +enum class AluType { Bits, Float, ToFloat }; +struct AluRule { + unsigned arity; + AluType type; + Name expression; +}; +#include "gfx1013_compute_alu.inl" + +struct Emit { + NativeComputeShader result{}; + const Program &program; + const D3D12_ROOT_SIGNATURE_DESC1 &layout; + std::ostringstream body; + unsigned srv = 0, uav = 0, first_sampler = 0; + string binding(const Inst &i, const State &state, unsigned base, unsigned width, ComputeViewKind kind, + unsigned bytes = 0,unsigned dimension = 1) { + auto sym = state.at(base); + const bool indexed = sym.type == Symbol::Type::indexed_descriptor; + if ((!indexed && sym.type != Symbol::Type::descriptor) || base + width > state.size()) + refuse(i.pc, "unproven resource descriptor s" + to_string(base)); + const bool byte_window = kind == ComputeViewKind::byte_window_srv || + (kind == ComputeViewKind::raw_buffer_uav && width == 4 && i.name == "buffer_store_raw" && + state[base + 1].type == Symbol::Type::zero_stride_word); + for (unsigned j = 1; j < width; ++j) { + Symbol expected = sym; + if (byte_window) { + constexpr Symbol::Type fields[] = {Symbol::Type::descriptor, Symbol::Type::zero_stride_word, + Symbol::Type::byte_count, Symbol::Type::byte_oob}; + expected.type = fields[j]; + } else expected.offset += j * 4; + if (!(state[base + j] == expected)) + refuse(i.pc, "non-contiguous resource descriptor"); + } + if (sym.offset % 32) + refuse(i.pc, "unaligned descriptor table entry"); + auto &list = result.bindings; + if (sym.value == compute_resource_heap) + refuse(i.pc, "whole-heap buffer access needs a matching descriptor at the GPU-selected index"); + if (indexed) { + if (width != 4 || compute_uav(kind) || (sym.index_mask & 31)) + refuse(i.pc, "indexed descriptor requires a bounded 32-byte-aligned SRV offset"); + const unsigned first = sym.offset / 32, count = 1 + sym.index_mask / 32; + if (sym.value >= layout.NumParameters || layout.pParameters[sym.value].ParameterType != D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) + refuse(i.pc, "missing indexed descriptor table range"); + const auto &table = layout.pParameters[sym.value].DescriptorTable; + const uint64_t end = uint64_t(first) + count; + if (count > D3D12_MAX_SHADER_VISIBLE_DESCRIPTOR_HEAP_SIZE_TIER_1 || + end > (uint64_t(UINT_MAX) + 1) / 32) + refuse(i.pc, "indexed SRV span exceeds its declared root range"); + std::vector> covered; + uint64_t next = 0; + for (unsigned j = 0; j < table.NumDescriptorRanges; ++j) { + const auto &range = table.pDescriptorRanges[j]; + uint64_t start = range.OffsetInDescriptorsFromTableStart == D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND + ? next : range.OffsetInDescriptorsFromTableStart; + next = start + range.NumDescriptors; + if (start >= end || next <= first) continue; + if (range.RangeType != D3D12_DESCRIPTOR_RANGE_TYPE_SRV) + refuse(i.pc, "indexed SRV span overlaps a non-SRV root range"); + covered.emplace_back((std::max)(uint64_t(first), start), (std::min)(end, next)); + } + // These are physical slots relative to the bound table. Adjacent + // SRV ranges may name unrelated guest registers or register spaces. + std::sort(covered.begin(), covered.end()); + uint64_t cursor = first; + for (const auto &[lo, hi] : covered) { + if (lo > cursor) break; + cursor = (std::max)(cursor, hi); + } + if (cursor != end) + refuse(i.pc, "indexed SRV span exceeds its declared root range"); + auto span = std::find_if(list.begin(), list.end(), [&](const auto &b) { + return b.kind == kind && b.root_parameter == sym.value && b.byte_offset == sym.offset && + b.array_count == count && !b.array_position; + }); + unsigned first_reg = srv; + if (span == list.end()) { + for (unsigned j = 0; j < count; ++j) + list.push_back({kind, sym.value, sym.offset + j * 32, srv++, bytes, count, j}); + } else { + first_reg = span->shader_register; + for (unsigned j = 0; j < count; ++j) + span[j].required_bytes = (std::max)(span[j].required_bytes, bytes); + } + return "r"+to_string(first_reg)+(count==1 ? "" : "[NonUniformResourceIndex("+reg(base)+")]"); + } + auto it = std::find_if(list.begin(), list.end(), [&](const auto &b) { + if (compute_buffer_uav(kind) && b.kind == kind && b.root_parameter == sym.value && + b.byte_offset == sym.offset && kind != ComputeViewKind::raw_buffer_uav && b.required_bytes != bytes) + refuse(i.pc, "incompatible formatted store widths on one slot"); + return b.array_count == 1 && b.image_dimension==dimension && b.kind == kind && b.root_parameter == sym.value && b.byte_offset == sym.offset; + }); + bool write = compute_uav(kind); + if (it == list.end()) { + list.push_back({kind, sym.value, sym.offset, write ? uav++ : srv++, bytes,1,0,dimension}); + it = std::prev(list.end()); + } + it->required_bytes = (std::max)(it->required_bytes, bytes); + return (write ? "w" : "r") + to_string(it->shader_register); + } + unsigned sampler_index(const Inst &i, const State &state, bool lod, bool gather_base_level = false, + bool implicit_sample = false, bool comparison = false) { + const unsigned base = ((i.b >> 21) & 31) * 4; + ComputeSampler sampler{{}, lod, comparison}; + for (unsigned j = 0; j < 4; ++j) { + const auto &s = state.at(base + j); + if (s.type != Symbol::Type::constant) + refuse(i.pc, "nonconstant sampler"); + sampler.words[j] = s.value; + } + if (comparison) { + // Field constraints from pixel_aot.comparison_sampler_state. The + // native static sampler also preserves the mip filter and LOD limits. + auto &[address, limits, filter, border] = sampler.words; + const unsigned mag = (filter >> 20) & 3, min = (filter >> 22) & 3, mip = (filter >> 26) & 3; + if ((address & 63) != 0x12 || (address & ((7u << 9) | (1u << 15) | (3u << 19) | (3u << 29))) || + mag != min || mag > 1 || mip == 3 || ((address >> 27) & 1) != (mag == 0) || + (filter & 0xfffff) || (filter >> 28 & (implicit_sample ? 15 : 8)) || (border & 0x3ffff000)) + refuse(i.pc, "unsupported comparison sampler fields"); + if (limits & 0xfff) + refuse(i.pc, "comparison sampler requires minimum LOD zero"); + if (!mip) + limits &= ~0x00fff000u; + } else if (implicit_sample) { + // The static sampler carries MIN_LOD and MAX_LOD. Only encode a + // gradient-derived LOD when its mip filter and bias are representable. + unsigned mip = (sampler.words[2] >> 26) & 3; + if ((sampler.words[2] & 0xfffff) || (mip != 1 && mip != 2) || + (sampler.words[1] & 0xfff) > ((sampler.words[1] >> 12) & 0xfff)) + refuse(i.pc, "implicit sample with unsupported sampler LOD fields"); + } + if (gather_base_level) { + // DXIL textureGather has no explicit LOD operand. A dedicated static + // sampler fixes the gather footprint to the first mip of the SRV. + if (sampler.words[1] & 0xfffu) + refuse(i.pc, "base-level gather with a nonzero minimum LOD"); + sampler.words[1] &= ~0x00fff000u; + sampler.explicit_lod = true; + } + auto &all = result.samplers; + auto it = std::find_if(all.begin(), all.end(), + [&](const auto &s) { return s.words == sampler.words && s.explicit_lod == sampler.explicit_lod && + s.comparison == sampler.comparison; }); + if (it == all.end()) { + all.push_back(sampler); + it = std::prev(all.end()); + } + return first_sampler+static_cast(it - all.begin()); + } + void image(const Inst &i, const State &state) { + unsigned mask = (i.a >> 8) & 15, base = ((i.b >> 16) & 31) * 4, addr = i.b & 255; + const bool half_store = i.op == 8 && (i.b & 0x80000000u); + if (!mask || (i.a & 0x3e0c0u) || (i.b & 0x3e000000u)) + refuse(i.pc, "unsupported image flags"); + bool store = i.op == 8, lod = i.op == 39, gather = i.op == 71; + if (i.op != 0 && !store && !lod && !gather) + refuse(i.pc, "unsupported image opcode"); + auto tex = binding(i, state, base, 8, half_store ? ComputeViewKind::half_scalar_uav : + store ? ComputeViewKind::texture_uav : ComputeViewKind::texture_srv); + string x = reg(256 + addr), y = reg(256 + (((i.a >> 1) & 3) ? (i.image_address_words[0] & 255) : addr + 1)); + if (i.b & 0x40000000u) { + if (lod || gather || (store && !half_store) || (half_store && ((i.a >> 1) & 3))) + refuse(i.pc, "packed sample address"); + y = "(" + x + ">>16)"; + x = "(" + x + "&65535u)"; + } + if (store) { + if (half_store) { + body << "if(active) " << tex << "[uint2(" << x << "," << y << ")]=f16tof32(" + << reg(256+i.dst) << "&65535u);\n"; + return; + } + if (mask != 15 || i.dst > 252) + refuse(i.pc, "unsupported image store mask"); + body << "if(active) " << tex << "[uint2(" << x << "," << y << ")]=asfloat(uint4("; + for (unsigned k = 0; k < 4; ++k) + body << (k ? "," : "") << reg(256 + i.dst + k); + body << "));\n"; + return; + } + if (lod || gather) { + if (gather && mask != 1) + refuse(i.pc, "unsupported gather channel"); + body << "t=" << tex << (lod ? ".SampleLevel(" : ".GatherRed(") << "q" << sampler_index(i, state, lod) + << ",float2(asfloat(" << x << "),asfloat(" << y << "))" << (lod ? ",0);\n" : ");\n"); + } else + body << "t=" << tex << ".Load(int3(" << x << "," << y << ",0));\n"; + unsigned dst = i.dst; + for (unsigned k = 0; k < 4; ++k) + if (gather || ((mask >> k) & 1)) { + if (dst >= 256) + refuse(i.pc, "image destination overflow"); + body << "if(active) " << reg(256 + dst++) << "=asuint(t." << "xyzw"[k] << ");\n"; + } + } + void require_numeric(const Inst &i, unsigned reg) const { + if (reg <= 105 && !program.before[program.at.at(i.pc)][reg].numeric()) + refuse(i.pc, "unbound numeric SGPR s" + to_string(reg)); + } + void scalar(const Inst &i) { + auto n = i.name; + string a = operand(i, i.src[0]), b = operand(i, i.src[1]), d = reg(i.dst), e; + if (n == "s_mov_b32" || n == "s_mov_b64") { + if (n == "s_mov_b64") { + if (i.dst == 126) + require_numeric(i, i.src[0]); + if ((i.dst & 1) || i.dst + 1 >= 128 || (i.src[0] < 128 && (i.src[0] & 1))) + refuse(i.pc, "scalar pair overflow"); + body << reg(i.dst + 1) << "=" + << (i.src[0] < 105 ? reg(i.src[0] + 1) + : i.src[0] >= 193 && i.src[0] <= 208 ? "0xffffffffu" + : "0u") + << ";\n"; + } + if (i.dst == 106 || i.dst == 126) + require_numeric(i, i.src[0]); + body << d << "=" << a << ";\n"; + if (i.dst == 126) + body << "active=(s126&laneBit)!=0;\n"; + return; + } + if (n == "s_bfe_u32" && i.src[0] <= 105) { + const auto &state = program.before[program.at.at(i.pc)]; + const auto word = state[i.src[0]]; + const auto bits = source(i, i.src[1], state); + if (word.type == Symbol::Type::indexed_descriptor && word.value == compute_resource_heap && + (word.offset & 31) == 4 && bits.type == Symbol::Type::constant && bits.value == 0xe0010) { + auto &bindings = result.bindings; + auto it = std::find_if(bindings.begin(), bindings.end(), [](const auto &b) { + return b.kind == ComputeViewKind::heap_stride_srv; + }); + if (it == bindings.end()) { + bindings.push_back({ComputeViewKind::heap_stride_srv, compute_resource_heap, 0, srv++, 4}); + it = std::prev(bindings.end()); + } + body << d << "=r" << it->shader_register << ".Load((" << a << "+" + << word.offset / 32 << "u)*4u)&16383u; scc=(" << d << "!=0);\n"; + return; + } + } + if (i.enc == Encoding::Sopk && n != "s_movk_i32") + require_numeric(i, i.dst); + if (i.enc != Encoding::Sopk) + require_numeric(i, i.src[0]); + if (i.enc == Encoding::Sop2 || i.enc == Encoding::Sopc) + require_numeric(i, i.src[1]); + if (n == "s_movk_i32") { + body << d << "=" << hexword(Word(int16_t(i.a))) << ";\n"; + return; + } + if (n == "s_and_saveexec_b32") { + body << "{uint old=s126;s126&=" << a << ";" << d << "=old;active=(s126&laneBit)!=0;scc=s126!=0;}\n"; + return; + } + if (n == "s_andn2_wrexec_b32") { + body << "s126=" << a << "&~s126;" << d << "=s126;active=(s126&laneBit)!=0;scc=s126!=0;\n"; + return; + } + if (n == "s_cmp_eq_i32" || n == "s_cmp_eq_u32") + e = a + "==" + b; + else if (n == "s_cmp_lt_u32") + e = a + "<" + b; + else if (n == "s_cmp_lg_i32" || n == "s_cmp_lg_u32") + e = a + "!=" + b; + else if (n == "s_cmp_lt_i32") + e = "asint(" + a + ")>(" + b + "&31))&1)!=0"; + if (!e.empty()) { + body << "scc=" << e << ";\n"; + return; + } + if (n == "s_mulk_i32") { + body << d << "*=" << hexword(Word(int16_t(i.a))) << ";\n"; + return; + } + if (n == "s_cmpk_lg_i32") { + body << "scc=" << d << "!=" << hexword(Word(int16_t(i.a))) << ";\n"; + return; + } + if (n == "s_min_u32" || n == "s_max_u32") { + body << "{uint lhs=" << a << ",rhs=" << b << ";scc=lhs" << (n == "s_min_u32" ? "<" : ">") << "rhs;" << d + << "=scc?lhs:rhs;}\n"; + return; + } + if (n == "s_sub_u32") { + body << "{uint lhs=" << a << ",rhs=" << b << ";scc=lhs>32);\n"; + return; + } + if (n == "s_mul_i32") { + body << d << "=" << a << "*" << b << ";\n"; + return; + } + if (n == "s_add_u32") { + body << "{uint lhs=" << a << ", sum=lhs+" << b << ";scc=sum>(" + b + "&31)"; + else if (n == "s_lshl_b32") + e = a + "<<(" + b + "&31)"; + else if (n == "s_bfe_u32") + e = "extractBits(" + a + "," + b + ",(" + b + ">>16)&127u)"; + else if (n == "s_bfm_b32") + e = "((1u<<(" + a + "&31))-1u)<<(" + b + "&31)"; + else if (n == "s_absdiff_i32") + e = "uint(abs(asint(" + a + ")-asint(" + b + ")))"; + else if (n == "s_cselect_b32") { + body << d << "=scc?" << a << ":" << b << ";\n"; + return; + } else if (i.enc == Encoding::Sop2 && i.op >= 0x2e && i.op <= 0x31) { + const unsigned shift = i.op - 0x2d; + body << "scc=(" << a << ">>" << (32 - shift) << ")!=0||((" << a << "<<" << shift << ")+" << b << ")<" << b + << ";\n" + << d << "=(" << a << "<<" << shift << ")+" << b << ";\n"; + return; + } else + refuse(i.pc, string(n)); + body << d << "=" << e << ";scc=" << d << "!=0;\n"; + } + void vector(const Inst &i) { + auto n = i.name; + if ((n == "v_readfirstlane_b32" || n == "v_readlane_b32") && i.dst >= 106) + refuse(i.pc, "invalid scalar lane read destination"); + if (n == "v_readlane_b32") + refuse(i.pc, "unsupported HLSL instruction v_readlane_b32"); + auto selected = [&](unsigned j) { + require_numeric(i, i.src[j]); + auto s = operand(i, i.src[j]); + if (i.subword && j < 2 && i.src_select[j] < 6) { + unsigned sel = i.src_select[j]; + unsigned shift = sel < 4 ? sel * 8 : (sel - 4) * 16; + s = "((" + s + ">>" + to_string(shift) + ")&" + to_string(sel < 4 ? 255 : 65535) + "u)"; + if (i.src_sext[j]) { + const auto sign = sel < 4 ? "128u" : "32768u"; + s = "((" + s + "^" + sign + ")-" + sign + ")"; + } + } + return s; + }; + auto val = [&](unsigned j, bool fp) { + auto s = selected(j); + if (fp) { + s = "asfloat(" + s + ")"; + if ((i.abs >> j) & 1) + s = "abs(" + s + ")"; + if ((i.neg >> j) & 1) + s = "(-" + s + ")"; + } else if (((i.abs | i.neg) >> j) & 1) { + if (n != "v_fma_mix_f32") + refuse(i.pc, "unexpected integer modifier"); + } + return s; + }; + auto d = reg(i.dst); + if (n == "v_cos_f32" || n == "v_cvt_f32_f16") { + if (i.wide) + refuse(i.pc, "unsupported wide conversion or cosine modifiers"); + if (n == "v_cvt_f32_f16") + body << "if(active) " << d << "=asuint(f16tof32(" << selected(0) << "&65535u));\n"; + else { + body << "if(active){float turns=" << val(0,true) + << ";float phase=turns-round(turns);" << d + << "=asuint(abs(phase)==0.25f?0.0f:cos(phase*6.283185307f));}\n"; + } + return; + } + if (n == "v_swap_b32") { + if (i.wide || i.src[0] < 256 || i.src[0] > 511) + refuse(i.pc, "swap requires two VGPRs in a VOP1 encoding"); + const auto src = reg(i.src[0]); + body << "if(active){uint old=" << d << ";" << d << "=" << src << ";" << src << "=old;}\n"; + return; + } + if (n == "v_readfirstlane_b32") { + if (i.abs || i.neg || i.scale || i.clamp) + refuse(i.pc, "readfirstlane modifiers"); + body << d << "=WaveReadLaneAt(" << val(0, false) << ",s126==0?0u:uint(firstbitlow(s126)));\n"; + return; + } + if (i.enc == Encoding::Vopc) { + bool fp = n.find("f32") != n.npos; + auto a = val(0, fp), b = val(1, fp); + string pred; + if (!fp && n.find("_u32") == n.npos) { + a = "asint(" + a + ")"; + b = "asint(" + b + ")"; + } + if (n == "v_cmp_class_f32") { + // Apply floating-point abs/neg to the raw sign bit, including for signed zero and NaNs. + auto bits = selected(0); + if (i.abs & 1) bits = "(" + bits + "&0x7fffffffu)"; + if (i.neg & 1) bits = "(" + bits + "^0x80000000u)"; + if ((i.abs | i.neg) & 2) refuse(i.pc, "unexpected class mask modifier"); + pred = "(fpClass(" + bits + ")&" + selected(1) + ")!=0u"; + } + else if (n.find("_nle_") != n.npos) + pred = "!(" + a + "<=" + b + ")"; + else { + string op = n.find("_lt_") != n.npos ? "<" + : n.find("_le_") != n.npos ? "<=" + : n.find("_gt_") != n.npos ? ">" + : n.find("_ge_") != n.npos ? ">=" + : n.find("_eq_") != n.npos ? "==" + : "!="; + pred = "(" + a + op + b + ")"; + } + body << d << "=WaveActiveBallot((uint(active)&uint(" << pred << "))!=0u).x;\n"; + if (i.dst == 126) + body << "active=(s126&laneBit)!=0;\n"; + return; + } + if (n == "v_cndmask_b32") { + require_numeric(i, i.src[2]); + auto a = val(0, true), b = val(1, true); + body << "if(active) " << d << "=((" << operand(i, i.src[2]) << "&laneBit)!=0)?asuint(" << b << "):asuint(" + << a << ");\n"; + return; + } + if (n == "v_lshrrev_b64") { + auto src = i.src[1]; + if (src == 128 && i.dst < 511) { + body << "if(active){" << d << "=0;" << reg(i.dst + 1) << "=0;}\n"; + return; + } + if (src < 256 || src >= 511 || i.dst >= 511) + refuse(i.pc, "invalid shift pair"); + body << "if(active){uint64_t w=(uint64_t(" << reg(src + 1) << ")<<32)|" << reg(src) << "; w>>=(" + << val(0, false) << "&63u);" << d << "=uint(w);" << reg(i.dst + 1) << "=uint(w>>32);}\n"; + return; + } + if (n == "v_fma_mix_f32") { + std::array args; + for (unsigned j = 0; j < 3; ++j) { + require_numeric(i, i.src[j]); + auto a = operand(i, i.src[j]); + bool half = j == 2 ? (i.a & 0x4000) != 0 : ((i.b >> (27 + j)) & 1) != 0; + args[j] = half ? "f16tof32((" + a + ">>" + to_string(((i.a >> (11 + j)) & 1) * 16) + ")&65535u)" + : "asfloat(" + a + ")"; + if ((i.abs >> j) & 1) + args[j] = "abs(" + args[j] + ")"; + if ((i.neg >> j) & 1) + args[j] = "-" + args[j]; + } + body << "if(active) " << d << "=asuint(mad(" << args[0] << "," << args[1] << "," << args[2] << "));\n"; + return; + } + auto it = alu_rules.find(n); + if (it == alu_rules.end()) + refuse(i.pc, string(n)); + const auto &rule = it->second; + bool fp = rule.type == AluType::Float; + std::array args; + for (unsigned j = 0; j < rule.arity; ++j) { + if (j == 2 && n == "v_fmac_f32") + args[j] = "asfloat(" + d + ")"; + else if ((n == "v_fmamk_f32" && j == 1) || (n == "v_fmaak_f32" && j == 2)) + args[j] = "asfloat(" + hexword(i.literal) + ")"; + else + args[j] = val(n == "v_fmamk_f32" && j == 2 ? 1 : j, fp); + } + string e; + for (size_t k = 0; k < rule.expression.size(); ++k) { + if (rule.expression[k] == '{') { + e += args[rule.expression[k + 1] - '0']; + k += 2; + } else + e += rule.expression[k]; + } + if (i.scale) + e = "(" + e + ")*" + (i.scale == 1 ? "2.0" : i.scale == 2 ? "4.0" : "0.5"); + if (i.clamp) + e = "saturate(" + e + ")"; + if (i.dst_select < 6) { + const unsigned width = i.dst_select < 4 ? 8 : 16; + const unsigned shift = width == 8 ? i.dst_select * 8 : (i.dst_select - 4) * 16; + const Word mask = (1u << width) - 1u; + e = "((" + e + ")&" + hexword(mask) + ")"; + if (i.dst_unused == 1) { + const auto sign = hexword(1u << (width - 1)); + e = "((" + e + "^" + sign + ")-" + sign + ")"; + } + e = "(" + e + "<<" + to_string(shift) + ")"; + if (i.dst_unused == 2) + e += "|(" + d + "&" + hexword(~(mask << shift)) + ")"; + } + body << "if(active) " << d << "=" << (rule.type != AluType::Bits ? "asuint(" + e + ")" : e) << ";\n"; + } + void instruction(size_t index) { + const auto &i = program.code[index]; + const auto &s = program.before[index]; + if (i.enc == Encoding::Mubuf) { + if (i.name == "buffer_store_format" || i.name == "buffer_store_raw") { + const bool raw = i.name == "buffer_store_raw"; + const bool half = (i.op & 0x80) != 0; + constexpr unsigned raw_widths[]{1, 2, 4, 3}; + const unsigned count = raw ? raw_widths[i.op & 3] : (i.op & 3) + 1; + if (i.dst + (half ? (count + 1) / 2 : count) > 256) + refuse(i.pc, "buffer store data register overflow"); + const auto kind = raw ? ComputeViewKind::raw_buffer_uav : + half ? ComputeViewKind::half_buffer_uav : ComputeViewKind::typed_buffer_uav; + auto view = binding(i, s, ((i.b >> 16) & 31) * 4, 4, kind, raw ? 4 : count * (half ? 2 : 4)); + auto address = reg(256 + (i.b & 255)); + if (raw) { + const unsigned scalar = i.b >> 24; + if (scalar > 105 && (scalar < 128 || scalar > 192)) + refuse(i.pc, "unsupported raw store scalar offset"); + require_numeric(i, scalar); + address = "((" + ((i.a & 0x1000) ? address : "0u") + "+" + operand(i, scalar) + + "+" + to_string(i.a & 4095) + "u)&~3u)"; + } + const string suffix = count == 1 ? "" : to_string(count); + string data; + for (unsigned j = 0; j < count; ++j) { + if (j) data += ","; + auto src = reg(256 + i.dst + (half ? j / 2 : j)); + data += half ? "f16tof32((" + src + ">>" + to_string((j%2)*16) + ")&65535u)" : src; + } + if (count > 1) data = (half ? "float" : "uint") + suffix + "(" + data + ")"; + body << "if(active) " << view; + if (raw) body << ".Store" << suffix << "(" << address << "," << data << ");\n"; + else body << "[" << address << "]=" << data << ";\n"; + return; + } + if (i.name == "buffer_load_dword") { + constexpr unsigned widths[] = {1, 2, 4, 3}; + const unsigned count = widths[i.op - 0x0c]; + if (i.dst + count > 256) + refuse(i.pc, "raw load destination overflow"); + auto r = binding(i, s, ((i.b >> 16) & 31) * 4, 4, ComputeViewKind::raw_vector_srv, 4); + // Address generation precedes every writeback, including when vaddr is a destination. + body << "if(active){uint address=(" << reg(256 + (i.b & 255)) << "+" << (i.a & 4095) + << "u)&~3u;"; + const string suffix = count == 1 ? "" : to_string(count); + body << "uint" << suffix << " loaded=" << r << ".Load" << suffix << "(address);"; + for (unsigned k = 0; k < count; ++k) { + body << reg(256 + i.dst + k) << "=loaded"; + if (count > 1) body << "." << "xyzw"[k]; + body << ";"; + } + body << "}\n"; + return; + } + const auto buffer = + binding(i, s, ((i.b >> 16) & 31) * 4, 4, ComputeViewKind::typed_buffer_srv, 4 * (1 + i.op)); + if (i.dst + i.op >= 256) + refuse(i.pc, "formatted load destination overflow"); + body << "if(active){uint4 loaded=" << buffer << ".Load(" << reg(256 + (i.b & 255)) << ");"; + for (unsigned j = 0; j <= i.op; ++j) + body << reg(256 + i.dst + j) << "=loaded[" << j << "];"; + body << "}\n"; + return; + } + if (i.enc == Encoding::Image) { + image(i, s); + return; + } + if (i.enc == Encoding::Smem) { + if (i.op < 8) { + if (s.at(i.src[0]).type != Symbol::Type::table) + refuse(i.pc, "unknown scalar table base"); + if (s.at(i.src[0]).value == compute_resource_heap && i.b >> 25 == 125) + refuse(i.pc, "unsupported immediate whole-heap descriptor"); + if (i.b >> 25 != 125) { + const auto high = s.at(i.src[0]+1); + if (high.type != Symbol::Type::constant || high.value || ((i.b & 0xfffff) % 32)) + refuse(i.pc,"unproven indexed table address"); + require_numeric(i,i.b>>25); + if (s.at(i.src[0]).value == compute_resource_heap) { + const auto offset = s.at(i.b >> 25); + if ((offset.type != Symbol::Type::masked && offset.type != Symbol::Type::constant) || + (offset.value & 31)) + refuse(i.pc, "whole-heap descriptor offset is not proven 32-byte aligned"); + } + body << "{uint slot=" << reg(i.b>>25) << ">>5;"; + for (unsigned j=0;j<4;++j) body << reg(i.dst+j) << "=slot;"; + body << "}\n"; + } + return; + } + unsigned off = i.b & 0xfffff, count = memory_count(i); + const unsigned offset_reg = i.b >> 25; + const bool dynamic = offset_reg != 125; + if (dynamic) + require_numeric(i, offset_reg); + auto r = binding(i, s, i.src[0], 4, ComputeViewKind::buffer_srv, dynamic ? 4 : off + count * 4); + // The offset can alias any destination SGPR. Snapshot it before committing the first word. + if (dynamic) + body << "{uint address=(" << reg(offset_reg) << "+" << off << "u)&~3u;\n"; + for (unsigned j = 0; j < count; ++j) + body << reg(i.dst + j) << "=" << r << ".Load(" << (dynamic ? "address+" : "") + << (dynamic ? 0 : off) + 4 * j << "u);\n"; + if (dynamic) + body << "}\n"; + return; + } + if (i.enc == Encoding::Lds) { + std::ostringstream line; + line << "#pragma x2w_lds " << std::hex << std::setfill('0') << std::setw(8) << i.a << " " << std::setw(8) + << i.b; + body << "{uint exec=uint(active);" << expand_gfx1013_compute(line.str()) << "}\n"; + return; + } + if (i.enc == Encoding::Sopp) { + if (i.name == "s_barrier") + body << "GroupMemoryBarrierWithGroupSync();\n"; + return; + } + if (i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2 || i.enc == Encoding::Sopk || i.enc == Encoding::Sopc) + scalar(i); + else + vector(i); + } +}; +string branch_test(const Inst &i) { + if (i.op == 2) + return "true"; + if (i.op == 4) + return "!scc"; + if (i.op == 5) + return "scc"; + if (i.op == 6 || i.op == 7) + return i.op == 6 ? "s106==0" : "s106!=0"; + return i.op == 8 ? "s126==0" : "s126!=0"; +} +void lower_blocks(Emit &e) { + const auto &p = e.program; + std::set starts{p.code.front().pc}; + for (const auto &i : p.code) + if (i.branch()) { + starts.insert(i.target()); + starts.insert(i.next); + } + std::map ends; + for (const auto &i : p.code) + if (i.branch() && i.target() < i.pc) { + if (*std::prev(starts.upper_bound(i.pc)) != i.target() || i.op == 2) + refuse(i.pc, "unsupported loop shape"); + ends[i.target()] = i.pc; + } + auto &out = e.body; + out << "uint pc=" << p.code.front().pc << "u;\n"; + for (size_t k = 0; k < p.code.size(); ++k) { + auto &i = p.code[k]; + if (starts.count(i.pc)) { + out << "if(pc==" << i.pc << "u){\n"; + if (ends.count(i.pc)) + out << "[loop] do {\n"; + } + if (i.branch()) { + if (i.target() < i.pc) + out << "}while(" << branch_test(i) << "); pc=" << i.next << "u;\n"; + else + out << "pc=(" << branch_test(i) << ")?" << i.target() << "u:" << i.next << "u;\n"; + } else { + if (i.name != "v_nop") e.instruction(k); + if (starts.count(i.next)) + out << "pc=" << i.next << "u;\n"; + } + if (k + 1 == p.code.size() || starts.count(i.next)) + out << "}\n"; + } +} +#include "gfx1013_direct_compute.inl" +#include "gfx1013_direct_graphics.inl" +} // namespace +static NativeComputeShader translate_program(const ComputeRequest &request, unsigned entry, bool direct_dxil, const GuestShaderStage *stage, + HeapViewContract heap_view) { + if (entry == 36 && ((word(request.code, 0) >> 16) != 0xd580 || (word(request.code, 12) >> 16) != 0xd580 || + (word(request.code, 24) >> 16) != 0xd580 || (word(request.code, 36) >> 16) != 0xbfa0)) + refuse(entry, "unrecognized compute header"); + if(direct_dxil && entry==36){ + for(unsigned at=0;atentry-at)refuse(at,"executable instruction in capture prefix"); + at+=prefix.size; + } + } + unsigned xy = stage ? 0 : word(request.sa, 12); + unsigned z = stage ? stage->threads[2] : word(request.sa, 16) & 65535; + unsigned rsrc2 = stage ? stage->rsrc2 : word(request.sa, 24); + unsigned lds = (rsrc2 >> 15) & 511; + unsigned x = stage ? stage->threads[0] : xy & 65535; + unsigned y = stage ? stage->threads[1] : xy >> 16; + if (x > 1024 || y > 1024 || z > 64) refuse(entry, "compute dimension exceeds desktop limit"); + const uint64_t threads = uint64_t(x) * y * z; + unsigned local_axes = 1 + ((rsrc2 >> 11) & 3); + unsigned user = (rsrc2 >> 1) & 31; + if (!threads || threads > 1024 || z > 64 || local_axes > 3) + refuse(entry, "invalid compute group shape"); + if (rsrc2 & ~0xff9fbeu || lds > 64) + refuse(entry, "unsupported compute resource flags"); + if (!direct_dxil && threads > 32 && threads % 32) + refuse(entry, "partial final wave in multi-wave group"); + Microsoft::WRL::ComPtr sig; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC empty{}; + const D3D12_VERSIONED_ROOT_SIGNATURE_DESC *layout = ∅ + if ((!stage || !request.root.empty()) && (FAILED(D3D12CreateVersionedRootSignatureDeserializer(request.root.data(), request.root.size(), + IID_PPV_ARGS(&sig))) || + FAILED(sig->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &layout)) || + layout->Desc_1_1.NumParameters > 16)) + refuse(entry, "invalid root layout"); + unsigned next = 4; + State initial{}; + for (unsigned k = 0; k <= 105; ++k) + initial[k].type = Symbol::Type::unbound; + std::vector constants; + if (stage) { + std::array assigned{}; + for (const auto &input : stage->inputs) { + if (input.type == 1) { + bind_root_address(initial, input, user); + assigned[input.user_data] = assigned[input.user_data + 1] = true; + continue; + } + if (input.type != 0 && input.type != 3 && input.type != 5) continue; + unsigned at = input.user_data; + unsigned count = input.type == 0 ? input.sgpr_count : 1; + if (!count || at >= user || count > user - at || (input.type != 5 && input.root_parameter >= 16)) + refuse(entry, "invalid FSSM user-data range"); + if (input.type == 0) { + constants.push_back({input.root_parameter, at, count}); + for (unsigned j = at; j < at + count; ++j) { + if (assigned[j]) refuse(entry, "overlapping FSSM constants"); + assigned[j] = true; + initial[j] = {}; + } + } else { + Symbol table{Symbol::Type::table, input.type == 5 ? compute_resource_heap : input.root_parameter}; + if (assigned[at] && !(initial[at] == table)) refuse(entry, "ambiguous FSSM table"); + initial[at] = table; + assigned[at] = true; + } + } + } + unsigned system = user; + for (unsigned flag : {128u, 256u, 512u, 1024u}) + if (rsrc2 & flag) + initial[system++] = {}; + for (unsigned i = 0; !stage && i < layout->Desc_1_1.NumParameters; ++i) { + const auto ¶m = layout->Desc_1_1.pParameters[i]; + if (param.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) { + if (next >= user) + refuse(entry, "descriptor table exceeds user SGPRs"); + initial[next++] = {Symbol::Type::table, i}; + } else if (param.ParameterType == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS) { + unsigned count = param.Constants.Num32BitValues; + if (next > user || count > user - next) + refuse(entry, "root constants exceed user SGPRs"); + constants.push_back({i, next, count}); + for (unsigned j = 0; j < count; ++j) + initial[next + j] = {}; + next += count; + } else if (direct_dxil && (param.ParameterType == D3D12_ROOT_PARAMETER_TYPE_CBV || + param.ParameterType == D3D12_ROOT_PARAMETER_TYPE_SRV || + param.ParameterType == D3D12_ROOT_PARAMETER_TYPE_UAV)) { + // Same packed entry layout as gfx2hlsl.Stage.setup: a root address + // occupies two consecutive SGPRs, even when only later parameters are used. + if (next > user || user - next < 2) + refuse(entry, "root descriptor pair exceeds user SGPRs"); + bind_root_address(initial, {1, 0, 2, 0, static_cast(next), static_cast(i)}, user); + next += 2; + } else + refuse(entry, "root-address parameter"); + } + // In this compute ABI the two directly indexed heaps follow the user root parameters. + // Require both flags and exactly two remaining user SGPRs, as in the matched native layouts. + if (!stage && (UINT(layout->Desc_1_1.Flags) & 0xc00u) == 0xc00u && next + 2 == user) + initial[next] = {Symbol::Type::table, compute_resource_heap}; + const bool wave64 = stage && !stage->wave32; + // The byte-address rewrite of a GPU-selected heap descriptor is read only under the raw_buffer contract. + const bool heap_window = direct_dxil && heap_view == HeapViewContract::raw_buffer; + auto program = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window); + Emit emit{{}, program,layout->Desc_1_1}; + emit.result.constants = constants; + if (!lds) + for (const auto &inst : program.code) + if (inst.enc == Encoding::Lds) + refuse(inst.pc, "LDS instruction without allocation"); + if (direct_dxil) { + DirectCompute compiler{emit}; + compiler.wave64 = wave64; + compiler.heap_view = heap_view; + compiler.heap_window = heap_window; + if (threads % (wave64 ? 64 : 32)) + for (const auto &i : program.code) + if (i.name == "v_readlane_b32" || i.name == "v_writelane_b32") + DirectCompute::validate_lane_shape(i, static_cast(threads), wave64 ? 64 : 32); + if (threads > 32 && threads % 32) + refuse(entry, "partial final wave in multi-wave group"); + if (wave64 && threads % 64) refuse(entry, "wave64 exchange requires complete guest waves"); + if (wave64 && threads > 64) { + const auto &code = program.code; + const bool branches = std::any_of(code.begin(), code.end(), + [](const Inst &i) { return i.branch() && i.op != 2; }); + const bool synchronizes = std::any_of(code.begin(), code.end(), [](const Inst &i) { + return i.enc == Encoding::Vopc || i.enc == Encoding::Lds || carry_destination(i) || + i.name == "v_readfirstlane_b32" || i.name == "v_readlane_b32" || i.name == "s_barrier"; + }); + if (branches && synchronizes) refuse(entry, "multi-wave64 exchange requires converged group control flow"); + } + auto translated = compiler.lower(entry,user,rsrc2,x,y,z); + for (auto &binding : translated.bindings) { + if (stage) apply_reflected_table_use(binding, *stage); + if (!request.root.empty()) { + const auto &desc = layout->Desc_1_1; + if (binding.kind == ComputeViewKind::buffer_srv && binding.root_parameter < desc.NumParameters) { + const auto ¶m = desc.pParameters[binding.root_parameter]; + if (param.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) + apply_scalar_table_layout(binding, param.DescriptorTable); + } + if (binding.kind != ComputeViewKind::root_buffer_srv) continue; + if (binding.root_parameter >= desc.NumParameters) + refuse(entry, "missing compute root descriptor"); + const auto ¶m = desc.pParameters[binding.root_parameter]; + if ((param.ParameterType != D3D12_ROOT_PARAMETER_TYPE_CBV && + param.ParameterType != D3D12_ROOT_PARAMETER_TYPE_SRV) || + param.ShaderVisibility != D3D12_SHADER_VISIBILITY_ALL) + refuse(entry, "compute root descriptor type or visibility"); + } + } + translated.group = {x, y, z}; + return translated; + } + lower_blocks(emit); + std::ostringstream h; + h << R"( +uint extractBits(uint v,uint offset,uint width){return width>=32?v>>(offset&31u):(v>>(offset&31u))&((1u<>31)!=0; + if(a>0x7f800000u)return (a&0x400000u)?2u:1u; + if(a==0x7f800000u)return neg?4u:512u; + if(a>=0x800000u)return neg?8u:256u; + if(a!=0)return neg?16u:128u; + return neg?32u:64u; +} +)"; + for (auto &b : emit.result.bindings) { + auto r = b.shader_register; + if (b.array_position) continue; + if (b.kind == ComputeViewKind::raw_buffer_uav) + h << "RWByteAddressBuffer w" << r << ":register(u" << r << ");\n"; + else if (compute_buffer_uav(b.kind)) { + const bool half = b.kind == ComputeViewKind::half_buffer_uav; + const unsigned n = b.required_bytes / (half ? 2 : 4); + h << "RWBuffer<" << (half ? "float" : "uint") << (n == 1 ? "" : to_string(n)) << "> w" + << r << ":register(u" << r << ");\n"; + } else if (b.kind == ComputeViewKind::half_scalar_uav) + h << "RWTexture2D w" << r << ":register(u" << r << ");\n"; + else if (b.kind == ComputeViewKind::texture_uav) + h << "RWTexture2D w" << r << ":register(u" << r << ");\n"; + else + h << (b.kind == ComputeViewKind::heap_stride_srv || b.kind == ComputeViewKind::buffer_srv || b.kind == ComputeViewKind::raw_vector_srv ? "ByteAddressBuffer" + : b.kind == ComputeViewKind::typed_buffer_srv ? "Buffer" + : "Texture2D") + << " r" << r << (b.array_count>1 ? "["+to_string(b.array_count)+"]" : "") << ":register(t" << r << ");\n"; + } + for (size_t j = 0; j < emit.result.samplers.size(); ++j) + h << "SamplerState q" << j << ":register(s" << j << ");\n"; + unsigned constant_words = 0; + for (const auto &block : constants) + constant_words += block.count; + if (constant_words) + h << "cbuffer EntryConstants:register(b0){uint4 rootWords[" << (constant_words + 3) / 4 << "];};\n"; + if (lds) + h << "groupshared uint lds[" << lds * 128 << "];\n"; + if (threads > 64) + h << "groupshared uint waveStarts[" << threads << "];\n"; + h << "[WaveSize(32)] [numthreads(" << x << "," << y << "," << z + << ")] void main(uint3 g:SV_GroupID,uint idx:SV_GroupIndex){\n"; + for (unsigned j = 0; j < 128; ++j) + h << "uint s" << j << "=0;\n"; + for (unsigned j = 0; j < 256; ++j) + h << "uint v" << j << "=0;\n"; + if (threads <= 32) + h << "uint wave=0u;\n"; + else if (threads == 64) + h << "uint wave=WaveActiveMin(idx)==0u?0u:1u;\n"; + else { + // Order host waves by their lowest group index. Physical lane order need not be row-major. + h << "uint first=WaveActiveMin(idx);waveStarts[idx]=uint(idx==first);GroupMemoryBarrierWithGroupSync();" + "uint wave=0;for(uint p=0;p= 2) + h << "v1=(guestIndex/" << x << "u)%" << y << "u;\n"; + if (local_axes == 3) + h << "v2=guestIndex/" << x * y << "u;\n"; + unsigned sys = user; + for (unsigned axis = 0; axis < 3; ++axis) + if (rsrc2 & (1u << (7 + axis))) + h << "s" << sys++ << "=g." << "xyz"[axis] << ";\n"; + if (rsrc2 & 1024) + h << "s" << sys << "=" << (threads + 31) / 32 << "u|(wave<<20)|(wave==0u?0x80000000u:0u);\n"; + unsigned offset = 0; + for (const auto &block : constants) + for (unsigned j = 0; j < block.count; ++j, ++offset) + h << "s" << block.first_sgpr + j << "=rootWords[" << offset / 4 << "][" << offset % 4 << "];\n"; + h << emit.body.str() << "}\n"; + emit.result.hlsl = h.str(); + emit.result.instruction_count = static_cast(program.code.size()); + emit.result.group = {x, y, z}; + return std::move(emit.result); +} + +// Native FSSM UsedResource and RootParam use dword table offsets and an +// explicit user SGPR. See victory-shader native.rs and victory-gpu draw.rs. +bool x2w::apply_reflected_table_use(ComputeViewBinding &binding, const GuestShaderStage &stage, + std::optional packed_sgpr) { + if (binding.array_count != 1 || binding.kind == ComputeViewKind::heap_stride_srv || + binding.kind == ComputeViewKind::root_buffer_srv || binding.root_parameter == compute_resource_heap) + return false; + const ShaderResourceUse *match = nullptr; + for (const auto &use : stage.resources) { + if (use.root_type != 3 || use.root_parameter != binding.root_parameter || + uint64_t(use.offset_dwords) * 4 != binding.byte_offset) continue; + if (packed_sgpr) { + if (use.user_data != *packed_sgpr) continue; + } else if (std::none_of(stage.inputs.begin(), stage.inputs.end(), [&](const auto &input) { + return input.type == 3 && input.root_parameter == use.root_parameter && input.user_data == use.user_data; + })) { + throw UnsupportedComputeShader("reflected table record has no matching user SGPR"); + } + if (match) throw UnsupportedComputeShader("ambiguous reflected table record"); + match = &use; + } + if (!match) return false; + const bool scalar = binding.kind == ComputeViewKind::buffer_srv; + const bool buffer = scalar || compute_buffer_uav(binding.kind) || binding.kind == ComputeViewKind::raw_vector_srv || + binding.kind == ComputeViewKind::typed_buffer_srv || binding.kind == ComputeViewKind::byte_window_srv; + if (match->dwords != (buffer ? 4u : 8u) || + (match->type != (compute_uav(binding.kind) ? 3u : 0u) && !(scalar && match->type == 2))) + throw UnsupportedComputeShader("raw load disagrees with reflected table record"); + if (scalar) + binding.scalar_table = match->type == 2 ? ComputeViewBinding::ScalarTable::reflected_cbv + : ComputeViewBinding::ScalarTable::srv; + return true; +} + +void x2w::apply_scalar_table_layout(ComputeViewBinding &binding, const D3D12_ROOT_DESCRIPTOR_TABLE1 &table) { + using Table = ComputeViewBinding::ScalarTable; + if (binding.kind != ComputeViewKind::buffer_srv || binding.scalar_table != Table::unknown || binding.byte_offset % 32) + return; + uint64_t end = 0; + const auto slot = binding.byte_offset / 32; + bool cbv = false, srv = false; + for (unsigned i = 0; i < table.NumDescriptorRanges; ++i) { + const auto &range = table.pDescriptorRanges[i]; + const uint64_t first = range.OffsetInDescriptorsFromTableStart == D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND + ? end : range.OffsetInDescriptorsFromTableStart; + end = first + range.NumDescriptors; + if (first <= slot && slot < end) { + cbv |= range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_CBV; + srv |= range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + } + } + if (cbv != srv) binding.scalar_table = cbv ? Table::declared_cbv : Table::srv; +} + +x2w::NativeComputeShader x2w::translate_compute(const ComputeRequest &request, unsigned entry, bool direct_dxil) { + return translate_program(request, entry, direct_dxil, nullptr, HeapViewContract::none); +} + +x2w::NativeComputeShader x2w::translate_compute_container(ComputeContainer container, HeapViewContract heap_view) { + auto stages = read_guest_shader_container(container.bytes); + GuestShaderStage *compute = nullptr; + for (auto &stage : stages) { + if (stage.stage != GpuStage::cs) continue; + if (compute) refuse(0, "ambiguous native compute program"); + compute = &stage; + } + if (!compute) refuse(0, "expected one compute program"); + ComputeRequest request{}; + request.code = std::move(compute->code); + request.root = std::move(container.root); + return translate_program(request, 0, true, compute, heap_view); +} + +x2w::NativeComputeShader x2w::translate_graphics_container(const std::string &bytes,bool pixel) { + auto stages=read_guest_shader_container(bytes); + GuestShaderStage *selected=nullptr; + for(auto &stage:stages)if(stage.stage==(pixel?GpuStage::ps:GpuStage::vs)){ + if(selected)refuse(0,"ambiguous native graphics stage"); + selected=&stage; + } + if(!selected)refuse(0,"missing native graphics stage"); + return lower_graphics(*selected); +} + +x2w::DirectGraphicsPair x2w::translate_graphics_pair(std::string_view a,std::string_view b) { + return translate_graphics_pair(a, b, {}); +} + +// Fixed-descriptor draws publish the bounded native stages in export order, +// without FSSM signatures. Link PARAM exports to interpolator reads using +// the captured entry layout and the channels actually named by each stage. +static bool raw_center_inputs(unsigned enable_mask) { + // SPI_PS_INPUT_ADDR allocates the enabled X/Y/Z/W components after + // the center I/J pair. The packed screen coordinate is a later VGPR. + // victory-shader 9376fd6 io.rs::PS_VGPRS uses the same allocation. + constexpr unsigned position_inputs = (0xfu << 8) | (1u << 15); + return (enable_mask & ~position_inputs) == 2; +} +static GuestShaderStage read_raw_graphics(std::string_view bytes, const D3D12_ROOT_SIGNATURE_DESC1 &layout, + unsigned enable_mask, unsigned address_mask) { + if (bytes.empty() || bytes.size() % 4 || bytes.size() > (1u << 20)) + throw UnsupportedComputeShader("invalid raw graphics extent"); + GuestShaderStage stage{}; + unsigned extent = 0; + bool position = false, color = false, ended = false; + struct Parameter { unsigned exported = 0, smooth = 0, flat = 0; }; + std::array params{}; + const bool has_params = raw_center_inputs(enable_mask); + std::map visited; + std::deque pending{0}; + while (!pending.empty()) { + const unsigned pc = pending.front(); + pending.pop_front(); + auto next = visited.lower_bound(pc); + if (next != visited.end() && next->first == pc) continue; + if (pc >= bytes.size() || (next != visited.begin() && std::prev(next)->second > pc)) + refuse(pc, "raw graphics branch outside code or into an instruction"); + auto op = gfx1013::instruction(bytes, pc); + if (next != visited.end() && pc + op.size > next->first) + refuse(pc, "overlapping raw graphics instructions"); + visited.emplace_hint(next, pc, pc + op.size); + extent = (std::max)(extent, pc + op.size); + if (op.form == gfx1013::Form::ds || op.name == "s_swappc_b64" || (!has_params && (op.form == gfx1013::Form::vintrp || + op.name.substr(0,9) == "s_cbranch" || op.name == "s_branch" || op.name.find("exec") != Name::npos || + op.name.substr(0,7) == "v_cmpx_" || op.name.find("wqm") != Name::npos))) + refuse(pc, "raw graphics requires a verified stage interface or wave state"); + if (op.form == gfx1013::Form::vintrp) { + Word w; std::memcpy(&w, bytes.data()+pc, sizeof(w)); + const unsigned attr = (w >> 10) & 63; + if (attr >= params.size()) refuse(pc, "raw interpolation attribute exceeds entry count"); + auto &mask = ((w >> 16) & 3) == 2 ? params[attr].flat : params[attr].smooth; + mask |= 1u << ((w >> 8) & 3); + } + if (op.form == gfx1013::Form::exp) { + Word w; std::memcpy(&w, bytes.data()+pc, sizeof(w)); + const unsigned target = (w >> 4) & 63; + if (target == 12) position = true; + else if (target < 8) color = true; + else if (target == 9 && !(w & 15)) {} // Null export on a pixel kill path. + else if (has_params && target >= 32 && target - 32 < params.size() && + !params[target - 32].exported && !(w & 0x400)) params[target - 32].exported = w & 15; + else refuse(pc, "raw graphics varying or system export requires a stage interface"); + } + if (op.name == "s_endpgm") { + ended = true; + continue; + } + if (op.name == "s_branch" || op.name.substr(0,9) == "s_cbranch") { + int16_t displacement; + std::memcpy(&displacement, bytes.data() + pc, sizeof(displacement)); + pending.push_back(pc + op.size + 4 * displacement); + } + if (op.name != "s_branch") pending.push_back(pc + op.size); + } + if (!ended || position == color) refuse(extent, "ambiguous raw graphics stage"); + stage.stage = position ? GpuStage::vs : GpuStage::ps; + stage.fixed_vertex_abi = position && has_params; + stage.code.assign(bytes.substr(0,extent)); + if (color) { + stage.pixel_input_address = address_mask; + stage.pixel_input_enable = enable_mask; + } + if ((color && (enable_mask & 0x8f00)) || (position && has_params)) + (color ? stage.input_signature : stage.output_signature).push_back({"SV_Position",0,1,3,0,15,15}); + for (uint8_t attr = 0; attr < params.size(); ++attr) { + const auto &p = params[attr]; + if ((position && (p.smooth || p.flat)) || (color && p.exported) || (p.smooth & p.flat)) + refuse(0, "ambiguous raw varying interface"); + // A PARAM may mix smooth channels and provoking-vertex fetches. + for (unsigned ch = 0; ch < 4; ++ch) { + const uint8_t bit = uint8_t(1u << ch); + if (!((p.exported | p.smooth | p.flat) & bit)) continue; + const unsigned index = 4 * attr + ch; + const uint8_t row = uint8_t(index + 1); + (position ? stage.outputs : stage.attributes).push_back({6,row,bit,attr,0,uint8_t(bool(p.flat & bit))}); + (position ? stage.output_signature : stage.input_signature).push_back({"TEXCOORD",index,0,3,row,bit,bit}); + } + } + // Same fixed-descriptor user data layout as the legacy graphics path. + unsigned sgpr = 8; + for (unsigned j=0; j106-sgpr || j>=16) refuse(0,"raw graphics user data exceeds register range"); + if (p.ShaderVisibility==D3D12_SHADER_VISIBILITY_ALL || + p.ShaderVisibility==(position ? D3D12_SHADER_VISIBILITY_VERTEX : D3D12_SHADER_VISIBILITY_PIXEL)) + stage.inputs.push_back({table ? 3u : constants ? 0u : 1u,0,count,0,uint8_t(sgpr),uint8_t(j)}); + sgpr+=count; + } + return stage; +} + +x2w::DirectGraphicsPair x2w::translate_graphics_pair(std::string_view a,std::string_view b, + const D3D12_ROOT_SIGNATURE_DESC1 &layout, std::string_view pixel_entry, + std::optional first_stage, + const std::array &target_components) { + const bool raw = a.substr(0,4)!="DXBC" && b.substr(0,4)!="DXBC"; + unsigned enable_mask=0, address_mask=0; + if (!pixel_entry.empty()) { + if (!raw || pixel_entry.size()!=13 || pixel_entry.substr(0,5)!="psin1") + refuse(0,"invalid raw pixel entry record"); + std::memcpy(&enable_mask,pixel_entry.data()+5,4); + std::memcpy(&address_mask,pixel_entry.data()+9,4); + if (enable_mask > 0xffff || address_mask > 0xffff || (enable_mask & ~address_mask)) + refuse(0,"contradictory pixel input enable/address masks"); + } + auto read_stage = [&](std::string_view bytes) { + return raw ? std::vector{read_raw_graphics(bytes,layout,enable_mask,address_mask)} : read_guest_shader_container(bytes); + }; + auto left=read_stage(a),right=read_stage(b); + if(left.size()!=1 || right.size()!=1)refuse(0,"expected a distinct stage per graphics container"); + if (first_stage && left.front().stage != *first_stage) + refuse(0,"raw exports disagree with reflected stage"); + auto *vs=&left.front(),*ps=&right.front(); + if(vs->stage==GpuStage::ps)std::swap(vs,ps); + if(vs->stage!=GpuStage::vs || ps->stage!=GpuStage::ps)refuse(0,"expected vertex and pixel stages"); + ps->target_components=target_components; + return translate_reflected_graphics(*vs,*ps,layout); +} +x2w::DirectGraphicsPair x2w::translate_reflected_graphics(GuestShaderStage &vs, GuestShaderStage &ps, + const D3D12_ROOT_SIGNATURE_DESC1 &layout) { + GraphicsConstantLayout constants; + for (const auto *stage:{&vs,&ps}) + for(const auto &input:stage->inputs) + if(input.type==0) constants.include(input.root_parameter,input.sgpr_count); + auto vertex=lower_graphics(vs,0,0,&constants,layout); + const unsigned vertex_uavs = static_cast(std::count_if(vertex.bindings.begin(), vertex.bindings.end(), + [](const auto &binding) { return compute_uav(binding.kind); })); + auto pixel = lower_graphics(ps, static_cast(vertex.bindings.size()) - vertex_uavs, + static_cast(vertex.samplers.size()), &constants, layout, vertex_uavs); + for (auto &binding : vertex.bindings) apply_reflected_table_use(binding, vs); + for (auto &binding : pixel.bindings) apply_reflected_table_use(binding, ps); + for(const auto &input:pixel.inputs){ + if(input.name=="SV_IsFrontFace" || input.kind==28) continue; + auto producer=std::find_if(vertex.outputs.begin(),vertex.outputs.end(),[&](auto &out){ + return out.name==input.name && out.index==input.index && out.row==input.row && out.component==input.component && + ((out.used< +#include +#include +#include +#include + +struct D3D12_ROOT_SIGNATURE_DESC1; +struct D3D12_ROOT_DESCRIPTOR_TABLE1; +namespace x2w { +enum class GpuStage; +struct GuestShaderStage; +class UnsupportedComputeShader : public std::runtime_error { + public: + using std::runtime_error::runtime_error; +}; +enum class ComputeViewKind { + buffer_srv, + typed_buffer_srv, + texture_srv, + texture_uav, + raw_vector_srv, + half_scalar_uav, + heap_stride_srv, + raw_buffer_uav, + typed_buffer_uav, + half_buffer_uav, + root_buffer_srv, + comparison_texture_srv, + half2_texture_uav, + half4_texture_uav, + cube_sample_srv, + cube_comparison_srv, + indexed_atomic_uav, + d16_sample_srv, + byte_window_srv, + heap_buffer_srv // A raw buffer read through ResourceDescriptorHeap[slot]; the slot is a GPU value. +}; +inline constexpr unsigned compute_resource_heap = ~0u; +// A binding of the whole descriptor heap: it has no table register and no root parameter. +inline bool compute_heap_binding(ComputeViewKind kind) { return kind == ComputeViewKind::heap_buffer_srv; } +inline bool compute_buffer_uav(ComputeViewKind kind) { + return kind == ComputeViewKind::raw_buffer_uav || kind == ComputeViewKind::typed_buffer_uav || + kind == ComputeViewKind::half_buffer_uav || kind == ComputeViewKind::indexed_atomic_uav; +} +struct IndexedAtomicView { + unsigned stride = 0, count = 0; // Bytes per guest index and number of valid indices. +}; +inline bool compute_uav(ComputeViewKind kind) { + return kind == ComputeViewKind::texture_uav || kind == ComputeViewKind::half_scalar_uav || + kind == ComputeViewKind::half2_texture_uav || kind == ComputeViewKind::half4_texture_uav || compute_buffer_uav(kind); +} +struct ComputeViewBinding { + ComputeViewKind kind; + unsigned root_parameter; + unsigned byte_offset; + unsigned shader_register; + unsigned required_bytes; + unsigned array_count = 1, array_position = 0; + unsigned image_dimension = 1; // ISA dimension field; 1 denotes Texture2D. + enum class ScalarTable { unknown, reflected_cbv, declared_cbv, srv }; + ScalarTable scalar_table = ScalarTable::unknown; +}; +bool apply_reflected_table_use(ComputeViewBinding &binding, const GuestShaderStage &stage, + std::optional packed_sgpr = {}); +void apply_scalar_table_layout(ComputeViewBinding &binding, const D3D12_ROOT_DESCRIPTOR_TABLE1 &table); +struct ComputeSampler { + std::array words; + bool explicit_lod; + bool comparison = false; +}; +struct ComputeConstants { + unsigned root_parameter; + unsigned first_sgpr; + unsigned count; +}; +// Both graphics stages read a single desktop b0. Pack each guest root once, +// in parameter order, irrespective of the SGPR order in either stage. +struct GraphicsConstantLayout { + std::array counts{}; + unsigned offset(unsigned parameter) const { + unsigned position = 0; + for (unsigned r = 0; r < parameter; ++r) + position += counts.at(r); + return position; + } + void include(unsigned parameter, unsigned count) { + if (parameter >= counts.size() || !count || count > 32) + throw UnsupportedComputeShader("invalid graphics root constant range"); + if (counts[parameter] < count) + counts[parameter] = count; + if (offset(static_cast(counts.size())) > 32) + throw UnsupportedComputeShader("linked graphics root exceeds 32 words"); + } +}; +struct GraphicsLinkage { + std::string name; + unsigned index, row, first, width, component, used, kind, interpolation; +}; +struct NativeComputeShader { + std::vector inputs, outputs; + std::vector constants; + std::string hlsl, dxil_ir; + std::vector bindings; + std::vector samplers; + unsigned instruction_count{}; + std::array group{}; + bool vertex_fetch = false; + std::array pixel_writes{}; +}; +// The view class a GPU-selected descriptor heap slot is read as. none: the slot and its view type are not known, so a +// heap read is refused. raw_buffer: the capture says the selected slot is a raw buffer SRV. other: the capture names a +// view type that is not translated (refused when the shader reads the heap). +// Under raw_buffer the direct path also reads the byte-address rewrite of the selected descriptor (stride read, +// max(stride, 1), byte count, stride cleared, raw out-of-bounds mode) as the same raw view. The caller guarantees that +// every slot the program can select is a raw view whose size is the guest range num_records * max(stride, 1); the +// translator does not check that, nor the swizzle bits (word 1 bits 31:30) or the other word 3 fields, and a program +// with two heap loads from different selectors is outside what one captured selection covers. +enum class HeapViewContract : unsigned { none, raw_buffer, other }; +NativeComputeShader translate_compute(const ComputeRequest &request, unsigned entry_byte_offset, + bool direct_dxil = false); +NativeComputeShader translate_compute_container(ComputeContainer container, + HeapViewContract heap_view = HeapViewContract::none); +struct NativeVertexElement { + std::string semantic; + unsigned index, format, slot, offset, classification, step_rate; + bool used = false; +}; +struct DirectGraphicsPair { + NativeComputeShader vertex, pixel; + std::vector input_layout; + // GuestShaderStage::target_components of the pixel stage: the target types an RTV variant asked for. + std::array target_components{}; + GraphicsConstantLayout constant_layout() const { + GraphicsConstantLayout layout; + for (auto *stage : {&vertex, &pixel}) + for (const auto &block : stage->constants) + layout.include(block.root_parameter, block.count); + return layout; + } +}; +DirectGraphicsPair translate_graphics_pair(std::string_view a, std::string_view b, + const D3D12_ROOT_SIGNATURE_DESC1 &layout, std::string_view pixel_entry = {}, + std::optional first_stage = {}, + const std::array &target_components = {}); +DirectGraphicsPair translate_graphics_pair(std::string_view a, std::string_view b); +DirectGraphicsPair translate_reflected_graphics(GuestShaderStage &vs, GuestShaderStage &ps, + const D3D12_ROOT_SIGNATURE_DESC1 &layout); +std::string native_rectangle_geometry(const std::vector& vertex_outputs, + const std::vector& pixel_inputs); +NativeComputeShader translate_graphics_container(const std::string &bytes, bool pixel); +} // namespace x2w diff --git a/src/gfx1013_compute_opcodes.inl b/src/gfx1013_compute_opcodes.inl new file mode 100644 index 000000000..5e05ef95c --- /dev/null +++ b/src/gfx1013_compute_opcodes.inl @@ -0,0 +1,193 @@ +// Opcode spellings and fields follow the repository gfx1013 disassembler. +static const char* mnemonic(Encoding enc, unsigned op) { + switch (enc) { + case Encoding::Sopp: + switch (op) { + case 0x0: return "s_nop"; + case 0x1: return "s_endpgm"; + case 0x2: return "s_branch"; + case 0x4: return "s_cbranch_scc0"; + case 0x5: return "s_cbranch_scc1"; + case 0x6: return "s_cbranch_vccz"; + case 0x7: return "s_cbranch_vccnz"; + case 0x8: return "s_cbranch_execz"; + case 0x9: return "s_cbranch_execnz"; + case 0xa: return "s_barrier"; + case 0xc: return "s_waitcnt"; + case 0x20: return "s_inst_prefetch"; + case 0x21: return "s_clause"; + default: break; + } + break; + case Encoding::Sop1: + switch (op) { + case 0x3: return "s_mov_b32"; + case 0x4: return "s_mov_b64"; + case 0x7: return "s_not_b32"; + case 0x3c: return "s_and_saveexec_b32"; + case 0x47: return "s_andn2_wrexec_b32"; + default: break; + } + break; + case Encoding::Sop2: + switch (op) { + case 0x1: return "s_sub_u32"; + case 0x7: return "s_min_u32"; + case 0x9: return "s_max_u32"; + case 0x20: return "s_lshr_b32"; + case 0x35: return "s_mul_hi_u32"; + case 0: return "s_add_u32"; + case 0x26: return "s_mul_i32"; + case 0xa: return "s_cselect_b32"; + case 0xe: return "s_and_b32"; + case 0x10: return "s_or_b32"; + case 0x14: return "s_andn2_b32"; + case 0x1a: return "s_nor_b32"; + case 0x1e: return "s_lshl_b32"; + case 0x24: return "s_bfm_b32"; + case 0x27: return "s_bfe_u32"; + case 0x2c: return "s_absdiff_i32"; + case 0x2e: return "s_lshl1_add_u32"; + case 0x2f: return "s_lshl2_add_u32"; + case 0x30: return "s_lshl3_add_u32"; + case 0x31: return "s_lshl4_add_u32"; + default: break; + } + break; + case Encoding::Sopc: + switch (op) { + case 0x6: return "s_cmp_eq_u32"; + case 0x7: return "s_cmp_lg_u32"; + case 0xa: return "s_cmp_lt_u32"; + case 0x0: return "s_cmp_eq_i32"; + case 0x1: return "s_cmp_lg_i32"; + case 0x4: return "s_cmp_lt_i32"; + case 0xd: return "s_bitcmp1_b32"; + default: break; + } + break; + case Encoding::Sopk: + switch (op) { + case 0x4: return "s_cmpk_lg_i32"; + case 0x10: return "s_mulk_i32"; + case 0x0: return "s_movk_i32"; + default: break; + } + break; + case Encoding::Vop1: + switch (op) { + case 0x0b: return "v_cvt_f32_f16"; + case 0x36: return "v_cos_f32"; + case 0x65: return "v_swap_b32"; + case 2: return "v_readfirstlane_b32"; + case 0x1: return "v_mov_b32"; + case 0x5: return "v_cvt_f32_i32"; + case 0x6: return "v_cvt_f32_u32"; + case 0x8: return "v_cvt_i32_f32"; + case 0x11: return "v_cvt_f32_ubyte0"; + case 0x23: return "v_rndne_f32"; + case 0x2e: return "v_rsq_f32"; + case 0x7: return "v_cvt_u32_f32"; + case 0x24: return "v_floor_f32"; + case 0x25: return "v_exp_f32"; + case 0x27: return "v_log_f32"; + case 0x2a: return "v_rcp_f32"; + case 0x33: return "v_sqrt_f32"; + case 0x35: return "v_sin_f32"; + default: break; + } + break; + case Encoding::Vop2: + switch (op) { + case 0x1d: return "v_xor_b32"; + case 0x13: return "v_min_u32"; + case 0x1: return "v_cndmask_b32"; + case 0x3: return "v_add_f32"; + case 0x4: return "v_sub_f32"; + case 0x5: return "v_subrev_f32"; + case 0x8: return "v_mul_f32"; + case 0xb: return "v_mul_u32_u24"; + case 0xf: return "v_min_f32"; + case 0x10: return "v_max_f32"; + case 0x16: return "v_lshrrev_b32"; + case 0x18: return "v_ashrrev_i32"; + case 0x1a: return "v_lshlrev_b32"; + case 0x1b: return "v_and_b32"; + case 0x1c: return "v_or_b32"; + case 0x25: return "v_add_nc_u32"; + case 0x26: return "v_sub_nc_u32"; + case 0x2b: return "v_fmac_f32"; + case 0x2c: return "v_fmamk_f32"; + case 0x2d: return "v_fmaak_f32"; + default: break; + } + break; + case Encoding::Vopc: + switch (op) { + case 0x0d: return "v_cmp_neq_f32"; + case 0x81: return "v_cmp_lt_i32"; + case 0x84: return "v_cmp_gt_i32"; + case 0x86: return "v_cmp_ge_i32"; + case 0x91: return "v_cmpx_lt_i32"; + case 0x92: return "v_cmpx_eq_i32"; + case 0x93: return "v_cmpx_le_i32"; + case 0x94: return "v_cmpx_gt_i32"; + case 0x95: return "v_cmpx_ne_i32"; + case 0x96: return "v_cmpx_ge_i32"; + case 0xc1: return "v_cmp_lt_u32"; + case 0xc2: return "v_cmp_eq_u32"; + case 0xc3: return "v_cmp_le_u32"; + case 0xc4: return "v_cmp_gt_u32"; + case 0xc5: return "v_cmp_ne_u32"; + case 0xc6: return "v_cmp_ge_u32"; + case 0xd1: return "v_cmpx_lt_u32"; + case 0xd2: return "v_cmpx_eq_u32"; + case 0xd3: return "v_cmpx_le_u32"; + case 0xd4: return "v_cmpx_gt_u32"; + case 0xd5: return "v_cmpx_ne_u32"; + case 0xd6: return "v_cmpx_ge_u32"; + case 0x1: return "v_cmp_lt_f32"; + case 0x2: return "v_cmp_eq_f32"; + case 0x3: return "v_cmp_le_f32"; + case 0x4: return "v_cmp_gt_f32"; + case 0x6: return "v_cmp_ge_f32"; + case 0xc: return "v_cmp_nle_f32"; + case 0x82: return "v_cmp_eq_i32"; + case 0x83: return "v_cmp_le_i32"; + case 0x85: return "v_cmp_ne_i32"; + case 0x88: return "v_cmp_class_f32"; + default: break; + } + break; + case Encoding::Vop3: + switch (op) { + case 0x148: return "v_bfe_u32"; + case 0x14a: return "v_bfi_b32"; + case 0x14b: return "v_fma_f32"; + case 0x151: return "v_min3_f32"; + case 0x154: return "v_max3_f32"; + case 0x157: return "v_med3_f32"; + case 0x158: return "v_med3_i32"; + case 0x16a: return "v_mul_hi_u32"; + case 0x169: return "v_mul_lo_u32"; + case 0x16c: return "v_mul_hi_i32"; + case 0x300: return "v_lshrrev_b64"; + case 0x346: return "v_lshl_add_u32"; + case 0x347: return "v_add_lshl_u32"; + case 0x365: return "v_mbcnt_lo_u32_b32"; + case 0x366: return "v_mbcnt_hi_u32_b32"; + case 0x36f: return "v_lshl_or_b32"; + case 0x371: return "v_and_or_b32"; + default: break; + } + break; + case Encoding::Mix: + switch (op) { + case 0x20: return "v_fma_mix_f32"; + default: break; + } + break; + default: break; + } + return nullptr; +} diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl new file mode 100644 index 000000000..e845bff37 --- /dev/null +++ b/src/gfx1013_direct_compute.inl @@ -0,0 +1,2243 @@ +// Lower the shared decoded CFG to DXIL operations. A scalar register holds one +// 32-bit word per wave. Ordinary vector writes retain their old value on inactive lanes. +struct DirectCompute { + static constexpr Word inline_float_words[]{0x3f000000, 0xbf000000, 0x3f800000, 0xbf800000, 0x40000000, + 0xc0000000, 0x40800000, 0xc0800000, 0x3e22f983}; + static std::optional constant32(const Inst &i, unsigned r) { + if (r >= 128 && r <= 192) return r - 128; + if (r >= 193 && r <= 208) return Word(192) - r; + if (r >= 240 && r <= 248) return inline_float_words[r - 240]; + if (r == 255) return i.literal; + return {}; + } + static void validate_lane_shape(const Inst &i, unsigned threads, unsigned width) { + const auto constant = constant32(i, i.src[1]); + const auto remaining = threads % width; + if (((i.src[1] <= 105 || (width == 32 && i.src[1] == 107)) && threads % 32) || + (constant && remaining && (*constant & (width - 1)) >= remaining)) + refuse(i.pc, "lane read/write needs full waves"); + } + Emit &analysis; + DxilModule ir; + std::set allocated; + string lane, lane_bit, half_index, upper_half, exchange_base; + unsigned exchange_words = 0; + bool uses_exchange = false; + bool wave64 = false; + // The view class a GPU-selected heap slot is read as; see HeapViewContract. + HeapViewContract heap_view = HeapViewContract::none; + // heap_view is raw_buffer and the path is direct: the byte-address rewrite of a heap descriptor is tracked. + bool heap_window = false; + // Binary16 add, sub, subrev and mul are lowered only while MODE stays at + // the contract this path implements: round-to-nearest-even, f16 denormals + // kept on input and output, and FP16_OVFL clear. mode_bits holds the + // fields this path tracks (round in [3:0], denorm in [7:4], FP16_OVFL in + // bit 23). A guest branch together with a MODE write makes the value at + // the arithmetic unprovable. + bool half_binary = false; + bool half_mode_known = true; + unsigned mode_bits = 0xf0; + std::vector scc_live; + unsigned label_number = 0; + bool pixel_stage = false; + // Straight-line graphics stages keep exact SSA definitions; a missing + // entry value is resolved through the container's stage signature. + std::function graphics_input; + std::function after_graphics_write; + std::map graphics_registers; + string graphics_predicate; + unsigned graphics_pc = 0; + bool perspective_center_pair = false; + bool exact_pixel_entry = false; + bool helper_result_unobserved = false; + unsigned pixel_entry_vgprs = 0; + std::function untouched_pixel_register; + // P1/P2 consume the entry IJ pair symbolically. After an exact-mask + // write, covered lanes can use the replacement. Materialize the entry + // barycentric only when an observer can also see the unmodified lanes. + std::map> guarded_ij; + string materialize_ij(unsigned r) { + auto [predicate, updated] = guarded_ij.at(r); + auto value = select(predicate, updated, graphics_input(r)); + graphics_registers[r] = value; + guarded_ij.erase(r); + return value; + } + string address(unsigned r) { + const auto name = "%r" + to_string(r); + if (allocated.insert(r).second) + ir.setup << " " << name << " = alloca i32, align 4\n"; + return name; + } + string read(unsigned r) { + if (graphics_input) { + auto guarded = guarded_ij.find(r); + if (guarded != guarded_ij.end()) + return guarded->second.first == graphics_predicate ? guarded->second.second : materialize_ij(r); + auto found = graphics_registers.find(r); + if (found != graphics_registers.end()) { + if (found->second.empty()) + refuse(graphics_pc, "graphics register undefined on an incoming path: " + to_string(r)); + return found->second; + } + auto value = graphics_input(r); + graphics_registers.emplace(r, value); + return value; + } + return ir.value("load i32, i32* " + address(r) + ", align 4"); + } + void write(unsigned r, const string &value) { + if (graphics_input) { + guarded_ij.erase(r); + graphics_registers[r] = value; + after_graphics_write(r); + return; + } + const auto ptr = address(r); + ir.body << " store i32 " << value << ", i32* " << ptr << ", align 4\n"; + } + string cmp(const string &predicate, const string &a, const string &b) { + return ir.value("icmp " + predicate + " i32 " + a + ", " + b); + } + string select(const string &predicate, const string &yes, const string &no) { + return ir.value("select i1 " + predicate + ", i32 " + yes + ", i32 " + no); + } + string active() { + if (graphics_input) + return "true"; + return cmp("ne", ir.binary("and", wave64 ? select(upper_half, read(127), read(126)) : read(126), lane_bit), "0"); + } + void vector_write(unsigned r, const string &value) { + if (graphics_input && graphics_predicate.empty()) + write(r, value); + else if (perspective_center_pair && (r == 256 || r == 257) && + (!graphics_registers.count(r) || (guarded_ij.count(r) && guarded_ij.at(r).first == graphics_predicate))) { + write(r, {}); + guarded_ij.emplace(r, std::make_pair(graphics_predicate, value)); + } else if (exact_pixel_entry && helper_result_unobserved && pixel_entry_vgprs && r >= 256 + pixel_entry_vgprs && + !graphics_registers.count(r) && untouched_pixel_register(r)) { + // Only covered lanes can observe this result. In particular no + // subsequent implicit LOD or quad operation can inspect helpers. + write(r, value); + } else + write(r, select(graphics_input ? graphics_predicate : active(), value, read(r))); + } + string operand32(const Inst &i, unsigned n) { + if (graphics_input && n == 106) + refuse(i.pc, "graphics instruction consumes a full wave mask"); + if (n <= 106 || n == 126 || n == 127 || (!graphics_input && n == 107) || (n >= 256 && n < 512)) { + analysis.require_numeric(i, n); + return read(n); + } + if (n == 253) + return read(128); // internal slot for SCC + if (auto constant = constant32(i, n)) + return to_string(*constant); + refuse(i.pc, "direct DXIL operand encoding"); + } + string ballot(const string &pred) { + ir.uses_wave = true; + auto b = ir.invoke("%dx.types.fouri32", "waveActiveBallot", 116, {{"i1", pred}}, "nounwind"); + return ir.value("extractvalue %dx.types.fouri32 " + b + ", 0"); + } + string group_intrinsic(const string &name, unsigned opcode, unsigned axis) { + return ir.invoke("i32", name, opcode, {{"i32", to_string(axis)}}, "nounwind readnone"); + } + string shared_address(const string &name, unsigned words, const string &index) { + const string type = "[" + to_string(words) + " x i32]"; + return ir.value("getelementptr " + type + ", " + type + " addrspace(3)* @" + name + ", i32 0, i32 " + index); + } + void barrier(unsigned mode = 9) { + ir.invoke("void", "barrier", 80, {{"i32", to_string(mode)}}, "nounwind noduplicate"); + } + // Each guest wave owns two scratch words. Multi-wave groups that use + // exchange must reach these workgroup barriers in the same order. + std::array exchange_halves(const string &word) { + const auto tag = to_string(label_number++); + if (!uses_exchange) { + ir.globals << "@waveExchange = internal addrspace(3) global [" << exchange_words << " x i32] undef, align 4\n"; + uses_exchange = true; + } + auto ptr = shared_address("waveExchange", exchange_words, half_index); + auto first = cmp("eq", lane, "0"); + ir.body << " br i1 " << first << ", label %publish" << tag << ", label %published" << tag + << "\npublish" << tag << ":\n store i32 " << word << ", i32 addrspace(3)* " << ptr + << ", align 4\n br label %published" << tag << "\npublished" << tag << ":\n"; + barrier(); + std::array pair; + for (unsigned j = 0; j != 2; ++j) + pair[j] = ir.value("load i32, i32 addrspace(3)* " + shared_address("waveExchange", exchange_words, ir.binary("add", exchange_base, to_string(j))) + ", align 4"); + barrier(); + return pair; + } + void write_ballot(unsigned dst, const string &condition) { + auto mask = ballot(ir.value("and i1 " + active() + ", " + condition)); + if (wave64) { + if ((dst & 1) || (dst > 104 && dst != 106 && dst != 126)) + throw UnsupportedComputeShader("invalid wave64 mask destination"); + auto pair = exchange_halves(mask); + write(dst, pair[0]); + write(dst + 1, pair[1]); + } else + write(dst, mask); + } + string pair_high(const Inst &i, unsigned src) { + if (src <= 104 || src == 106 || src == 126) { + if (src & 1) refuse(i.pc, "unaligned scalar mask pair"); + return operand32(i, src + 1); + } + if ((src >= 128 && src <= 192) || src == 255) return "0"; + if (src >= 193 && src <= 208) return "4294967295"; + refuse(i.pc, "unsupported wave64 scalar pair"); + } + void initialize(unsigned user, unsigned flags, unsigned x, unsigned y, unsigned z) { + unsigned threads = x * y * z; + lane = ir.invoke("i32", "waveGetLaneIndex", 111, {}, "nounwind readnone"); + lane_bit = ir.binary("shl", "1", lane); + write(126, ballot("true")); + if (!wave64) { + write(127, "0"); + // s107 is ordinary scalar data in wave32; a VCC pair read sees zero until it is written. + write(107, "0"); + } + string wave = "0"; + if (threads > 32) { + auto flat = ir.invoke("i32", "flattenedThreadIdInGroup.i32", 96, {}, "nounwind readnone"); + auto first = + ir.invoke("i32", "waveActiveOp.i32", 119, {{"i32", flat}, {"i8", "2"}, {"i8", "1"}}, "nounwind"); + if (threads == 64) + wave = ir.value("zext i1 " + cmp("ne", first, "0") + " to i32"); + else { + ir.globals << "@waveStarts = internal addrspace(3) global [" << threads << " x i32] undef, align 4\n"; + auto ptr = shared_address("waveStarts", threads, flat); + auto leader = ir.value("zext i1 " + cmp("eq", first, flat) + " to i32"); + ir.body << " store i32 " << leader << ", i32 addrspace(3)* " << ptr << ", align 4\n"; + barrier(); + ir.body << " br label %rankLoop\nrankLoop:\n %idx = phi i32 [0, %entry], [%step, %count]\n" + " %rank = phi i32 [0, %entry], [%sum, %count]\n"; + auto more = cmp("ult", "%idx", first); + ir.body << " br i1 " << more << ", label %count, label %rankDone\ncount:\n"; + auto addr = shared_address("waveStarts", threads, "%idx"); + auto flag = ir.value("load i32, i32 addrspace(3)* " + addr + ", align 4"); + ir.body << " %sum = add i32 %rank, " << flag + << "\n %step = add i32 %idx, 1\n br label %rankLoop\nrankDone:\n"; + wave = "%rank"; + } + } + if (wave64) { + exchange_words = threads / 32; + half_index = wave; + exchange_base = ir.binary("and", wave, "4294967294"); + upper_half = cmp("ne", ir.binary("and", wave, "1"), "0"); + write(127, "4294967295"); + } + auto logical = ir.binary("add", ir.binary("mul", wave, "32"), lane); + write(256, ir.binary("urem", logical, to_string(x))); + if (((flags >> 11) & 3) >= 1) + write(257, ir.binary("urem", ir.binary("udiv", logical, to_string(x)), to_string(y))); + if (((flags >> 11) & 3) >= 2) + write(258, ir.binary("udiv", logical, to_string(x * y))); + for (unsigned j = 0; j < 3; ++j) + if (flags & (128u << j)) + write(user++, group_intrinsic("groupId.i32", 94, j)); + if (flags & 1024) { + if (wave64) wave = ir.binary("lshr", wave, "1"); + auto info = ir.binary("or", ir.binary("shl", wave, "20"), to_string(wave64 ? threads / 64 : (threads + 31) / 32)); + write(user, ir.binary("or", info, select(cmp("eq", wave, "0"), "2147483648", "0"))); + } + initialize_constants(); + } + void initialize_constants(const GraphicsConstantLayout *linked = nullptr) { + unsigned words = 0; + for (const auto &block : analysis.result.constants) + words += block.count; + if (words) { + if (linked) + words = linked->offset(static_cast(linked->counts.size())); + auto h = ir.handle({2, 0, 13, 0, 0, (words + 3) / 4 * 16}); + unsigned pos = 0; + std::map vectors; + for (const auto &block : analysis.result.constants) { + if (linked) + pos = linked->offset(block.root_parameter); + for (unsigned j = 0; j < block.count; ++j, ++pos) { + auto &vec = vectors[pos / 4]; + if (vec.empty()) + vec = ir.invoke("%dx.types.CBufRet.i32", "cbufferLoadLegacy.i32", 59, + {{"%dx.types.Handle", h}, {"i32", to_string(pos / 4)}}, "nounwind readonly"); + write(block.first_sgpr + j, + ir.value("extractvalue %dx.types.CBufRet.i32 " + vec + ", " + to_string(pos % 4))); + } + } + } + } + // Refuses a GPU-selected heap read that the contract does not cover. raw_buffer is the only class that is translated. + void refuse_heap_contract(unsigned pc) const { + if (heap_view == HeapViewContract::none) + refuse(pc, "direct resource-heap load requires the selected GPU slot and its view type"); + if (heap_view == HeapViewContract::other) + refuse(pc, "GPU-selected heap slot view type is not raw_buffer; only raw buffer heap reads are translated"); + } + // A raw buffer SRV chosen by a GPU value in the whole descriptor heap: ResourceDescriptorHeap[slot]. The view class the + // shader reads is the one this handle is annotated with (raw buffer); a slot holding another class is refused by the + // dispatch before the shader runs. The binding names the heap (no table register); the pipeline indexes it directly. + // A byte window is the byte-address rewrite of that descriptor (word 0 copied, word 1 without stride, word 2 the + // byte count, word 3 with the raw out-of-bounds mode; see byte_descriptor_field): read as the same raw slot view. + string heap_resource(const Inst &i, const State &s, unsigned base, ComputeViewKind kind, unsigned bytes) { + const auto &symbol = s.at(base); + refuse_heap_contract(i.pc); + const bool window = kind == ComputeViewKind::byte_window_srv; + if (kind != ComputeViewKind::raw_vector_srv && kind != ComputeViewKind::buffer_srv && !window) + refuse(i.pc, "a GPU-selected heap slot is read as a raw buffer SRV only"); + if (symbol.offset % 32 || s[base].type != Symbol::Type::indexed_descriptor) + refuse(i.pc, "unaligned heap descriptor"); + // Precaution: the rewritten words are compared by the pc of their heap load (symbol.definition), which a loop + // around that load executes again for another selection. A loop that does not contain the load runs it once. + // The scan also sees unreached code up to s_endpgm, which can only refuse more. + if (window) + for (const auto &inst : analysis.program.code) + if (inst.branch() && inst.target() <= symbol.definition && symbol.definition <= inst.pc) + refuse(i.pc, "heap byte window loaded inside a loop"); + constexpr Symbol::Type window_words[] = {Symbol::Type::indexed_descriptor, Symbol::Type::zero_stride_word, + Symbol::Type::byte_count, Symbol::Type::byte_oob}; + for (unsigned j = 1; j < 4; ++j) { + Symbol expected = symbol; + if (window) + expected.type = window_words[j]; // field() already cleared the word offset + else + expected.offset += 4 * j; + if (!(s.at(base + j) == expected)) + refuse(i.pc, "non-contiguous resource descriptor"); + } + auto &bindings = analysis.result.bindings; + auto it = std::find_if(bindings.begin(), bindings.end(), [](const auto &b) { + return b.kind == ComputeViewKind::heap_buffer_srv; + }); + if (it == bindings.end()) + bindings.push_back({ComputeViewKind::heap_buffer_srv, compute_resource_heap, 0, 0, bytes}); + else + it->required_bytes = (std::max)(it->required_bytes, bytes); + // 16: raw buffers. 0x40000000: the module reads ResourceDescriptorHeap (DXC sets both for the HLSL reference, + // see tests/native_heap_handle_probe_check.py); the validator refuses a module whose flags do not match. + ir.features |= 16 | 0x40000000; + return ir.heap_handle(ir.binary("add", read(base), to_string(symbol.offset / 32)), 11, 0); + } + string resource(const Inst &i, const State &s, unsigned base, ComputeViewKind kind, unsigned bytes, + unsigned *bound_register = nullptr) { + const auto &symbol = s.at(base); + const bool indexed = symbol.type == Symbol::Type::indexed_descriptor; + if (indexed && symbol.value == compute_resource_heap) + return heap_resource(i, s, base, kind, bytes); + const unsigned count = indexed ? 1 + symbol.index_mask / 32 : 1; + analysis.binding(i, s, base, 4, kind, bytes); + auto it = std::find_if(analysis.result.bindings.begin(), analysis.result.bindings.end(), [&](const auto &b) { + return !b.array_position && b.array_count == count && b.kind == kind && b.root_parameter == s[base].value && + b.byte_offset == s[base].offset; + }); + if (it == analysis.result.bindings.end()) + throw std::logic_error("missing direct binding"); + if (bound_register) *bound_register = it->shader_register; + const bool raw = kind == ComputeViewKind::raw_buffer_uav || kind == ComputeViewKind::buffer_srv || + kind == ComputeViewKind::raw_vector_srv || kind == ComputeViewKind::byte_window_srv || + kind == ComputeViewKind::indexed_atomic_uav; + const bool half = kind == ComputeViewKind::half_buffer_uav; + const unsigned width = kind == ComputeViewKind::typed_buffer_srv ? 4 : bytes / (half ? 2 : 4); + if (raw) + ir.features |= 16; + return ir.handle({unsigned(compute_uav(kind)), it->shader_register, raw ? 11u : 10u, + raw ? 0u + : half ? 9u + : 5u, + raw ? 0u : width, 0, count}, + indexed && count > 1 ? read(base) : ""); + } + string load_buffer(const string &h, const string &addr, bool raw, unsigned count) { + using Arg = std::pair; + std::vector args{{"%dx.types.Handle", h}, {"i32", addr}, {"i32", "undef"}}; + if (raw) { + args.emplace_back("i8", to_string((1u << count) - 1)); + args.emplace_back("i32", "4"); + } + return ir.invoke("%dx.types.ResRet.i32", raw ? "rawBufferLoad.i32" : "bufferLoad.i32", raw ? 139 : 68, args, + "nounwind readonly"); + } + void buffer_atomic(const Inst &i, const State &s) { + // The operation set and VGPR ordering follow gfx2hlsl.MUBUF_ATOMIC_OPS. + static const std::map operations{ + {"buffer_atomic_add", 0}, {"buffer_atomic_sub", 0}, {"buffer_atomic_and", 1}, {"buffer_atomic_or", 2}, + {"buffer_atomic_xor", 3}, {"buffer_atomic_smin", 4}, {"buffer_atomic_smax", 5}, {"buffer_atomic_umin", 6}, + {"buffer_atomic_umax", 7}, {"buffer_atomic_swap", 8}}; + const bool exchange = i.name == "buffer_atomic_cmpswap"; + const auto op = operations.find(i.name); + if ((!exchange && op == operations.end()) || (exchange && i.dst == 255)) + refuse(i.pc, "unsupported buffer atomic width or operation"); + const unsigned data = 256 + i.dst; + const bool indexed = (i.a & 0x2000) != 0; + unsigned reg; + auto h = resource(i, s, ((i.b >> 16) & 31) * 4, + indexed ? ComputeViewKind::indexed_atomic_uav : ComputeViewKind::raw_buffer_uav, 4, ®); + string address, in_range; + if (indexed) { + // b(1 + uav register) is filled from the exact recorded buffer view. + // Test the element count before multiplication to reject wrapped indices. + auto cb = ir.handle({2, reg + 1, 13, 0, 0, 16}); + auto shape = ir.invoke("%dx.types.CBufRet.i32", "cbufferLoadLegacy.i32", 59, + {{"%dx.types.Handle", cb}, {"i32", "0"}}, "nounwind readonly"); + auto stride = ir.value("extractvalue %dx.types.CBufRet.i32 " + shape + ", 0"); + auto count = ir.value("extractvalue %dx.types.CBufRet.i32 " + shape + ", 1"); + auto index = read(256 + (i.b & 255)); + in_range = cmp("ult", index, count); + address = ir.binary("mul", index, stride); + } else { + address = ir.binary("add", operand32(i, i.b >> 24), to_string(i.a & 4095)); + if (i.a & 0x1000) + address = ir.binary("add", address, read(256 + (i.b & 255))); + } + address = ir.binary("and", address, "4294967292"); + auto value = read(data); + if (i.name == "buffer_atomic_sub") + value = ir.binary("sub", "0", value); + std::vector> args{{"%dx.types.Handle", h}}; + if (!exchange) + args.emplace_back("i32", to_string(op->second)); + args.emplace_back("i32", address); + args.emplace_back("i32", "undef"); + args.emplace_back("i32", "undef"); + if (exchange) + args.emplace_back("i32", read(data + 1)); + args.emplace_back("i32", value); + auto tag = to_string(label_number++), pred = active(); + if (indexed) { + if (i.a & 0x4000) { + auto out_of_range = ir.value("and i1 " + pred + ", " + ir.value("xor i1 " + in_range + ", true")); + write(data, select(out_of_range, "0", read(data))); + } + pred = ir.value("and i1 " + pred + ", " + in_range); + } + ir.body << " br i1 " << pred << ", label %atomic" << tag << ", label %atomicEnd" << tag << "\natomic" << tag + << ":\n"; + auto previous = ir.invoke("i32", exchange ? "atomicCompareExchange.i32" : "atomicBinOp.i32", exchange ? 79 : 78, + args, "nounwind"); + if (i.a & 0x4000) + write(data, previous); + ir.body << " br label %atomicEnd" << tag << "\natomicEnd" << tag << ":\n"; + } + #include "gfx1013_compute_mtbuf.inl" + + // global_load_dword in the saddr form (#2962): ADDR = SADDR + zext(VADDR) + sext(OFFSET[11:0]) (RDNA 2 ISA, + // FLAT/GLOBAL addressing), with SADDR the unadvanced root address of a root SRV, as for the scalar root loads. + // The byte offset zext(VADDR) + OFFSET is guarded to [0, 2^32) before it becomes a 32-bit view offset, so a + // wrapped address reads zero instead of an in-bounds word (gfx2hlsl.py op_global_load_dword). The low two + // address bits are dropped, as for buffer_load_dword in this path (DWORD alignment mode). + void global_load(const Inst &i, const State &s) { + const unsigned base = (i.b >> 16) & 127; + if (base > 104 || (base & 1)) + refuse(i.pc, "global load base must be an aligned SGPR pair"); + const auto &low = s.at(base); + if (low.type != Symbol::Type::root_address) + refuse(i.pc, "global load base is not a root buffer address"); + const Symbol high{Symbol::Type::root_address, low.value, 1}; + if (low.offset || !(s.at(base + 1) == high)) + refuse(i.pc, "global load base is an advanced or mismatched root address"); + const int offset = int(Word(i.a) << 20) >> 20; + if (offset % 4) + refuse(i.pc, "global load at an unaligned immediate offset"); + const unsigned span = offset > 0 ? unsigned(offset) + 4 : 4; + auto &bindings = analysis.result.bindings; + auto binding = std::find_if(bindings.begin(), bindings.end(), [&](const auto &b) { + return b.kind == ComputeViewKind::root_buffer_srv && b.root_parameter == low.value; + }); + if (binding == bindings.end()) { + bindings.push_back({ComputeViewKind::root_buffer_srv, low.value, 0, analysis.srv++, span}); + binding = std::prev(bindings.end()); + } else + binding->required_bytes = (std::max)(binding->required_bytes, span); + ir.features |= 16; + const auto h = ir.handle({0, binding->shader_register, 11}); + const auto vaddr = read(256 + (i.b & 255)); + string in_range, addr = vaddr; + if (offset > 0) { + in_range = cmp("ule", vaddr, to_string(0xffffffffu - unsigned(offset))); + addr = ir.binary("add", vaddr, to_string(offset)); + } else if (offset < 0) { + in_range = cmp("uge", vaddr, to_string(-offset)); + addr = ir.binary("sub", vaddr, to_string(-offset)); + } + addr = ir.binary("and", addr, "4294967292"); + const auto ret = load_buffer(h, addr, true, 1); + auto value = ir.value("extractvalue %dx.types.ResRet.i32 " + ret + ", 0"); + if (!in_range.empty()) + value = ir.value("select i1 " + in_range + ", i32 " + value + ", i32 0"); + vector_write(256 + i.dst, value); + } + void memory(const Inst &i, const State &s) { + if (i.name == "global_load_dword") { + global_load(i, s); + return; + } + if (i.enc == Encoding::Mubuf && i.name.substr(0, 8) == "tbuffer_") { + formatted_byte_load(i, s); + return; + } + if (i.enc == Encoding::Mubuf && i.name.substr(0, 14) == "buffer_atomic_") { + buffer_atomic(i, s); + return; + } + if (i.enc == Encoding::Smem) { + unsigned so = i.b >> 25; + const auto &low = s.at(i.src[0]); + const bool root = low.type == Symbol::Type::root_address; + if (!root && low.type == Symbol::Type::table && low.value == compute_resource_heap) { + // Reads from the whole descriptor heap: only the indexed descriptor load of a captured raw buffer slot. + if (i.op >= 8) + refuse(i.pc, "scalar buffer load from the descriptor heap is not translated"); + refuse_heap_contract(i.pc); + if (so == 125) + refuse(i.pc, "heap descriptor load needs a GPU-selected index (SGPR offset)"); + // The captured selection names the slot the GPU data selects; a constant index or an immediate offset + // would address another slot than the one the guard checked. + if (s.at(so).type == Symbol::Type::constant) + refuse(i.pc, "heap descriptor index is a constant; the captured selection must come from GPU data"); + if (i.b & 0xfffff) + refuse(i.pc, "heap descriptor load with an immediate offset addresses another slot than the captured selection"); + } + if (i.op < 8 && !root) { + if (s.at(i.src[0]).type != Symbol::Type::table || + s.at(i.src[0] + 1).type != Symbol::Type::constant || s.at(i.src[0] + 1).value != 0) + refuse(i.pc, "direct descriptor address outside bound table"); + if (so != 125) { + if (i.op != 2 || so > 105) + refuse(i.pc, "direct indexed descriptor load shape"); + auto index = ir.binary("lshr", operand32(i, so), "5"); + for (unsigned j = 0; j < 4; ++j) + write(i.dst + j, index); + } + return; // The CFG transfer already associated every destination word with its table slot. + } + unsigned off = i.b & 0xfffff, n = memory_count(i); + string h; + if (root) { + const Symbol high{Symbol::Type::root_address, low.value, 1}; + if (low.offset || !(s.at(i.src[0] + 1) == high)) + refuse(i.pc, "mismatched root address high half"); + // Like Victory's Source::Built, retain the root identity through + // SGPR copies. Scalar buffer loads read dwords at byte offsets. + // Accept a finite byte bound or the unbounded NUM_RECORDS form + // only for this verified zero-stride, byte-address V# layout. + const bool built = i.op >= 8; + if (built && (s.at(i.src[0] + 2).type != Symbol::Type::constant || + !(s.at(i.src[0] + 3) == Symbol{Symbol::Type::constant, 0x31016fac}))) + refuse(i.pc, "unsupported synthesized scalar buffer descriptor fields"); + unsigned span = off + 4 * n; + if (off % 4 || span > 65536 || i.dst + n > 106) + refuse(i.pc, "unsupported root descriptor load range"); + if (so != 125) { + const auto &index = s.at(so); + if ((index.type != Symbol::Type::masked && index.type != Symbol::Type::constant) || + (index.value & 3) || index.value > 65536 - span) + refuse(i.pc, "unbounded or unaligned root descriptor index"); + span += index.value; + } + if (built && span > s.at(i.src[0] + 2).value) + refuse(i.pc, "scalar load exceeds synthesized descriptor byte bound"); + auto &bindings = analysis.result.bindings; + auto binding = std::find_if(bindings.begin(), bindings.end(), [&](const auto &b) { + return b.kind == ComputeViewKind::root_buffer_srv && b.root_parameter == low.value; + }); + if (binding == bindings.end()) { + bindings.push_back({ComputeViewKind::root_buffer_srv, low.value, 0, analysis.srv++, span}); + binding = std::prev(bindings.end()); + } else + binding->required_bytes = (std::max)(binding->required_bytes, span); + ir.features |= 16; + h = ir.handle({0, binding->shader_register, 11}); + } else + h = resource(i, s, i.src[0], ComputeViewKind::buffer_srv, so == 125 ? off + 4 * n : 4); + auto addr = so == 125 ? to_string(off) + : ir.binary("and", ir.binary("add", operand32(i, so), to_string(off)), "4294967292"); + for (unsigned j = 0; j < n; j += 4) { + unsigned width = (std::min)(4u, n - j); + auto chunk = so == 125 ? to_string(off + j * 4) : + j ? ir.binary("add", addr, to_string(j * 4)) : addr; + auto ret = load_buffer(h, chunk, true, width); + for (unsigned k = 0; k < width; ++k) + write(i.dst + j + k, ir.value("extractvalue %dx.types.ResRet.i32 " + ret + ", " + to_string(k))); + } + return; + } + bool store = i.name == "buffer_store_raw" || i.name == "buffer_store_format"; + bool raw = i.name == "buffer_load_dword" || i.name == "buffer_store_raw"; + bool half = i.name == "buffer_store_format" && (i.op & 128); + constexpr unsigned widths[]{1, 2, 4, 3}; + unsigned n = raw ? widths[i.op & 3] : (i.op & 3) + 1, data = 256 + i.dst; + if (i.dst + (half ? (n + 1) / 2 : n) > 256) + refuse(i.pc, "direct buffer data overflow"); + auto kind = store ? (raw ? ComputeViewKind::raw_buffer_uav + : half ? ComputeViewKind::half_buffer_uav + : ComputeViewKind::typed_buffer_uav) + : raw && s.at(((i.b >> 16) & 31) * 4 + 1).type == Symbol::Type::zero_stride_word + ? ComputeViewKind::byte_window_srv + : raw ? ComputeViewKind::raw_vector_srv + : ComputeViewKind::typed_buffer_srv; + auto h = resource(i, s, ((i.b >> 16) & 31) * 4, kind, raw ? 4 : n * (half ? 2 : 4)); + auto addr = (i.a & (raw ? 0x1000 : 0x2000)) ? read(256 + (i.b & 255)) : "0"; + if (raw) { + addr = ir.binary("add", addr, to_string(i.a & 4095)); + addr = ir.binary("and", ir.binary("add", addr, operand32(i, i.b >> 24)), "4294967292"); + } + if (!store) { + auto ret = load_buffer(h, addr, raw, n); + for (unsigned k = 0; k < n; ++k) + vector_write(data + k, ir.value("extractvalue %dx.types.ResRet.i32 " + ret + ", " + to_string(k))); + return; + } + const string tag = to_string(label_number++), pred = active(); + if (!graphics_input) + ir.body << " br i1 " << pred << ", label %store" << tag << ", label %after" << tag << "\nstore" << tag + << ":\n"; + std::vector> args{{"%dx.types.Handle", h}, {"i32", addr}, {"i32", "undef"}}; + for (unsigned j = 0; j < 4; ++j) { + string value = "undef"; + if (j < n || !raw) { + const unsigned component = (std::min)(j, n - 1); + value = read(data + (half ? component / 2 : component)); + if (half) { + if (component % 2) + value = ir.binary("lshr", value, "16"); + value = ir.invoke("float", "legacyF16ToF32", 131, {{"i32", value}}, "nounwind readnone"); + } + } + args.emplace_back(half ? "float" : "i32", value); + } + args.emplace_back("i8", to_string(raw ? (1u << n) - 1 : 15)); + if (raw) + args.emplace_back("i32", "4"); + ir.invoke("void", + raw ? "rawBufferStore.i32" + : half ? "bufferStore.f32" + : "bufferStore.i32", + raw ? 140 : 69, args, "nounwind"); + if (!graphics_input) + ir.body << " br label %after" << tag << "\nafter" << tag << ":\n"; + } + string select_float(const string &condition, const string &yes, const string &no) { + return ir.value("select i1 " + condition + ", float " + yes + ", float " + no); + } + // Invert the cube projection. Each pair of faces has a common major + // axis, with the negative face second. The two minor axes span [-1,1]. + std::array cube_axes(const string &face, const string &u, const string &v, bool tangent) { + const auto nu = ir.value("fsub float -0.0, " + u), nv = ir.value("fsub float -0.0, " + v); + const auto axis = ir.binary("lshr", ir.binary("and", face, "7"), "1"); + const auto is_x = cmp("eq", axis, "0"), is_y = cmp("eq", axis, "1"); + const auto negative = cmp("ne", ir.binary("and", face, "1"), "0"); + const auto major = tangent ? "0.0" : select_float(negative, "-1.0", "1.0"); + return {select_float(is_x, major, select_float(is_y, u, select_float(negative, nu, u))), + select_float(is_y, major, nv), + select_float(is_x, select_float(negative, u, nu), select_float(is_y, select_float(negative, nv, v), major))}; + } + void image_io(const Inst &i, const State &s) { + const bool bias = i.op == 37, gradient = i.op == 34, query = i.op == 96, dimensions = i.op == 14; + // image_gather4_c_lz (79) is the comparison gather at the view's first mip (#2969): DXIL textureGatherCmp. + const bool compare_gather = i.op == 79; + const bool compare = i.op == 40 || i.op == 47 || compare_gather; + const bool implicit = i.op == 32 || i.op == 40 || bias || query || i.op == 64; + if (implicit && !pixel_stage) + refuse(i.pc, "implicit derivatives require a pixel stage"); + const bool gather = i.op == 64 || i.op == 71 || compare_gather; + const bool sample = (!gather && implicit) || (compare && !gather) || gradient || i.op == 39 || i.op == 36, + store = i.op == 8, + half = store && (i.b >> 31); + const bool lod = i.op == 1 || i.op == 36; + const unsigned mask = (i.a >> 8) & 15, addr = i.b & 255, base = ((i.b >> 16) & 31) * 4, dim = (i.a >> 3) & 7; + constexpr unsigned dx_kind[]{1, 2, 4, 5, 6, 7, 3, 8}; + constexpr unsigned coord_count[]{1, 2, 3, 3, 2, 3, 2, 3}; + const unsigned coords = coord_count[dim]; + if ((i.op != 0 && i.op != 1 && !store && !sample && !gather && !dimensions) || !mask || (i.a & 0x3e0c0u) || + (i.b & 0x3e000000u) || (gather && ((mask & (mask - 1)) || (dim != 1 && dim != 3 && dim != 5))) || + (query && ((dim != 1 && dim != 3) || (mask & ~3u))) || + (compare && (mask != 1 || (dim != 1 && dim != 3 && dim != 5) || (i.a & 0x1000u))) || + (compare_gather && dim == 3) || + ((sample || gather) && (i.a & 0x1000u) && gradient) || + (dimensions && (dim == 4 || dim >= 6 || (i.b & 0x40000000u))) || + (store && !half && mask != 15) || (half && mask != 1 && mask != 3 && mask != 15) || + s.at(base).type != Symbol::Type::descriptor) + refuse(i.pc, "direct image opcode or descriptor modifiers"); + if ((dim == 3 && ((!sample && !gather && !dimensions) || (i.a & 0x1000u))) || + (dim >= 6 && (sample || gather || store || lod))) + refuse(i.pc, "unsupported cube or multisample operation"); + const bool d16_sample = !store && (i.b >> 31); + const unsigned channels = half && mask == 1 ? 1 : half && mask == 3 ? 2 : 4; + const bool cube_sample = dim == 3 && (sample || gather); + const auto kind = half ? (channels == 1 ? ComputeViewKind::half_scalar_uav : + channels == 2 ? ComputeViewKind::half2_texture_uav : ComputeViewKind::half4_texture_uav) + : store ? ComputeViewKind::texture_uav + : cube_sample ? (compare ? ComputeViewKind::cube_comparison_srv : ComputeViewKind::cube_sample_srv) + : d16_sample ? ComputeViewKind::d16_sample_srv + : compare ? ComputeViewKind::comparison_texture_srv + : ComputeViewKind::texture_srv; + analysis.binding(i, s, base, 8, kind, 0, dim); + const auto &bs = analysis.result.bindings; + auto it = std::find_if(bs.begin(), bs.end(), [&](const auto &b) { + return !b.array_position && b.image_dimension == dim && b.kind == kind && + b.root_parameter == s[base].value && b.byte_offset == s[base].offset; + }); + if (it == bs.end()) + throw std::logic_error("missing image binding"); + auto h = ir.handle({unsigned(store), it->shader_register, cube_sample ? 9u : dx_kind[dim], 9, compare ? 1u : channels, 0}); + auto coordinate = [&](unsigned j) { + unsigned r = addr + j; + if (j && (i.a & 6)) { + const unsigned word_index = (j - 1) / 4; + if (word_index >= ((i.a >> 1) & 3)) + refuse(i.pc, "incomplete image NSA address list"); + r = (i.image_address_words[word_index] >> (8 * ((j - 1) % 4))) & 255; + } + if (r > 255) + refuse(i.pc, "image coordinate register overflow"); + return read(256 + r); + }; + auto texture_dimensions = [&](const string &mip) { + return ir.invoke("%dx.types.Dimensions", "getDimensions", 72, + {{"%dx.types.Handle", h}, {"i32", mip}}, "nounwind readonly"); + }; + if (dimensions) { + auto info = texture_dimensions(coordinate(0)); + unsigned dst = i.dst; + for (unsigned ch = 0; ch < 4; ++ch) { + if (!(mask & (1u << ch))) continue; + if (dst > 255) refuse(i.pc, "image destination overflow"); + auto value = ch == 3 || ch < (dim == 3 ? 2 : coords) ? ir.value("extractvalue %dx.types.Dimensions " + info + ", " + to_string(ch)) : "1"; + vector_write(256 + dst++, value); + } + return; + } + std::array c{"undef", "undef", "undef", "undef"}; + string level = "0"; + const unsigned spatial = coords - unsigned(dim == 3 || dim == 4 || dim == 5); + const bool a16 = (i.b & 0x40000000u) != 0; + if (a16) { + if (dim != 1 || lod || (i.a & 6) || (sample && i.op != 32 && i.op != 39) || gather || (store && !half)) + refuse(i.pc, "packed image addressing"); + auto packed = coordinate(0); + c[0] = ir.binary("and", packed, "65535"); + c[1] = ir.binary("lshr", packed, "16"); + } else { + for (unsigned j = 0; j < coords; ++j) + c[j] = coordinate(j + unsigned(bias || compare) + (gradient ? 2 * spatial : 0)); + if (bias || compare) + level = coordinate(0); + if (lod || dim >= 6) + level = coordinate(coords); + } + if (!store) { + string r; + if (sample || gather) { + auto sampler_reg = analysis.sampler_index(i, s, sample || implicit, i.op == 71 || compare_gather, + implicit || gradient, compare); + if (i.op == 64 && (analysis.result.samplers.at(sampler_reg - analysis.first_sampler).words[1] & 0xffffff)) + refuse(i.pc, "implicit gather requires a sampler fixed to mip zero"); + auto sampler = ir.handle({3, sampler_reg, 14, 0, 0, 0, 1, compare}); + using Arg = std::pair; + std::vector args{{"%dx.types.Handle", h}, {"%dx.types.Handle", sampler}}; + const auto size = (i.a & 0x1000u) ? texture_dimensions("0") : string{}; + for (unsigned j = 0; j < coords; ++j) { + c[j] = a16 ? ir.invoke("float", "legacyF16ToF32", 131, {{"i32", c[j]}}, "nounwind readnone") : + ir.value("bitcast i32 " + c[j] + " to float"); + if (!size.empty() && j < spatial) { + auto extent = ir.value("extractvalue %dx.types.Dimensions " + size + ", " + to_string(j)); + auto scale = ir.value("uitofp i32 " + extent + " to float"); + c[j] = ir.value("fdiv float " + c[j] + ", " + scale); + } + } + string face; + if (dim == 3) { + // GFX packs face + 8 * layer. Desktop cube arrays take a + // direction plus the layer relative to the bound view. + face = ir.value("fptosi float " + c[2] + " to i32"); + auto projected = [&](const string &a) { + return ir.value("fsub float " + ir.value("fmul float " + a + ", 2.0") + ", 3.0"); + }; + auto direction = cube_axes(face, projected(c[0]), projected(c[1]), false); + std::copy(direction.begin(), direction.end(), c.begin()); + c[3] = ir.value("sitofp i32 " + ir.binary("ashr", face, "3") + " to float"); + } + if (query) { + for (unsigned j = 0; j < 3; ++j) + args.emplace_back("float", c[j]); + args.emplace_back("i1", "true"); + unsigned dst = i.dst; + for (unsigned ch = 0; ch < 2; ++ch) { + if (!(mask & (1u << ch))) continue; + if (dst > 255) refuse(i.pc, "image destination overflow"); + args.back().second = ch ? "false" : "true"; + auto result = ir.invoke("float", "calculateLOD.f32", 81, args, "nounwind readonly"); + vector_write(256 + dst++, ir.value("bitcast float " + result + " to i32")); + } + return; + } + for (unsigned j = 0; j < 4; ++j) + args.emplace_back("float", c[j]); + const unsigned offsets = dim == 3 ? 0 : spatial; + for (unsigned j = 0; j < (sample ? 3u : 2u); ++j) + args.emplace_back("i32", j < offsets ? "0" : "undef"); + if (gather) { + unsigned channel = 0; + while (!(mask & (1u << channel))) ++channel; + args.emplace_back("i32", to_string(channel)); + // textureGatherCmp takes the reference after the channel; the comparison reads red. + if (compare_gather) + args.emplace_back("float", ir.value("bitcast i32 " + level + " to float")); + } else if (compare) { + args.emplace_back("float", ir.value("bitcast i32 " + level + " to float")); + if (implicit) + args.emplace_back("float", "undef"); + } else if (gradient) { + // Victory emit/lower.rs: d/dx and then d/dy of spatial + // coordinates precede the coordinates, excluding array slices. + for (unsigned axis = 0; axis < 2; ++axis) { + std::array d{"undef", "undef", "undef"}; + for (unsigned j = 0; j < spatial; ++j) + d[j] = ir.value("bitcast i32 " + coordinate(axis * spatial + j) + " to float"); + if (dim == 3) + d = cube_axes(face, ir.value("fmul float " + d[0] + ", 2.0"), + ir.value("fmul float " + d[1] + ", 2.0"), true); + for (const auto &component : d) args.emplace_back("float", component); + } + args.emplace_back("float", "undef"); + } else if (implicit) { + if (bias) + args.emplace_back("float", ir.value("bitcast i32 " + level + " to float")); + args.emplace_back("float", "undef"); // no per-instruction minimum LOD clamp + } else + args.emplace_back("float", lod ? ir.value("bitcast i32 " + level + " to float") : "0.0"); + const char *method = compare_gather ? "textureGatherCmp.f32" : + compare ? (implicit ? "sampleCmp.f32" : "sampleCmpLevelZero.f32") : + gather ? "textureGather.f32" : gradient ? "sampleGrad.f32" : + bias ? "sampleBias.f32" : implicit ? "sample.f32" : "sampleLevel.f32"; + const unsigned opcode = compare_gather ? 74 : compare ? (implicit ? 64 : 65) : gather ? 73 : + gradient ? 63 : bias ? 61 : implicit ? 60 : 62; + r = ir.invoke("%dx.types.ResRet.f32", method, opcode, args, "nounwind readonly"); + } else + r = ir.invoke("%dx.types.ResRet.f32", "textureLoad.f32", 66, + {{"%dx.types.Handle", h}, + {"i32", level}, + {"i32", c[0]}, + {"i32", c[1]}, + {"i32", c[2]}, + {"i32", "undef"}, + {"i32", "undef"}, + {"i32", "undef"}}, + "nounwind readonly"); + unsigned dst = i.dst; + string pending_half; + for (unsigned c = 0; c < 4; ++c) + if (gather || (mask & (1u << c))) { + if (dst > 255) + refuse(i.pc, "image destination overflow"); + auto value = ir.value("extractvalue %dx.types.ResRet.f32 " + r + ", " + to_string(c)); + auto bits = ir.value("bitcast float " + value + " to i32"); + if (d16_sample) { + bits = packed_half_rne(bits); + if (pending_half.empty()) { + pending_half = bits; + continue; + } + bits = ir.binary("or", pending_half, ir.binary("shl", bits, "16")); + pending_half.clear(); + } + vector_write(256 + dst++, bits); + } + if (!pending_half.empty()) vector_write(256 + dst, pending_half); + } else { + if (i.dst + (half ? (channels + 1) / 2 : channels) > 256) + refuse(i.pc, "image data overflow"); + string label = to_string(label_number++), pred = active(); + if (!graphics_input) + ir.body << " br i1 " << pred << ", label %img" << label << ", label %imgover" << label << "\nimg" << label + << ":\n"; + std::vector> args{ + {"%dx.types.Handle", h}, {"i32", c[0]}, {"i32", c[1]}, {"i32", c[2]}}; + std::array values; + string packed; + for (unsigned c = 0; c < channels; ++c) { + if (half) { + if (!(c & 1)) packed = read(256 + i.dst + c / 2); + const auto bits = c & 1 ? ir.binary("lshr", packed, "16") : packed; + values[c] = ir.invoke("float", "legacyF16ToF32", 131, {{"i32", bits}}, "nounwind readnone"); + } else + values[c] = ir.value("bitcast i32 " + read(256 + i.dst + c) + " to float"); + } + // DXIL typed stores use a full write mask; narrower views ignore the tail. + for (unsigned c = 0; c < 4; ++c) + args.emplace_back("float", values[(std::min)(c, channels - 1)]); + args.emplace_back("i8", "15"); + ir.invoke("void", "textureStore.f32", 67, args, "nounwind"); + if (!graphics_input) + ir.body << " br label %imgover" << label << "\nimgover" << label << ":\n"; + } + } + void local_memory(const Inst &i, unsigned words) { + const auto op = decode_local_data(i.a, i.b); + // The host executes a guest wave64 on two wave32s. Meet before + // each operation, outside its lane predicate, as in Victory split_lds. + if (wave64) + barrier(); + const auto label = to_string(label_number++); + auto enabled = active(); + ir.body << " br i1 " << enabled << ", label %ds" << label << ", label %dsDone" << label << "\nds" << label + << ":\n"; + const auto address = read(256 + op.address); + for (unsigned j = 0; j < op.count; ++j) { + auto index = ir.binary("lshr", ir.binary("add", address, to_string(op.byte_offset(j))), "2"); + auto ptr = shared_address("lds", words, index); + if (op.read) + write(256 + op.destination + j, ir.value("load i32, i32 addrspace(3)* " + ptr + ", align 4")); + else { + auto data = read(256 + op.data_register(j)); + if (op.atomic_ir) { + if (op.subtract) + data = ir.binary("sub", "0", data); + auto old = ir.value(string("atomicrmw ") + op.atomic_ir + " i32 addrspace(3)* " + ptr + + ", i32 " + data + " monotonic"); + if (op.return_old) + write(256 + op.destination, old); + } else + ir.body << " store i32 " << data << ", i32 addrspace(3)* " << ptr << ", align 4\n"; + } + } + ir.body << " br label %dsDone" << label << "\ndsDone" << label << ":\n"; + } + string shift(const string &op, const string &a, const string &b) { + return ir.binary(op, a, ir.binary("and", b, "31")); + } + string subword(const string &value, unsigned sel, bool sign) { + if (sel == 6) + return value; + unsigned width = sel < 4 ? 8 : 16, bit = sel < 4 ? 8 * sel : 16 * (sel - 4); + auto slice = ir.binary("lshr", value, to_string(bit)); + if (!sign) + return ir.binary("and", slice, to_string((1u << width) - 1)); + auto left = ir.binary("shl", slice, to_string(32 - width)); + return ir.binary("ashr", left, to_string(32 - width)); + } + string place_subword(const Inst &i, const string &value) { + if (i.dst_select == 6) + return value; + unsigned sel = i.dst_select, width = sel < 4 ? 8 : 16, bit = sel < 4 ? 8 * sel : 16 * (sel - 4); + Word mask = (1u << width) - 1; + string result = subword(value, sel < 4 ? 0 : 4, i.dst_unused == 1); + if (bit) + result = ir.binary("shl", result, to_string(bit)); + if (i.dst_unused == 2) + result = ir.binary("or", result, ir.binary("and", read(i.dst), to_string(~(mask << bit)))); + return result; + } + string cube_alu(Name op, const string &x, const string &y, const string &z) { + auto magnitude = [&](const string &v) { + return ir.invoke("float", "unary.f32", 6, {{"float", v}}, "nounwind readnone"); + }; + auto at_least = [&](const string &a, const string &b) { return ir.value("fcmp oge float " + a + ", " + b); }; + auto negative = [&](const string &a) { return ir.value("fcmp olt float " + a + ", 0.0"); }; + auto negate = [&](const string &a) { return ir.value("fsub float -0.0, " + a); }; + const auto ax = magnitude(x), ay = magnitude(y), az = magnitude(z); + // The tie order is Z, Y, X, as in pixel_aot's cube lowering. + const auto major_z = ir.value("and i1 " + at_least(az, ax) + ", " + at_least(az, ay)); + const auto major_y = at_least(ay, ax); + auto axis = [&](const string &xf, const string &yf, const string &zf) { + return select_float(major_z, zf, select_float(major_y, yf, xf)); + }; + if (op == "v_cubeid_f32") + return axis(select_float(negative(x), "1.0", "0.0"), select_float(negative(y), "3.0", "2.0"), + select_float(negative(z), "5.0", "4.0")); + if (op == "v_cubesc_f32") + return axis(select_float(negative(x), z, negate(z)), x, select_float(negative(z), negate(x), x)); + if (op == "v_cubetc_f32") { + const auto ny = negate(y); + return axis(ny, select_float(negative(y), negate(z), z), ny); + } + return ir.value("fmul float " + axis(x, y, z) + ", 2.0"); + } + string packed_half_rne(const string &bits) { + // Round the integer significand to nearest even. Some desktop + // implementations truncate legacyF32ToF16 (Victory 9376fd6, + // emit/lower.rs::f16_nearest). This also preserves subnormals. + const auto sign = ir.binary("and", ir.binary("lshr", bits, "16"), "32768"); + const auto mag = ir.binary("and", bits, "2147483647"); + const auto exp = ir.binary("lshr", mag, "23"); + const auto frac = ir.binary("and", mag, "8388607"); + auto round_shift = [&](const string &v, const string &shift, const string &half) { + const auto odd = ir.binary("and", ir.binary("lshr", v, shift), "1"); + const auto bias = ir.binary("add", ir.binary("sub", half, "1"), odd); + return ir.binary("lshr", ir.binary("add", v, bias), shift); + }; + const auto normal = round_shift(ir.binary("sub", mag, "939524096"), "13", "4096"); + const auto sub_range = ir.value("and i1 " + cmp("uge", exp, "102") + ", " + cmp("ule", exp, "112")); + const auto shift = select(sub_range, ir.binary("sub", "126", exp), "14"); + const auto half = ir.binary("shl", "1", ir.binary("sub", shift, "1")); + const auto sub = round_shift(ir.binary("or", frac, "8388608"), shift, half); + auto h = select(cmp("ule", exp, "112"), select(sub_range, sub, "0"), normal); + h = select(cmp("ugt", exp, "142"), "31744", h); + const auto nan = cmp("ugt", mag, "2139095040"); + h = select(nan, ir.binary("or", ir.binary("lshr", frac, "13"), "32256"), h); + return ir.binary("or", h, sign); + } + bool float_alu(const Inst &i, const string *permuted = nullptr) { + auto n = i.name; + if ((i.subword || (!i.wide && !i.dpp_control && !permuted)) && + (n == "v_cvt_f16_f32" || n == "v_cvt_f32_f16")) { + if (i.scale || i.clamp || i.src_sext[0]) + refuse(i.pc, "unsupported SDWA half conversion modifier"); + string bits = operand32(i, i.src[0]); + if (i.subword) bits = subword(bits, i.src_select[0], false); + const bool narrow = n == "v_cvt_f16_f32"; + if (i.abs) bits = ir.binary("and", bits, narrow ? "2147483647" : "32767"); + if (i.neg) bits = ir.binary("xor", bits, narrow ? "2147483648" : "32768"); + if (narrow) { + bits = packed_half_rne(bits); + if (!i.subword) bits = ir.binary("or", bits, ir.binary("and", read(i.dst), "4294901760")); + } else { + auto f = ir.invoke("float", "legacyF16ToF32", 131, {{"i32",bits}}, "nounwind readnone"); + bits = ir.value("bitcast float " + f + " to i32"); + } + vector_write(i.dst, place_subword(i, bits)); + return true; + } + if (n == "v_pack_b32_f16") { + // VOP3 only: D[15:0] = S0.f16, D[31:16] = S1.f16. Every step is an + // integer bit operation so signed zeros and NaN payloads survive. + // Unsupported forms: clamp, omod, a destination or third-source + // op_sel bit, third-source abs/neg, inline constants, literals, + // SDWA and DPP. They are refused rather than approximated. + if (!i.wide || i.enc != Encoding::Vop3 || i.subword || i.dpp_control || permuted) + refuse(i.pc, "v_pack_b32_f16 requires the VOP3 encoding"); + if (i.clamp || i.scale) + refuse(i.pc, "unsupported v_pack_b32_f16 clamp or omod"); + if ((i.a & 0x6000) || ((i.abs | i.neg) & 4)) + refuse(i.pc, "unsupported v_pack_b32_f16 destination or third-source modifier"); + auto half = [&](unsigned j) { + const unsigned r = i.src[j]; + if (r >= 128 && r < 256) + refuse(i.pc, "unsupported v_pack_b32_f16 constant source"); + auto bits = operand32(i, r); + if ((i.a >> (11 + j)) & 1) bits = ir.binary("lshr", bits, "16"); + bits = ir.binary("and", bits, "65535"); + // Clear the sign for abs first, then toggle it for neg. + if (i.abs & (1u << j)) bits = ir.binary("and", bits, "32767"); + if (i.neg & (1u << j)) bits = ir.binary("xor", bits, "32768"); + return bits; + }; + auto low = half(0), high = half(1); + vector_write(i.dst, ir.binary("or", low, ir.binary("shl", high, "16"))); + return true; + } + if (n == "v_cvt_pkrtz_f16_f32") { + if (i.clamp || i.scale || i.subword || (i.wide && (i.a & 0x7800))) + refuse(i.pc, "unsupported packed half conversion modifier"); + auto pack = [&](unsigned j) { + auto bits = operand32(i, i.src[j]); + if (i.abs & (1u << j)) bits = ir.binary("and", bits, "2147483647"); + if (i.neg & (1u << j)) bits = ir.binary("xor", bits, "2147483648"); + auto f = ir.value("bitcast i32 " + bits + " to float"); + auto h = ir.invoke("i32", "legacyF32ToF16", 130, {{"float",f}}, "nounwind readnone"); + auto mag = ir.binary("and", h, "32767"); + auto back = ir.invoke("float", "legacyF16ToF32", 131, {{"i32",mag}}, "nounwind readnone"); + auto abs = ir.value("bitcast i32 " + ir.binary("and", bits, "2147483647") + " to float"); + auto rounded_up = ir.value("fcmp ogt float " + back + ", " + abs); + return ir.binary("and", ir.binary("sub", h, ir.value("zext i1 " + rounded_up + " to i32")), "65535"); + }; + auto low = pack(0), high = pack(1); + vector_write(i.dst, ir.binary("or", low, ir.binary("shl", high, "16"))); + return true; + } + if (n == "v_add_f16" || n == "v_sub_f16" || n == "v_subrev_f16" || n == "v_mul_f16") { + // The graphics frontend shares this ALU. Leave those programs on the + // existing refusal; this lowering is the direct compute path. + if (graphics_input) + return false; + if (i.dpp_control || permuted) + refuse(i.pc, "unsupported " + string(n) + " DPP form"); + if (i.clamp || i.scale) + refuse(i.pc, "unsupported " + string(n) + " clamp or omod"); + // op_sel bits 11..14 select a high half. Bit 15 is clamp, already refused. + if (i.wide && (i.a & 0x7800)) + refuse(i.pc, "unsupported " + string(n) + " high-half op_sel"); + if (!half_mode_known || ((mode_bits ^ 0xf0u) & 0x8000ccu)) + refuse(i.pc, "unsupported binary16 rounding or denormal mode"); + auto half_bits = [&](unsigned j) { + const unsigned r = i.src[j]; + string bits; + if (i.subword) { + // A DWORD selection reads the low half for binary16 arithmetic. + const unsigned sel = i.src_select[j]; + bits = subword(operand32(i, r), sel == 6 ? 4 : sel, false); + } else if (r >= 240 && r <= 248) { + // Inline floats are f32 patterns. The f16 operation consumes the + // binary16 rounding of that value. + constexpr unsigned halves[]{0x3800, 0xb800, 0x3c00, 0xbc00, 0x4000, + 0xc000, 0x4400, 0xc400, 0x3118}; + bits = to_string(halves[r - 240]); + } else if (r == 255) + bits = to_string(i.literal & 65535u); + else if (r >= 128 && r <= 192) + bits = to_string((r - 128) & 65535u); + else if (r >= 193 && r <= 208) + bits = to_string((192u - r) & 65535u); + else + bits = ir.binary("and", operand32(i, r), "65535"); + if (i.abs & (1u << j)) + bits = ir.binary("and", bits, "32767"); + if (i.neg & (1u << j)) + bits = ir.binary("xor", bits, "32768"); + return bits; + }; + auto widen = [&](const string &bits) { + return ir.invoke("float", "legacyF16ToF32", 131, {{"i32", bits}}, "nounwind readnone"); + }; + auto a = widen(half_bits(0)); + auto b = widen(half_bits(1)); + if (n == "v_subrev_f16") + std::swap(a, b); + const char *op = n == "v_mul_f16" ? "fmul" : n == "v_add_f16" ? "fadd" : "fsub"; + auto widened = ir.value(string(op) + " float " + a + ", " + b); + auto bits = ir.value("bitcast float " + widened + " to i32"); + // f32 has a 24-bit significand, which covers a correctly rounded f16 + // add, sub or mul (2*11+2). Round with the same integer nearest-even + // conversion v_cvt_f16_f32 uses. + auto rounded = packed_half_rne(bits); + // D[31:16] keeps its value: LLVM GCNSubtarget::zeroesHigh16BitsOfDest lists these four ops with + // "On gfx10, all 16-bit instructions preserve the high bits", as v_cvt_f16_f32 above already does. + vector_write(i.dst, i.subword ? place_subword(i, rounded) + : ir.binary("or", ir.binary("and", read(i.dst), "4294901760"), + ir.binary("and", rounded, "65535"))); + return true; + } + const auto rule = alu_rules.find(n); + const bool byte_to_float = + n.size() == 16 && n.substr(0, 15) == "v_cvt_f32_ubyte" && n.back() >= '0' && n.back() <= '3'; + const bool round = n == "v_fract_f32" || n == "v_trunc_f32" || n == "v_ceil_f32"; + const bool to_integer = n == "v_cvt_i32_f32" || n == "v_cvt_u32_f32" || + n == "v_cvt_flr_i32_f32" || n == "v_cvt_rpi_i32_f32"; + const bool cube = n == "v_cubeid_f32" || n == "v_cubesc_f32" || n == "v_cubetc_f32" || n == "v_cubema_f32"; + const bool mixed = i.enc == Encoding::Mix && (n == "v_fma_mix_f32" || n == "v_fma_mixlo_f16" || n == "v_fma_mixhi_f16"); + if (!mixed && !to_integer && !byte_to_float && !round && !cube && n != "v_mul_legacy_f32" && + n != "v_cos_f32" && (rule == alu_rules.end() || rule->second.type == AluType::Bits)) + return false; + auto source = [&](unsigned j) { + auto v = !j && permuted ? *permuted : operand32(i, i.src[j]); + if (i.subword && j < 2) + v = subword(v, i.src_select[j], i.src_sext[j]); + return v; + }; + auto fp = [&](unsigned j) { + auto bits = source(j); + if (i.abs & (1u << j)) + bits = ir.binary("and", bits, "2147483647"); + if (i.neg & (1u << j)) + bits = ir.binary("xor", bits, "2147483648"); + return ir.value("bitcast i32 " + bits + " to float"); + }; + auto unary = [&](unsigned op, const string &v) { + return ir.invoke("float", "unary.f32", op, {{"float", v}}, "nounwind readnone"); + }; + auto binary = [&](unsigned op, const string &a, const string &b) { + return ir.invoke("float", "binary.f32", op, {{"float", a}, {"float", b}}, "nounwind readnone"); + }; + string result; + if (to_integer) { + if (i.scale || i.clamp) + refuse(i.pc, "integer conversion output modifier"); + auto a = fp(0); + if (n == "v_cvt_rpi_i32_f32") + a = ir.value("fadd float " + a + ", 0.5"); + if (n == "v_cvt_rpi_i32_f32" || n == "v_cvt_flr_i32_f32") + a = unary(27, a); + const bool sign = n != "v_cvt_u32_f32"; + // Only convert a representable input. Select the ISA's saturated + // result (and zero for NaN) independently of LLVM poison behavior. + auto lower = ir.value("fcmp oge float " + a + ", " + (sign ? "-2147483648.0" : "0.0")); + auto upper = ir.value("fcmp olt float " + a + ", " + (sign ? "2147483648.0" : "4294967296.0")); + auto safe = select_float(ir.value("and i1 " + lower + ", " + upper), a, "0.0"); + auto converted = ir.value(string(sign ? "fptosi" : "fptoui") + " float " + safe + " to i32"); + auto bounded = select(upper, converted, sign ? "2147483647" : "4294967295"); + if (sign) + bounded = select(lower, bounded, "2147483648"); + else + bounded = select(lower, bounded, "0"); + auto ordered = ir.value("fcmp ord float " + a + ", " + a); + vector_write(i.dst, place_subword(i, select(ordered, bounded, "0"))); + return true; + } + if (mixed) { + // GFX10 VOP3P splits OP_SEL_HI between the two instruction words. + const unsigned half = ((i.b >> 27) & 3) | ((i.a >> 12) & 4); + std::vector> args; + for (unsigned j = 0; j < 3; ++j) { + auto bits = source(j); + if (half & (1u << j)) { + bits = subword(bits, 4 + ((i.a >> (11 + j)) & 1), false); + const auto value = ir.invoke("float", "legacyF16ToF32", 131, {{"i32", bits}}, "nounwind readnone"); + bits = ir.value("bitcast float " + value + " to i32"); + } + if (i.abs & (1u << j)) bits = ir.binary("and", bits, "2147483647"); + if (i.neg & (1u << j)) bits = ir.binary("xor", bits, "2147483648"); + args.emplace_back("float", ir.value("bitcast i32 " + bits + " to float")); + } + result = ir.invoke("float", "tertiary.f32", 46, args, "nounwind readnone"); + if (i.clamp) result = unary(7, result); + if (n == "v_fma_mix_f32") { + vector_write(i.dst, ir.value("bitcast float " + result + " to i32")); + } else { + auto h = ir.invoke("i32", "legacyF32ToF16", 130, {{"float", result}}, "nounwind readnone"); + const bool high = n == "v_fma_mixhi_f16"; + auto keep = ir.binary("and", read(i.dst), high ? "65535" : "4294901760"); + vector_write(i.dst, ir.binary("or", keep, high ? ir.binary("shl", h, "16") : ir.binary("and", h, "65535"))); + } + return true; + } + if (byte_to_float || (rule != alu_rules.end() && rule->second.type == AluType::ToFloat)) { + if (i.abs || i.neg) + refuse(i.pc, "integer conversion source modifier"); + auto a = source(0); + if (byte_to_float) { + unsigned shift_bits = 8u * (n.back() - '0'); + if (shift_bits) + a = ir.binary("lshr", a, to_string(shift_bits)); + a = ir.binary("and", a, "255"); + } + result = ir.value(string(n == "v_cvt_f32_i32" ? "sitofp" : "uitofp") + " i32 " + a + " to float"); + } else { + auto a = fp(0); + if (n == "v_fma_f32" || n == "v_fmac_f32" || n == "v_fmamk_f32" || n == "v_fmaak_f32") { + // Victory emit/lower.rs uses DXIL FMad for gfx10 f32 FMA. + auto as_float = [&](const string &bits) { return ir.value("bitcast i32 " + bits + " to float"); }; + auto b = n == "v_fmamk_f32" ? as_float(to_string(i.literal)) : fp(1); + auto c = n == "v_fmac_f32" ? as_float(read(i.dst)) : n == "v_fmaak_f32" ? as_float(to_string(i.literal)) : + n == "v_fmamk_f32" ? fp(1) : fp(2); + result = ir.invoke("float", "tertiary.f32", 46, {{"float", a}, {"float", b}, {"float", c}}, "nounwind readnone"); + } else if (n == "v_mul_legacy_f32") { + auto b = fp(1); + auto zero = ir.value("or i1 " + ir.value("fcmp oeq float " + a + ", 0.0") + ", " + + ir.value("fcmp oeq float " + b + ", 0.0")); + result = select_float(zero, "0.0", ir.value("fmul float " + a + ", " + b)); + } else if (n == "v_sin_f32" || n == "v_cos_f32") { + // Victory trig_turns: reduce in turns before converting to + // radians, preserving signed zero and exact quarter-turn zeros. + auto part = ir.value("fsub float " + a + ", " + unary(26, a)); + part = select_float(ir.value("fcmp oeq float " + a + ", 0.0"), a, part); + const bool cosine = n == "v_cos_f32"; + auto radians = ir.value("fmul float " + part + ", 0x401921FB60000000"); + auto exact = ir.value("fcmp oeq float " + unary(6, part) + (cosine ? ", 0.25" : ", 0.5")); + result = select_float(exact, "0.0", unary(cosine ? 12 : 13, radians)); + } else if (cube) + result = cube_alu(n, a, fp(1), fp(2)); + else if (n == "v_add_f32" || n == "v_sub_f32" || n == "v_subrev_f32" || n == "v_mul_f32") { + auto b = fp(1); + if (n == "v_subrev_f32") + std::swap(a, b); + result = ir.value(string(n == "v_add_f32" ? "fadd" + : n == "v_mul_f32" ? "fmul" + : "fsub") + + " float " + a + ", " + b); + } else if (n == "v_med3_f32") { + auto b = fp(1), c = fp(2); + auto lo = binary(36, a, b), hi = binary(35, a, b); + auto median = binary(35, lo, binary(36, hi, c)); + auto nan = ir.value("or i1 " + ir.value("fcmp uno float " + a + ", " + b) + ", " + + ir.value("fcmp uno float " + c + ", " + c)); + result = select_float(nan, binary(36, lo, c), median); + } else if (n == "v_min_f32" || n == "v_max_f32" || n == "v_min3_f32" || n == "v_max3_f32") { + unsigned op = n.substr(2, 3) == "min" ? 36 : 35; + result = binary(op, a, fp(1)); + if (rule->second.arity == 3) + result = binary(op, result, fp(2)); + } else if (n == "v_exp_f32") + result = unary(21, a); + else if (n == "v_log_f32") + result = unary(23, a); + else if (n == "v_rndne_f32") + result = unary(26, a); + else if (n == "v_floor_f32") + result = unary(27, a); + else if (round) + result = unary(n == "v_fract_f32" ? 22 : n == "v_ceil_f32" ? 28 : 29, a); + else if (n == "v_sqrt_f32") + result = unary(24, a); + else if (n == "v_rsq_f32") + result = unary(25, a); + else if (n == "v_rcp_f32") + result = ir.value("fdiv float 1.000000e+00, " + a); + else + return false; + } + if (i.scale) + result = ir.value("fmul float " + result + ", " + (i.scale == 1 ? "2.0" : i.scale == 2 ? "4.0" : "0.5")); + if (i.clamp) + result = unary(7, result); + vector_write(i.dst, place_subword(i, ir.value("bitcast float " + result + " to i32"))); + return true; + } + string graphics_lane_mask(const Inst &i, const State &state, unsigned src, const char *failure) { + if (src == 106) return read(106); + if (src < 106) { + const auto &mask = state[src]; + if ((mask.type == Symbol::Type::lane_mask || mask.type == Symbol::Type::uniform_mask) && !mask.offset && + (!analysis.program.graphics_wave64 || (!(src & 1) && + state[src+1] == Symbol{mask.type,mask.value,1}))) + return read(1024+mask.value); + } + refuse(i.pc,failure); + } + string comparison(const Inst &i) { + if (graphics_input && i.wide && (i.a & 0x7800)) + refuse(i.pc, "unsupported graphics compare operand selection"); + if ((i.abs || i.neg) && i.name.find("_f16") == Name::npos && i.name.find("_f32") == Name::npos) + refuse(i.pc, "integer comparison with floating modifier"); + auto input = [&](unsigned j) { + auto value = operand32(i,i.src[j]); + return i.subword ? subword(value,i.src_select[j],i.src_sext[j]) : value; + }; + auto a = input(0), b = input(1); + return comparison(i,a,b); + } + string comparison(const Inst &i, const string &lhs, const string &rhs) { + Name n = i.name; + const auto at = n.rfind('_'); + if (at == n.npos) + refuse(i.pc, "comparison missing type"); + Name type = n.substr(at + 1), stem = n.substr(0, at); + Name op = stem.substr(stem.rfind('_') + 1); + bool fp = type == "f16" || type == "f32"; + bool sign = type == "i16" || type == "i32"; + bool half = type == "f16" || type == "i16" || type == "u16"; + if (!fp && !sign && type != "u16" && type != "u32") + refuse(i.pc, "direct comparison width"); + if (op == "f") + return "false"; + if (op == "t" || op == "tru") + return "true"; + string a = lhs, b = rhs; + auto bits = [&](string v, unsigned j) { + if (i.abs & (1u << j)) + v = ir.binary("and", v, half ? "32767" : "2147483647"); + if (i.neg & (1u << j)) + v = ir.binary("xor", v, half ? "32768" : "2147483648"); + return v; + }; + if (op == "class" && fp) { + if ((i.abs | i.neg) & 2 || + (i.subword && (half || i.src_select[0] != 6 || i.src_sext[0])) || + (i.wide && (i.a & 0x7800))) + refuse(i.pc, "unsupported floating class operand selection"); + // The class mask is integer data. Testing raw bits keeps sNaNs, + // subnormals and negative zero distinct (gfx2hlsl's class16/32). + auto word = bits(a,0); + auto neg = cmp("ne", ir.binary("and",word,half ? "32768" : "2147483648"), "0"); + auto exp = ir.binary("and", word, half ? "31744" : "2139095040"); + auto frac = ir.binary("and", word, half ? "1023" : "8388607"); + auto empty = cmp("eq", frac, "0"); + auto nan = select(cmp("ne",ir.binary("and",frac,half ? "512" : "4194304"),"0"), "2", "1"); + auto zero_or_tiny = select(empty, select(neg,"32","64"), select(neg,"16","128")); + auto normal = select(neg,"8","256"); + auto cls = select(cmp("eq",exp,half ? "31744" : "2139095040"), + select(empty,select(neg,"4","512"),nan), + select(cmp("eq",exp,"0"),zero_or_tiny,normal)); + return cmp("ne",ir.binary("and",cls,b),"0"); + } + if (fp) { + auto convert = [&](const string &v, unsigned j) { + auto value = bits(v, j); + return half ? ir.invoke("float", "legacyF16ToF32", 131, {{"i32", ir.binary("and", value, "65535")}}, + "nounwind readnone") + : ir.value("bitcast i32 " + value + " to float"); + }; + a = convert(a, 0); + b = convert(b, 1); + static const std::map predicates{{"lt", "olt"}, {"le", "ole"}, {"eq", "oeq"}, {"lg", "one"}, + {"gt", "ogt"}, {"ge", "oge"}, {"o", "ord"}, {"u", "uno"}, + {"nge", "ult"}, {"nlg", "ueq"}, {"ngt", "ule"}, {"nle", "ugt"}, + {"neq", "une"}, {"nlt", "uge"}}; + auto it = predicates.find(op); + if (it == predicates.end()) + refuse(i.pc, "unknown floating comparison predicate"); + return ir.value("fcmp " + string(it->second) + " float " + a + ", " + b); + } + if (half) { + a = subword(a, 4, sign); + b = subword(b, 4, sign); + } + if (op == "eq") + return cmp("eq", a, b); + if (op == "lg" || op == "ne") + return cmp("ne", a, b); + if (op != "lt" && op != "le" && op != "gt" && op != "ge") + refuse(i.pc, "unknown integer comparison predicate"); + return cmp(string(sign ? "s" : "u") + string(op), a, b); + } + // Compute SCC liveness once, only for programs that construct buffer + // descriptors symbolically. A join can observe the old SCC through either + // predecessor. Closed loops without a read do not make it live. + bool uses_scc_after(const Inst &definition) { + const auto &program = analysis.program; + if (scc_live.empty()) { + scc_live.resize(program.code.size()); + std::vector> predecessors(program.code.size()); + std::vector pending; + for (size_t j = 0; j < program.code.size(); ++j) { + const auto &inst = program.code[j]; + const auto n = inst.name; + const bool reads_scc = n == "s_cselect_b32" || n == "s_cselect_b64" || + std::find(inst.src.begin(), inst.src.end(), 253u) != inst.src.end(); + // These scalar mask operations set SCC from their entire + // result and do not consume the incoming SCC. An explicit + // SRC_SCC operand still takes precedence below. + const bool mask_scc = n == "s_andn2_b64" || n == "s_and_b64" || n == "s_or_b64" || + n == "s_xor_b64" || n == "s_not_b64" || n == "s_wqm_b32" || n == "s_wqm_b64" || + n == "s_and_saveexec_b64" || n == "s_or_saveexec_b64"; + const bool overwrites = mask_scc || inst.enc == Encoding::Sopc || n == "s_bfe_u32" || n == "s_and_b32" || + n == "s_or_b32" || n == "s_max_u32" || n == "s_add_u32" || n == "s_sub_u32" || + n == "s_add_i32" || n == "s_sub_i32" || n == "s_and_saveexec_b32" || + n == "s_andn2_wrexec_b32" || n == "s_andn2_b32" || n == "s_orn2_b32" || + n == "s_nor_b32" || n == "s_nand_b32" || n == "s_xnor_b32" || n == "s_not_b32" || + n == "s_lshr_b32" || n == "s_lshl_b32" || n == "s_ashr_i32" || n == "s_xor_b32"; + const bool preserves_pair = n == "s_mul_i32" || n == "s_mul_hi_i32" || n == "s_mul_hi_u32" || + n == "s_bfm_b32" || n == "s_bfm_b64" || n == "s_pack_ll_b32_b16" || n == "s_pack_lh_b32_b16" || + n == "s_pack_hh_b32_b16"; + const bool uncertain_scalar = (inst.enc == Encoding::Sopk && n != "s_movk_i32") || + (inst.enc == Encoding::Sop2 && !overwrites && !preserves_pair) || + (inst.enc == Encoding::Sop1 && !overwrites && n != "s_mov_b32" && n != "s_mov_b64"); + if (reads_scc || uncertain_scalar || (inst.branch() && (inst.op == 4 || inst.op == 5))) { + scc_live[j] = true; + pending.push_back(j); + continue; + } + if (overwrites || n == "s_endpgm") continue; + if (inst.branch()) predecessors[program.at.at(inst.target())].push_back(j); + if (!inst.branch() || inst.op != 2) + predecessors[program.at.at(inst.next)].push_back(j); + } + while (!pending.empty()) { + const auto j = pending.back(); + pending.pop_back(); + for (auto prev : predecessors[j]) { + if (scc_live[prev]) continue; + scc_live[prev] = true; + pending.push_back(prev); + } + } + } + return scc_live[program.at.at(definition.next)]; + } + void arithmetic(const Inst &i, const State &state, const string *permuted = nullptr, bool compute = false) { + auto n = i.name; + if (n == "v_mad_u32_u16" || n == "v_mad_i32_i16") { + // AMD RDNA 2 ISA, VOP3A opcodes 883/885. Only the two + // multiplicands are halfwords. The addend and result are dwords. + if (!i.wide || i.abs || i.neg || i.scale || (i.a & 0x6000)) + refuse(i.pc, "unsupported halfword MAD operand modifiers"); + const bool sign = n == "v_mad_i32_i16"; + auto half = [&](unsigned j) { + auto value = operand32(i, i.src[j]); + if (i.a & (1u << (11 + j))) return ir.binary(sign ? "ashr" : "lshr", value, "16"); + return sign ? ir.binary("ashr", ir.binary("shl", value, "16"), "16") + : ir.binary("and", value, "65535"); + }; + auto product = ir.binary("mul", half(0), half(1)); + auto addend = operand32(i, i.src[2]); + auto sum = ir.binary("add", product, addend); + if (i.clamp) { + if (sign) { + auto overflow = ir.binary("and", ir.binary("xor", product, sum), ir.binary("xor", addend, sum)); + sum = select(cmp("slt", overflow, "0"), + select(cmp("slt", product, "0"), "2147483648", "2147483647"), sum); + } else sum = select(cmp("ult", sum, product), "4294967295", sum); + } + vector_write(i.dst, sum); + return; + } + if (auto dst = carry_destination(i)) { + if (pixel_stage || (graphics_input && ir.loop_dependencies) || i.subword || i.dpp_control || i.clamp || i.neg || i.scale) + refuse(i.pc, "unsupported carry instruction stage or operand modifiers"); + // Victory add_sub_carry and pixel_aot model unsigned carry/borrow + // as lane bits. Snapshot both operands and carry-in before writing + // the result VGPR or its possibly aliased scalar mask. + const bool add = n.substr(0, 5) == "v_add"; + auto a = operand32(i, i.src[0]), b = operand32(i, i.src[1]); + if (n.substr(0, 8) == "v_subrev") std::swap(a, b); + auto result = ir.binary(add ? "add" : "sub", a, b); + auto carry = add ? cmp("ult", result, a) : cmp("ult", a, b); + if (n.find("_ci_") != n.npos) { + unsigned src = i.src[2]; + if (src > 106) refuse(i.pc, "unsupported carry-in mask source"); + string bit; + if (graphics_input) { + bit = cmp("ne",graphics_lane_mask(i,state,src,"unproven vertex carry-in mask"),"0"); + } else { + auto mask = operand32(i, src); + if (wave64) mask = select(upper_half, pair_high(i, src), mask); + bit = cmp("ne", ir.binary("and", mask, lane_bit), "0"); + } + auto edge = cmp("eq", result, add ? "4294967295" : "0"); + auto extra = ir.value("and i1 " + edge + ", " + bit); + carry = ir.value("or i1 " + carry + ", " + extra); + result = ir.binary(add ? "add" : "sub", result, ir.value("zext i1 " + bit + " to i32")); + } + vector_write(i.dst, result); + if (graphics_input) { + if (!graphics_predicate.empty()) carry = ir.value("and i1 " + graphics_predicate + ", " + carry); + auto bit = ir.value("zext i1 " + carry + " to i32"); + // An explicit VOP3B SDST leaves VCC untouched. Its per-lane + // bit may feed another carry, but neither dword is numeric. + if (*dst != 106) write(*dst,{}); + if (analysis.program.graphics_wave64) write(*dst+1,{}); + write(*dst == 106 ? 106 : 1024+i.pc,bit); + } else write_ballot(*dst, carry); + return; + } + if (auto field = byte_descriptor_field(i,state,heap_window)) { + // Keep derived words symbolic, including the status bit until a + // later instruction overwrites it. Never let a numeric branch + // observe a placeholder for this field or its SCC. + // The byte-address OOB selector ORs in two nonzero bits. + // Its SCC is known for every source descriptor. + if (field->type == Symbol::Type::byte_oob) + write(128, "1"); + else if (n != "s_mul_i32" && uses_scc_after(i)) + refuse(i.pc, "numeric SCC from a symbolic descriptor field"); + if (graphics_input) write(i.dst, {}); + return; + } + if (float_alu(i, permuted)) + return; + if (i.enc == Encoding::Vopc && !i.clamp && !i.scale && + (n.find("class") == n.npos || n.find("_f16") != n.npos || n.find("_f32") != n.npos)) { + auto condition = comparison(i); + write_ballot(i.dst, condition); + return; + } + const bool select_mods = n == "v_cndmask_b32" && i.wide && !((i.abs | i.neg) & 4); + if ((i.subword && i.enc != Encoding::Vop1 && i.enc != Encoding::Vop2) || ((i.abs || i.neg) && !select_mods) || i.clamp || i.scale) + refuse(i.pc, "direct ALU operand modifiers"); + auto val = [&](unsigned j) { + auto value = !j && permuted ? *permuted : operand32(i, i.src[j]); + if (select_mods && (i.abs & (1u << j))) value = ir.binary("and", value, "2147483647"); + if (select_mods && (i.neg & (1u << j))) value = ir.binary("xor", value, "2147483648"); + return i.subword && j < 2 ? subword(value, i.src_select[j], i.src_sext[j]) : value; + }; + if (n == "s_mov_b32" || n == "s_mov_b64") { + if (i.dst > 106 && i.dst != 126 && !(compute && i.dst == 107) && !(wave64 && i.dst == 127)) + refuse(i.pc, "direct scalar move destination"); + if (i.src[0] <= 105 && !state[i.src[0]].numeric()) { + if (i.dst > 105) + refuse(i.pc, "descriptor used as mask"); + if (n == "s_mov_b64" && ((i.dst | i.src[0]) & 1)) + refuse(i.pc, "unaligned scalar pair"); + if (state[i.src[0]].type == Symbol::Type::indexed_descriptor) + write(i.dst, read(i.src[0])); + if (n == "s_mov_b64" && state.at(i.src[0] + 1).type == Symbol::Type::indexed_descriptor) + write(i.dst + 1, read(i.src[0] + 1)); + // Transfer tracks symbolic low words; preserve numeric high words of a pair independently. + if (n == "s_mov_b64" && state.at(i.src[0] + 1).numeric()) + write(i.dst + 1, operand32(i, i.src[0] + 1)); + return; + } + string a = val(0); + if (n == "s_mov_b64") { + unsigned src = i.src[0]; + if (src >= 240 && src != 255) + refuse(i.pc, "floating inline constant in 64-bit move"); + if ((i.dst & 1) || (src < 128 && (src & 1))) + refuse(i.pc, "unaligned scalar pair"); + auto hi = graphics_input && !wave64 && src == 106 ? "0" : pair_high(i, src); + write(i.dst + 1, hi); + } + write(i.dst, a); + return; + } + if (i.enc == Encoding::Sopk && (n.substr(0, 7) == "s_cmpk_" || n == "s_addk_i32" || n == "s_mulk_i32")) { + auto a = operand32(i, i.dst); + auto immediate = to_string(n.find("_u32") != n.npos ? Word(uint16_t(i.a)) : Word(int16_t(i.a))); + if (n.substr(0, 7) == "s_cmpk_") { + write(128, ir.value("zext i1 " + comparison(i, a, immediate) + " to i32")); + return; + } + auto result = ir.binary(n == "s_mulk_i32" ? "mul" : "add", a, immediate); + if (n == "s_addk_i32") { + auto overflow = ir.binary("and", ir.binary("xor", a, result), ir.binary("xor", immediate, result)); + write(128, ir.binary("lshr", overflow, "31")); + } + write(i.dst, result); + return; + } + if (n == "s_movk_i32") { + write(i.dst, to_string(Word(int16_t(i.a)))); + return; + } + if (compute && (n == "v_readlane_b32" || n == "v_writelane_b32")) { + if (i.enc != Encoding::Vop3 || i.dpp_control || (i.a & 0x7800u) || i.src[2]) + refuse(i.pc, "lane read/write encoding or operand modifiers"); + const bool reading = n == "v_readlane_b32"; + if ((reading && (i.src[0] < 256 || i.src[0] >= 512 || i.dst > 107)) || + (!reading && (i.src[0] >= 256 || i.dst < 256 || i.dst >= 512))) + refuse(i.pc, "lane read/write register operand"); + const unsigned width = wave64 ? 64 : 32; + const unsigned selector = i.src[1]; + string selected; + if (selector <= 105 || (!wave64 && selector == 107)) { + selected = ir.binary("and", val(1), to_string(width - 1)); + } else { + const auto constant = constant32(i, selector); + if (!constant) + refuse(i.pc, "lane read/write needs a constant or SGPR lane"); + selected = to_string(*constant & (width - 1)); + } + if (reading) { + const auto physical = wave64 ? ir.binary("and", selected, "31") : selected; + auto value = ir.invoke("i32", "waveReadLaneAt.i32", 117, + {{"i32", val(0)}, {"i32", physical}}, "nounwind"); + if (wave64) { + const auto halves = exchange_halves(value); + value = select(cmp("uge", selected, "32"), halves[1], halves[0]); + } + write(i.dst, value); + } else { + const auto guest_lane = wave64 ? ir.binary("or", lane, select(upper_half, "32", "0")) : lane; + // The lane selector is the sole write predicate, independent of guest EXEC. + write(i.dst, select(cmp("eq", guest_lane, selected), val(0), read(i.dst))); + } + return; + } + if (n == "v_readfirstlane_b32") { + if (compute && (i.dpp_control || (i.wide && (i.a & 0x7800u)))) + refuse(i.pc, "readfirstlane modifiers"); + // Guest EXEC selects the first lane, even if it is not physical lane zero. + auto low = read(126); + auto mask = wave64 ? select(upper_half, read(127), low) : low; + auto first = ir.invoke("i32", "unaryBits.i32", 32, {{"i32", mask}}, "nounwind readnone"); + first = select(cmp("eq", mask, "0"), "0", first); + auto value = ir.invoke("i32", "waveReadLaneAt.i32", 117, {{"i32", val(0)}, {"i32", first}}, "nounwind"); + if (wave64) { + auto candidates = exchange_halves(value); + value = select(cmp("ne", low, "0"), candidates[0], candidates[1]); + } + write(i.dst, value); + return; + } + if (n == "v_lshrrev_b64" || n == "v_lshlrev_b64" || n == "v_ashrrev_i64") { + // v_ashrrev_i64 (#2991) sign-extends a 32-bit literal, as gfx2hlsl.py's i64_words(signed=True) does. + const bool arithmetic = n == "v_ashrrev_i64"; + unsigned src = i.src[1]; + const bool sgpr_pair = src <= 104 && (src & 1) == 0; + const bool vgpr_pair = src >= 256 && src < 511; + const bool inline_int = src >= 128 && src <= 208; + if (i.dst >= 511 || !(sgpr_pair || vgpr_pair || inline_int || src == 255)) + refuse(i.pc, "direct 64-bit shift operand"); + string lo = "0", hi = "0"; + if (src != 128) { + lo = operand32(i, src); + if (sgpr_pair || vgpr_pair) + hi = operand32(i, src + 1); + else if (inline_int && src >= 193) + hi = "4294967295"; + else if (src == 255 && arithmetic) + hi = ir.binary("ashr", lo, "31"); + auto low = ir.value("zext i32 " + lo + " to i64"), high = ir.value("zext i32 " + hi + " to i64"); + auto bits = ir.value("shl i64 " + high + ", 32"); + bits = ir.value("or i64 " + bits + ", " + low); + auto amt = ir.value("zext i32 " + ir.binary("and", val(0), "63") + " to i64"); + bits = ir.value(string(arithmetic ? "ashr" : n == "v_lshrrev_b64" ? "lshr" : "shl") + " i64 " + bits + + ", " + amt); + lo = ir.value("trunc i64 " + bits + " to i32"); + hi = ir.value("trunc i64 " + ir.value("lshr i64 " + bits + ", 32") + " to i32"); + ir.features |= 1048576; + } + vector_write(i.dst, lo); + vector_write(i.dst + 1, hi); + return; + } + if (n == "s_bfe_u32" && i.src[0] <= 105) { + const auto &descriptor = state[i.src[0]]; + const auto field = source(i, i.src[1], state); + if (descriptor.type == Symbol::Type::indexed_descriptor && descriptor.value == compute_resource_heap && + descriptor.offset % 32 == 4 && field.type == Symbol::Type::constant && field.value == 0xe0010) { + // Reachable only through a heap descriptor load, which needs the raw_buffer contract. A raw buffer view + // has no stride to read, so the stride of a GPU-selected slot stays untranslated in the direct path. + // With the raw_buffer contract a stride read into s0-s105 is tracked symbolically + // (byte_descriptor_field) and does not reach here. + refuse_heap_contract(i.pc); + refuse(i.pc, "a GPU-selected heap slot stride read is not translated with a view contract"); + } + } + if (compute && n == "s_bfm_b64") { + if ((i.dst & 1) || i.dst > 104) + refuse(i.pc, "invalid s_bfm_b64 destination"); + if ((i.src[0] > 105 && !constant32(i, i.src[0])) || + (i.src[1] > 105 && !constant32(i, i.src[1]))) + refuse(i.pc, "invalid s_bfm_b64 source"); + auto width = ir.binary("and", val(0), "63"); + auto offset = ir.binary("and", val(1), "63"); + auto wide_width = ir.value("zext i32 " + width + " to i64"); + auto wide_offset = ir.value("zext i32 " + offset + " to i64"); + // Width and offset are six-bit fields, so both shifts stay below 64 and a raw + // width of 64 is an empty mask. + auto mask = ir.value("sub i64 " + ir.value("shl i64 1, " + wide_width) + ", 1"); + auto bits = ir.value("shl i64 " + mask + ", " + wide_offset); + write(i.dst, ir.value("trunc i64 " + bits + " to i32")); + write(i.dst + 1, ir.value("trunc i64 " + ir.value("lshr i64 " + bits + ", 32") + " to i32")); + ir.features |= 1048576; + return; + } + if (compute && (n == "s_cselect_b64" || n == "s_not_b64")) { + if ((i.dst & 1) || (i.dst > 104 && i.dst != 106)) + refuse(i.pc, "invalid " + string(n) + " destination"); + auto high = [&](unsigned src) { + if (src == 106 || src == 126) + refuse(i.pc, "invalid " + string(n) + " source"); + return pair_high(i, src); + }; + auto lo = val(0), hi = high(i.src[0]); + if (n == "s_cselect_b64") { + auto condition = cmp("ne", read(128), "0"); + lo = select(condition, lo, val(1)); + hi = select(condition, hi, high(i.src[1])); + } else { + lo = ir.binary("xor", lo, "4294967295"); + hi = ir.binary("xor", hi, "4294967295"); + write(128, ir.value("zext i1 " + cmp("ne", ir.binary("or", lo, hi), "0") + " to i32")); + } + write(i.dst, lo); + write(i.dst + 1, hi); + return; + } + auto a = val(0); + string b, z; + const bool scalar = n.substr(0, 2) == "s_"; + if (i.enc != Encoding::Vop1 && i.enc != Encoding::Sop1) + b = val(1); + // As in Victory's SALU lowering and pixel_aot's SGPR-pair rules, + // bitset reads its previous destination and leaves SCC alone. + if (n == "s_bitset0_b32" || n == "s_bitset1_b32" || n == "s_bitset0_b64" || n == "s_bitset1_b64") { + const bool pair = n.substr(n.size() - 3) == "b64"; + if (i.dst > 105 || (pair && (i.dst & 1))) + refuse(i.pc, "bitset requires a general scalar destination or aligned pair"); + auto old = operand32(i, i.dst); + auto bit = shift("shl", "1", a); + auto replace = [&](const string &value) { + return n[8] == '1' ? ir.binary("or", value, bit) + : ir.binary("and", value, ir.binary("xor", bit, "4294967295")); + }; + if (pair) { + auto high = operand32(i, i.dst + 1); + auto upper = cmp("ne", ir.binary("and", a, "32"), "0"); + write(i.dst, select(upper, old, replace(old))); + write(i.dst + 1, select(upper, replace(high), high)); + } else + write(i.dst, replace(old)); + return; + } + if (n == "s_bitreplicate_b64_b32") { + if ((i.dst > 104 && (graphics_input || i.dst != 106)) || (i.dst & 1)) + refuse(i.pc, "bitreplicate requires an aligned general scalar pair or compute VCC"); + // pixel_aot expands each 16-bit half into the even positions, + // then duplicates each of the original bits into its neighbour. + auto replicate = [&](string half) { + unsigned shift = 8; + for (Word mask : {0x00ff00ffu, 0x0f0f0f0fu, 0x33333333u, 0x55555555u}) { + half = ir.binary("and", ir.binary("or", half, ir.binary("shl", half, to_string(shift))), to_string(mask)); + shift >>= 1; + } + return ir.binary("or", half, ir.binary("shl", half, "1")); + }; + write(i.dst, replicate(ir.binary("and", a, "65535"))); + write(i.dst + 1, replicate(ir.binary("lshr", a, "16"))); + return; + } + if (n == "s_pack_ll_b32_b16" || n == "s_pack_lh_b32_b16" || n == "s_pack_hh_b32_b16") { + const auto lo = n == "s_pack_hh_b32_b16" ? ir.binary("lshr", a, "16") : ir.binary("and", a, "65535"); + const auto hi = n == "s_pack_ll_b32_b16" ? ir.binary("shl", b, "16") : ir.binary("and", b, "4294901760"); + write(i.dst, ir.binary("or", lo, hi)); + return; + } + if (i.enc == Encoding::Sop2 && i.op >= 0x2e && i.op <= 0x31) { + unsigned amount = i.op - 0x2d; + auto shifted = ir.binary("shl", a, to_string(amount)); + auto sum = ir.binary("add", shifted, b); + auto shifted_out = cmp("ne", ir.binary("lshr", a, to_string(32 - amount)), "0"); + auto carry = ir.value("or i1 " + shifted_out + ", " + cmp("ult", sum, shifted)); + write(i.dst, sum); + write(128, ir.value("zext i1 " + carry + " to i32")); + return; + } + if ((i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2) && n.size() > 6 && n.substr(n.size() - 4) == "_b64") { + bool save = n.find("_saveexec_") != Name::npos; + auto op = n.substr(2, n.find('_', 2) - 2); + if ((i.dst & 1) || (i.dst > 104 && i.dst != 106 && i.dst != 126) || + (save && i.enc != Encoding::Sop1) || (!save && i.enc != Encoding::Sop2)) + refuse(i.pc, "unsupported wave64 scalar operation"); + auto ah = pair_high(i, i.src[0]); + auto bl = save ? read(126) : b, bh = save ? read(127) : pair_high(i, i.src[1]); + auto combine = [&](const string &left, const string &right) -> string { + if (op == "and" || op == "or" || op == "xor") return ir.binary(string(op), left, right); + if (op == "andn2" || op == "orn2") + return ir.binary(op == "andn2" ? "and" : "or", left, ir.binary("xor", right, "4294967295")); + if (op == "nand" || op == "nor" || op == "xnor") + return ir.binary("xor", ir.binary(op == "nand" ? "and" : op == "nor" ? "or" : "xor", left, right), "4294967295"); + refuse(i.pc, "unsupported wave64 scalar mask operation"); + }; + // SAVEEXEC combines its source operand with the old EXEC in ISA operand order. + auto lo = combine(a, bl), hi = combine(ah, bh); + write(i.dst, save ? bl : lo); + write(i.dst + 1, save ? bh : hi); + if (save) { write(126, lo); write(127, hi); } + write(128, ir.value("zext i1 " + cmp("ne", ir.binary("or", lo, hi), "0") + " to i32")); + return; + } + if (n == "s_and_saveexec_b32" || n == "s_andn2_wrexec_b32") { + auto old = read(126); + auto mask = ir.binary("and", a, n == "s_and_saveexec_b32" ? old : ir.binary("xor", old, "4294967295")); + write(i.dst, n == "s_and_saveexec_b32" ? old : mask); + write(126, mask); + write(128, ir.value("zext i1 " + cmp("ne", mask, "0") + " to i32")); + return; + } + if (n == "s_add_i32" || n == "s_sub_i32") { + auto z = ir.binary(n == "s_add_i32" ? "add" : "sub", a, b); + auto left = ir.binary("xor", a, z); + auto right = ir.binary("xor", n == "s_add_i32" ? b : a, n == "s_add_i32" ? z : b); + write(128, ir.binary("lshr", ir.binary("and", left, right), "31")); + write(i.dst, z); + return; + } + if (n == "s_addc_u32" || n == "s_subb_u32") { + auto carry = read(128); + bool add = n == "s_addc_u32"; + auto partial = ir.binary(add ? "add" : "sub", a, b), + result = ir.binary(add ? "add" : "sub", partial, carry); + auto flag = add ? cmp("ult", partial, a) : cmp("ult", a, b); + auto carry2 = add ? cmp("ult", result, partial) : cmp("ult", partial, carry); + write(i.dst, result); + write(128, ir.value("zext i1 " + ir.value("or i1 " + flag + ", " + carry2) + " to i32")); + return; + } + if (n == "s_brev_b32" || n == "v_bfrev_b32" || n == "v_bcnt_u32_b32") { + bool count = n == "v_bcnt_u32_b32"; + auto value = ir.invoke("i32", count ? "unaryBits.i32" : "unary.i32", count ? 31 : 30, {{"i32", a}}, + "nounwind readnone"); + if (scalar) + write(i.dst, value); + else + vector_write(i.dst, place_subword(i, count ? ir.binary("add", value, b) : value)); + return; + } + if (n == "v_swap_b32") { + if (i.wide || i.src[0] < 256) + refuse(i.pc, "invalid vector swap source"); + auto old = read(i.dst); + vector_write(i.dst, a); + vector_write(i.src[0], old); + return; + } + if (n == "s_cselect_b32") { + write(i.dst, select(cmp("ne", read(128), "0"), a, b)); + return; + } + if (n == "s_bitcmp1_b32" || n == "s_bitcmp0_b32") { + auto bit = ir.binary("and", shift("lshr", a, b), "1"); + write(128, n == "s_bitcmp0_b32" ? ir.binary("xor", bit, "1") : bit); + return; + } + if (n == "s_min_u32" || n == "s_max_u32" || n == "s_min_i32" || n == "s_max_i32" || + n == "v_min_u32" || n == "v_max_u32" || n == "v_min_i32" || n == "v_max_i32") { + const string sign = n.substr(n.size() - 3) == "i32" ? "s" : "u"; + auto pred = cmp(sign + (n.substr(2, 3) == "min" ? "lt" : "gt"), a, b); + auto result = select(pred, a, b); + if (scalar) { + write(i.dst, result); + write(128, ir.value("zext i1 " + pred + " to i32")); + } else { + vector_write(i.dst, place_subword(i, result)); + } + return; + } + if (n == "v_cndmask_b32") { + if (!wave64 && i.src[2] == 107) + refuse(i.pc, "unsupported wave32 conditional mask source"); + z = select(cmp("ne", ir.binary("and", wave64 ? select(upper_half, pair_high(i, i.src[2]), val(2)) : val(2), lane_bit), "0"), b, a); + } else if (n == "v_mov_b32") + z = a; + else if (n == "s_mul_i32" || n == "v_mul_lo_u32" || n == "v_mul_lo_i32") + z = ir.binary("mul", a, b); + else if (n == "v_mul_hi_u32" || n == "v_mul_hi_i32" || n == "s_mul_hi_u32" || n == "s_mul_hi_i32") { + // Accumulate 16-bit partial products without requiring Int64ShaderOps. + auto lo = [&](const string &v) { return ir.binary("and", v, "65535"); }; + auto hi = [&](const string &v) { return ir.binary("lshr", v, "16"); }; + auto al = lo(a), ah = hi(a), bl = lo(b), bh = hi(b); + auto middle = ir.binary("add", ir.binary("mul", ah, bl), hi(ir.binary("mul", al, bl))); + auto carry = hi(ir.binary("add", lo(middle), ir.binary("mul", al, bh))); + z = ir.binary("add", ir.binary("add", ir.binary("mul", ah, bh), hi(middle)), carry); + if (n == "v_mul_hi_i32" || n == "s_mul_hi_i32") { + z = ir.binary("sub", z, select(cmp("slt", a, "0"), b, "0")); + z = ir.binary("sub", z, select(cmp("slt", b, "0"), a, "0")); + } + } else if (n == "s_abs_i32") + z = select(cmp("slt", a, "0"), ir.binary("sub", "0", a), a); + else if (n == "v_add_nc_u32" || n == "s_add_u32") + z = ir.binary("add", a, b); + else if (n == "s_sub_u32" || n == "v_sub_nc_u32") + z = ir.binary("sub", a, b); + else if (n == "v_subrev_nc_u32") + z = ir.binary("sub", b, a); + else if (n == "v_not_b32") + z = ir.binary("xor", a, "4294967295"); + else if (n == "s_and_b32" || n == "v_and_b32") + z = ir.binary("and", a, b); + else if (n == "s_or_b32" || n == "v_or_b32") + z = ir.binary("or", a, b); + else if (n == "v_xor_b32" || n == "s_xor_b32") + z = ir.binary("xor", a, b); + else if (n == "v_and_or_b32") + z = ir.binary("or", ir.binary("and", a, b), val(2)); + else if (n == "v_xad_u32") + z = ir.binary("add", ir.binary("xor", a, b), val(2)); + else if (n == "v_or3_b32" || n == "v_xor3_b32" || n == "v_add3_u32") { + const char *op = n == "v_or3_b32" ? "or" : n == "v_xor3_b32" ? "xor" : "add"; + z = ir.binary(op, ir.binary(op, a, b), val(2)); + } else if (n == "v_add_lshl_u32") + z = shift("shl", ir.binary("add", a, b), val(2)); + else if (n == "v_mad_i32_i24") { + // sext(S0[23:0]) * sext(S1[23:0]) + S2 modulo 2^32 (#2991, gfx2hlsl.py's VOP3 table). + auto sext24 = [&](const string &x) { return ir.binary("ashr", ir.binary("shl", x, "8"), "8"); }; + z = ir.binary("add", ir.binary("mul", sext24(a), sext24(b)), val(2)); + } else if (n == "v_mul_u32_u24" || n == "v_mad_u32_u24") { + z = ir.binary("mul", ir.binary("and", a, "16777215"), ir.binary("and", b, "16777215")); + if (n == "v_mad_u32_u24") + z = ir.binary("add", z, val(2)); + } else if ((n.substr(2, 3) == "min" || n.substr(2, 3) == "max" || n.substr(2, 4) == "med3") && + (n.substr(n.size() - 4) == "_u32" || n.substr(n.size() - 4) == "_i32") && !scalar) { + const bool signed_order = n.substr(n.size() - 4) == "_i32"; + auto bound = [&](const string &x, const string &y, bool minimum) { + return select(cmp(signed_order ? (minimum ? "slt" : "sgt") : (minimum ? "ult" : "ugt"), x, y), x, y); + }; + bool minimum = n.substr(2, 3) == "min"; + if (n.substr(2, 4) == "med3") { + auto c = val(2); + z = bound(bound(a, b, true), bound(bound(a, b, false), c, true), false); + } else { + z = bound(a, b, minimum); + if (n[5] == '3') + z = bound(z, val(2), minimum); + } + } else if (n == "v_sad_u8" || n == "v_sad_hi_u8" || n == "v_sad_u16" || n == "v_sad_u32" || n == "v_msad_u8") { + // Sums of unsigned absolute differences plus S2, modulo 2^32 (#2987), as gfx2hlsl.py's sad_u8, sad4_u8, + // sad_u16 and sad_u32 helpers and tools/pixel_aot.py compute them. v_msad_u8 skips each byte whose S1 + // byte is zero; v_sad_hi_u8 places the byte sum in the high half. + auto absdiff = [&](const string &x, const string &y) { + return select(cmp("ult", x, y), ir.binary("sub", y, x), ir.binary("sub", x, y)); + }; + auto field = [&](const string &x, unsigned at, unsigned mask) { + return ir.binary("and", at ? ir.binary("lshr", x, to_string(at)) : x, to_string(mask)); + }; + string sum; + if (n == "v_sad_u32") + sum = absdiff(a, b); + else { + const bool half = n == "v_sad_u16"; + for (unsigned at = 0; at < 32; at += half ? 16 : 8) { + const unsigned mask = half ? 65535 : 255; + auto x = field(a, at, mask), y = field(b, at, mask); + auto term = absdiff(x, y); + if (n == "v_msad_u8") + term = select(cmp("eq", y, "0"), "0", term); + sum = sum.empty() ? term : ir.binary("add", sum, term); + } + if (n == "v_sad_hi_u8") + sum = ir.binary("shl", sum, "16"); + } + z = ir.binary("add", sum, val(2)); + } else if (n == "v_alignbit_b32" || n == "v_alignbyte_b32") { + // Bits [k + 31 : k] of the 64-bit value {S0, S1}, with k = S2[4:0] or 8 * S2[1:0] (#2985, the + // gfx2hlsl.py VOP3 table). A zero k returns S1; the masked shift keeps the other arm in range. + auto k = n == "v_alignbit_b32" ? ir.binary("and", val(2), "31") + : ir.binary("shl", ir.binary("and", val(2), "3"), "3"); + auto joined = ir.binary("or", shift("lshr", b, k), shift("shl", a, ir.binary("sub", "32", k))); + z = select(cmp("eq", k, "0"), b, joined); + } else if (n == "v_bfm_b32") + z = shift("shl", ir.binary("sub", shift("shl", "1", a), "1"), b); // like s_bfm_b32 (#2985) + else if (n == "v_bfi_b32") + z = ir.binary("or", ir.binary("and", a, b), ir.binary("and", ir.binary("xor", a, "4294967295"), val(2))); + else if (n == "s_bfe_u32" || n == "s_bfe_i32") { + const bool sign = n == "s_bfe_i32"; + auto offset = ir.binary("and", b, "31"); + auto width = ir.binary("and", ir.binary("lshr", b, "16"), "127"); + auto shifted = ir.binary(sign ? "ashr" : "lshr", a, offset); + auto pad = ir.binary("and", ir.binary("sub", "32", width), "31"); + auto narrow = ir.binary(sign ? "ashr" : "lshr", ir.binary("shl", shifted, pad), pad); + z = select(cmp("eq", width, "0"), "0", select(cmp("uge", width, "32"), shifted, narrow)); + } + else if (n == "v_cvt_pk_u16_u32" || n == "v_cvt_pk_i16_i32") { + // Saturate S0 and S1 to 16 bits and pack S0 low, S1 high (#2995, gfx2hlsl.py's VOP3 table). The + // instructions have two sources; like gfx2hlsl.py, refuse a nonzero unused SRC2 field. + if (i.src[2] != 0) + refuse(i.pc, string(n) + " with unused src2 field set"); + if (i.a & 0x7800) + refuse(i.pc, string(n) + " with op_sel"); + auto narrow = [&](const string &x) { + if (n == "v_cvt_pk_u16_u32") + return select(cmp("ugt", x, "65535"), "65535", x); + auto low = select(cmp("slt", x, "-32768"), "-32768", x); + return ir.binary("and", select(cmp("sgt", low, "32767"), "32767", low), "65535"); + }; + z = ir.binary("or", narrow(a), ir.binary("shl", narrow(b), "16")); + } + else if (n == "v_bfe_u32") + z = ir.binary("and", shift("lshr", a, b), ir.binary("sub", shift("shl", "1", val(2)), "1")); + else if (n == "v_bfe_i32") { + auto width = ir.binary("and", val(2), "31"); + auto pad = ir.binary("sub", "32", width); + auto field = shift("ashr", a, b); + z = select(cmp("eq", width, "0"), "0", shift("ashr", shift("shl", field, pad), pad)); + } else if (n == "v_cvt_pk_u8_f32") { + // (S2 & ~(0xff << 8 * S1[1:0])) | (flt32_to_uint8(S0) << 8 * S1[1:0]) (#2997), with the conversion + // gfx2hlsl.py measured on RDNA 2: round to nearest even, saturate to [0, 255], zero for NaN, both zeros + // and negatives. (bits - 1) < 0x7f800000 holds exactly from the smallest subnormal to +inf, as an integer + // test that fast-math cannot fold. + auto amount = ir.binary("shl", ir.binary("and", b, "3"), "3"); + auto positive = cmp("ult", ir.binary("sub", a, "1"), "2139095040"); + auto bounded = ir.invoke("float", "binary.f32", 36, {{"float", ir.value("bitcast i32 " + a + " to float")}, + {"float", "2.550000e+02"}}, "nounwind readnone"); + auto rounded = ir.invoke("float", "unary.f32", 26, {{"float", bounded}}, "nounwind readnone"); + auto byte = select(positive, ir.binary("and", ir.value("fptoui float " + rounded + " to i32"), "255"), "0"); + auto keep = ir.binary("xor", ir.binary("shl", "255", amount), "4294967295"); + z = ir.binary("or", ir.binary("and", val(2), keep), ir.binary("shl", byte, amount)); + } else if (n == "s_orn2_b32") + z = ir.binary("or", a, ir.binary("xor", b, "4294967295")); + else if (n == "s_nand_b32" || n == "s_xnor_b32") + z = ir.binary("xor", ir.binary(n == "s_nand_b32" ? "and" : "xor", a, b), "4294967295"); + else if (n == "s_ashr_i32") + z = shift("ashr", a, b); + else if (n == "s_bfm_b32") + z = shift("shl", ir.binary("sub", shift("shl", "1", a), "1"), b); + else if (n == "s_not_b32") + z = ir.binary("xor", a, "4294967295"); + else if (n == "s_andn2_b32" || n == "s_nor_b32") + z = n == "s_andn2_b32" ? ir.binary("and", a, ir.binary("xor", b, "4294967295")) + : ir.binary("xor", ir.binary("or", a, b), "4294967295"); + else if (n == "s_lshl_b32" || n == "s_lshr_b32") + z = shift(n == "s_lshl_b32" ? "shl" : "lshr", a, b); + else if (n == "v_lshlrev_b32" || n == "v_lshrrev_b32" || n == "v_ashrrev_i32") + z = shift(n == "v_lshlrev_b32" ? "shl" : n == "v_lshrrev_b32" ? "lshr" : "ashr", b, a); + else if (n == "v_lshl_add_u32" || n == "v_lshl_or_b32") + z = ir.binary(n == "v_lshl_add_u32" ? "add" : "or", shift("shl", a, b), val(2)); + else if (n == "v_mbcnt_hi_u32_b32" || n == "v_mbcnt_lo_u32_b32") { + bool high = n == "v_mbcnt_hi_u32_b32"; + auto before = ir.binary("sub", lane_bit, "1"); + auto mask = wave64 ? select(upper_half, high ? before : "4294967295", high ? "0" : before) + : high ? "0" : before; + auto lower = ir.binary("and", a, mask); + z = ir.binary("add", b, ir.invoke("i32", "unaryBits.i32", 31, {{"i32", lower}}, "nounwind readnone")); + } else if (i.enc == Encoding::Sopc || i.enc == Encoding::Vopc || n.substr(0, 6) == "v_cmpx" || + n.substr(0, 6) == "v_cmp_") { + auto condition = comparison(i, a, b); + if (scalar) + write(128, ir.value("zext i1 " + condition + " to i32")); + else + write_ballot(i.dst, condition); + return; + } else + refuse(i.pc, "direct DXIL lowering for " + string(n)); + if (scalar) { + write(i.dst, z); + if (n != "s_mul_i32" && n != "s_mul_hi_u32" && n != "s_mul_hi_i32" && n != "s_bfm_b32") { + auto flag = n == "s_add_u32" ? cmp("ult", z, a) + : n == "s_sub_u32" ? cmp("ult", a, b) + : cmp("ne", z, "0"); + write(128, ir.value("zext i1 " + flag + " to i32")); + } + } else + vector_write(i.dst, place_subword(i, z)); + } + void lower_dpp(const Inst &i, const State &state, unsigned threads) { + // Both lane selections stay in one physical wave32 for split guest wave64. + // Shader control flow stays wave-uniform. Guest EXEC predicates VGPR + // writes, so FI can fetch the last VGPR value from a disabled thread. + const unsigned mask = i.mirror_mask(); + const unsigned group_size = mask ? mask + 1 : 4; + if (threads % group_size) + refuse(i.pc, mask ? "DPP mirror needs complete source lane groups" + : "DPP quad_perm needs a thread count divisible by four"); + const auto rule = alu_rules.find(i.name); + if (rule == alu_rules.end() || rule->second.arity > 2) + refuse(i.pc, "unsupported DPP arithmetic"); + if (i.enc == Encoding::Vop1 && ((i.neg | i.abs) & 2)) + refuse(i.pc, "unexpected second DPP source modifier"); + string source_lane; + if (mask) + source_lane = ir.binary("xor", lane, to_string(mask)); + else { + auto quad_base = ir.binary("and", lane, "4294967292"); + auto quad_lane = ir.binary("and", lane, "3"); + auto shift = ir.binary("shl", quad_lane, "1"); + auto fields = ir.binary("lshr", to_string(*i.dpp_control), shift); + source_lane = ir.binary("or", quad_base, ir.binary("and", fields, "3")); + } + auto src = operand32(i, i.src[0]); + auto word = ir.invoke("i32", "waveReadLaneAt.i32", 117, {{"i32",src},{"i32",source_lane}}, "nounwind"); + string source_enabled, previous; + if (!i.dpp_fetch_inactive) { + auto exec = wave64 ? select(upper_half, read(127), read(126)) : read(126); + source_enabled = cmp("ne", ir.binary("and", exec, ir.binary("shl", "1", source_lane)), "0"); + if (i.dpp_bound_zero) word = select(source_enabled, word, "0"); + else previous = read(i.dst); + } + arithmetic(i, state, &word); + if (!previous.empty()) + write(i.dst, select(source_enabled, read(i.dst), previous)); + } + // Returns true when the instruction is a MODE write this path has accepted + // (including a no-op that leaves the implemented contract in place). + bool consume_half_mode(const Inst &i) { + if (!half_binary || graphics_input) + return false; + constexpr unsigned f16_bits = 0x8000ccu; // round16 [3:2], denorm16 [7:6], FP16_OVFL + constexpr unsigned contract = 0xf0u; // denorm32 = denorm16 = 3 (keep) + auto bad = [&]() { refuse(i.pc, "unsupported binary16 rounding or denormal mode"); }; + auto accept = [&](unsigned updated) { + if ((updated ^ contract) & f16_bits) + bad(); + // A write that moves a bit this path does not model (f32 round or + // f32 denorm) keeps the previous refusal. + if ((updated ^ mode_bits) & ~f16_bits) + return false; + mode_bits = updated; + return true; + }; + const auto &n = i.name; + if (n == "s_round_mode" || n == "s_denorm_mode") { + // Both immediates use [1:0] for f32 and [3:2] for f16/f64. Bits above + // the low nibble are ignored by the instruction. + const unsigned nibble = i.a & 15u; + const unsigned mask = n == "s_round_mode" ? 0xfu : 0xf0u; + const unsigned field = n == "s_round_mode" ? nibble : nibble << 4; + if (!half_mode_known && ((field ^ mode_bits) & mask & f16_bits)) + bad(); + return accept((mode_bits & ~mask) | field); + } + if (n != "s_setreg_b32" && n != "s_setreg_imm32_b32") + return false; + // SIMM16 = {size[4:0], offset[4:0], hwRegId[5:0]}. hwRegId 1 is MODE. + const unsigned simm = i.a & 0xffffu; + const unsigned hw = simm & 63u; + const unsigned offset = (simm >> 6) & 31u; + const unsigned size = ((simm >> 11) & 31u) + 1u; + if (hw != 1u || offset >= 32u || size > 32u - offset) + return false; + const unsigned mask = size == 32u ? 0xffffffffu : ((1u << size) - 1u) << offset; + if ((mask & f16_bits) == 0) + return false; + // The SGPR form, and any form reached from more than one path, does not + // prove the bits that this lowering implements. + if (n == "s_setreg_b32" || !half_mode_known) + bad(); + const unsigned updated = (mode_bits & ~mask) | ((i.literal << offset) & mask); + return accept(updated); + } + NativeComputeShader lower(unsigned entry, unsigned user, unsigned flags, unsigned x, unsigned y, unsigned z) { + const unsigned lds_words = ((flags >> 15) & 511) * 128; + const bool uses_lds = std::any_of(analysis.program.code.begin(), analysis.program.code.end(), + [](const Inst &i) { return i.enc == Encoding::Lds; }); + if (uses_lds) + ir.globals << "@lds = internal addrspace(3) global [" << lds_words << " x i32] undef, align 4\n"; + initialize(user, flags, x, y, z); + const auto &p = analysis.program; + mode_bits = 0xf0; + bool mode_write = false, conditional = false; + for (size_t k = 0; k < p.code.size(); ++k) { + if (!p.reached[k]) + continue; + const auto &op = p.code[k]; + if (binary16_alu(op.name)) + half_binary = true; + if (op.name == "s_round_mode" || op.name == "s_denorm_mode" || op.name == "s_setreg_b32" || + op.name == "s_setreg_imm32_b32") + mode_write = true; + if (op.branch() && op.op != 2) + conditional = true; + } + half_mode_known = !(half_binary && mode_write && conditional); + const bool writes_uavs = std::any_of(p.code.begin(), p.code.end(), [](const Inst &i) { + return i.name.substr(0, 12) == "buffer_store" || i.name.substr(0, 13) == "buffer_atomic" || + (i.enc == Encoding::Image && i.op == 8); + }); + std::set labels{entry}; + ir.body << " br label %pc" << entry << "\n"; + for (auto &i : p.code) + if (i.branch()) { + labels.insert(i.target()); + if (i.op != 2) + labels.insert(i.next); + } + for (size_t k = 0; k < p.code.size(); ++k) { + const auto &i = p.code[k]; + if (labels.count(i.pc)) { + if (k && p.code[k - 1].name != "s_endpgm" && !p.code[k - 1].branch()) + ir.body << " br label %pc" << i.pc << "\n"; + ir.body << "pc" << i.pc << ":\n"; + } + if (!p.reached[k]) { + ir.body << " unreachable\n"; + while (k + 1 < p.code.size() && !labels.count(p.code[k + 1].pc)) + ++k; + continue; + } + if (i.branch()) { + if (i.op == 2) + ir.body << " br label %pc" << i.target() << "\n"; + else { + unsigned r = i.op == 4 || i.op == 5 ? 128 : i.op == 6 || i.op == 7 ? 106 : 126; + auto mask = wave64 && r != 128 ? ir.binary("or", read(r), read(r + 1)) : read(r); + auto pred = cmp((i.op & 1) ? "ne" : "eq", mask, "0"); + ir.body << " br i1 " << pred << ", label %pc" << i.target() << ", label %pc" << i.next << "\n"; + } + } else if (i.dpp_control) + lower_dpp(i, p.before[k], x*y*z); + else if (i.name == "s_endpgm") + ir.body << " ret void\n"; + // Hardware scheduling and register-dependency waits have no SGPR + // operands. SSA dependencies carry these constraints into DXIL. + else if (i.name == "v_nop" || i.name == "s_inst_prefetch" || i.name == "s_clause" || i.name == "s_nop" || + i.name == "s_waitcnt" || i.name == "s_waitcnt_depctr" || i.name == "s_setprio") + continue; + else if (i.enc == Encoding::Mubuf || i.enc == Encoding::Smem) + memory(i, p.before[k]); + else if (i.enc == Encoding::Lds) + local_memory(i, lds_words); + else if (i.name == "s_barrier") + barrier(writes_uavs ? 11 : 9); // group rendezvous, LDS and, when used, UAV memory + else if (i.name == "s_waitcnt_vscnt" || i.name == "s_waitcnt_vmcnt" || + i.name == "s_waitcnt_lgkmcnt" || i.name == "s_waitcnt_expcnt") { + // null,0 drains this wave's counter. Memory-only barriers + // preserve ordering without rendezvousing other workgroup waves. + if (i.dst != 125 || (i.a & 65535)) + refuse(i.pc, "compute counter wait requires null and a zero threshold"); + if (i.name == "s_waitcnt_lgkmcnt" && uses_lds) + barrier(8); + if ((i.name == "s_waitcnt_vscnt" || i.name == "s_waitcnt_vmcnt") && writes_uavs) + barrier(2); + } + else if (consume_half_mode(i)) + continue; + else if (i.enc == Encoding::Sopp) + refuse(i.pc, "unsupported compute control instruction " + string(i.name)); + else if (i.enc == Encoding::Image) + image_io(i, p.before[k]); + else + arithmetic(i, p.before[k], nullptr, true); + } + auto &r = analysis.result; + r.instruction_count = unsigned(p.code.size()); + const unsigned rank_words = x * y * z > 64 ? x * y * z : 0; + if ((uses_lds ? lds_words : 0) + rank_words + (uses_exchange ? exchange_words : 0) > 8192) + refuse(entry, "combined shared storage exceeds 32 KiB"); + r.dxil_ir = ir.finish_compute(x, y, z); + return std::move(r); + } +}; diff --git a/src/gfx1013_direct_graphics.inl b/src/gfx1013_direct_graphics.inl new file mode 100644 index 000000000..b79a2eb3c --- /dev/null +++ b/src/gfx1013_direct_graphics.inl @@ -0,0 +1,2080 @@ +// Graphics stages share decoded operands, scalar provenance, +// vector arithmetic, memory operations and binary resource declarations with CS. +// Signature rows describe how native exports meet the desktop rasterizer. +struct GraphicsStage { + const GuestShaderStage &stage; + DirectCompute &alu; + bool pixel; + std::map exported; + unsigned pc = 0; + + struct Interpolation { + unsigned attribute, channel, source, mode; + }; + std::map partial; + std::set overwritten_inputs; + std::map branch_inputs; + // SPI_PS_INPUT_ADDR order and DXIL interpolation modes, following + // victory-shader (9376fd6), io.rs and emit/lower.rs::barycentric. + static constexpr unsigned bary_modes[] = {6, 2, 3, 0, 7, 4, 5}; + const string &incoming_input(unsigned reg) { + auto [it, new_value] = branch_inputs.try_emplace(reg); + if (!new_value || reg < 256 || reg >= 512) + return it->second; + // An input untouched on one predecessor still has its entry value. + // Its load must dominate every edge of the phi at the join. + alu.ir.setup.swap(alu.ir.body); + try { + it->second = input(reg); + } catch (const UnsupportedComputeShader &) { + // A temporary may legitimately be undefined on a dead edge. + // A subsequent read of this merged register reports the refusal. + } + alu.ir.setup.swap(alu.ir.body); + return it->second; + } + void interpolate(Word w) { + unsigned op = (w >> 16) & 3, attr = (w >> 10) & 63, channel = (w >> 8) & 3, src = w & 255, + dest = 256 + ((w >> 18) & 255); + if (!pixel) + refuse(pc, "interpolation outside pixel stage"); + const auto it = std::find_if(stage.attributes.begin(), stage.attributes.end(), + [&](auto &a) { return a.location == attr && (a.mask & (1u << channel)); }); + if (it == stage.attributes.end() || it->usage != 6 || (it->flags & 0x18)) + refuse(pc, "missing or packed interpolation attribute"); + unsigned mode = 1; + if (op == 2) { + if (src != 2 || !(it->flags & 1)) + refuse(pc, "unsupported provoking vertex or smooth flat fetch"); + } else { + unsigned base = 0, first = UINT_MAX; + for (unsigned bit = 0; bit < 7; ++bit) + if (stage.pixel_input_address & (1u << bit)) { + if ((stage.pixel_input_enable & (1u << bit)) && src == base + (op == 1)) { + mode = bary_modes[bit]; + first = base; + break; + } + base += bit == 3 ? 3 : 2; + } + if (op > 1 || !mode || first == UINT_MAX || (it->flags & 1) || overwritten_inputs.count(256 + src)) + refuse(pc, "interpolation barycentric source is not an entry register"); + if (op == 0) { + partial[dest] = {attr, channel, src, mode}; + alu.graphics_registers.erase(dest); + alu.guarded_ij.erase(dest); + overwritten_inputs.insert(dest); + return; + } + const auto prev = partial.find(dest); + if (prev == partial.end() || prev->second.attribute != attr || prev->second.channel != channel || + prev->second.source != first || prev->second.mode != mode) + refuse(pc, "unmatched interpolation pair"); + } + partial.erase(dest); + alu.write(dest, load(generic(true, it->row, channel, mode), channel)); + overwritten_inputs.insert(dest); + } + unsigned system(const string &name) { + if (name == "SV_Position") + return 3; + if (name == "SV_VertexID") + return 1; + if (name == "SV_InstanceID") + return 2; + if (name == "SV_Target") + return 16; + if (name.rfind("SV_", 0) == 0) + refuse(pc, "unsupported graphics system semantic " + name); + return 0; + } + unsigned row(bool input, const string &name, unsigned index, unsigned kind, unsigned component, unsigned reg, + unsigned mask, unsigned interpolation) { + auto &rows = input ? alu.ir.inputs : alu.ir.outputs; + const bool unpacked = pixel && reg == UINT_MAX && (input ? kind == 28 && mask == 7 : mask == 1); + if ((reg >= 32 && !unpacked) || !mask || mask > 15) + refuse(pc, "invalid signature register or component mask"); + unsigned first = 0, width = 0; + while (!(mask & (1u << first))) + ++first; + while (mask & (1u << (first + width))) + ++width; + if (mask != ((1u << width) - 1) << first) + refuse(pc, "noncontiguous signature channels"); + for (unsigned j = 0; j < rows.size(); ++j) { + const auto &r = rows[j]; + if (r.name == name && r.semantic_index == index) { + if (r.row != reg || r.first != first || r.width != width || r.interpolation != interpolation || + r.component != component || r.kind != kind) + refuse(pc, "inconsistent graphics signature row"); + return j; + } + if (reg != UINT_MAX && r.row == reg && mask & (((1u << r.width) - 1) << r.first)) + refuse(pc, "overlapping graphics signature rows"); + } + rows.push_back({name, index, kind, component, reg, first, width, interpolation}); + return static_cast(rows.size() - 1); + } + unsigned generic(bool input, unsigned reg, unsigned channel, unsigned interpolation) { + const auto &signature = input ? stage.input_signature : stage.output_signature; + for (const auto &s : signature) { + if (s.row != reg || !(s.mask & (1u << channel)) || s.system) + continue; + unsigned component = s.component == 1 ? 5 : s.component == 2 ? 4 : s.component == 3 ? 9 : 0; + if (!component) + refuse(pc, "unknown signature component"); + return row(input, s.name, s.index, system(s.name), component, s.row, s.mask, + !input && component != 9 ? 1 : interpolation); + } + refuse(pc, "missing generic graphics signature row"); + } + string load(unsigned id, unsigned channel) { + auto &s = alu.ir.inputs.at(id); + const unsigned col = channel - s.first; + const bool fp = s.component == 9; + auto v = alu.ir.invoke(fp ? "float" : "i32", fp ? "loadInput.f32" : "loadInput.i32", 4, + {{"i32", to_string(id)}, {"i32", "0"}, {"i8", to_string(col)}, {"i32", "undef"}}, + "nounwind readnone"); + alu.ir.dependencies[v].set(s.row == UINT_MAX ? 128 : s.row * 4 + channel); + s.used |= 1u << col; + return fp ? alu.ir.value("bitcast float " + v + " to i32") : v; + } + string input(unsigned reg) { + if (partial.count(reg)) + refuse(pc, "intermediate interpolation value used outside its pair"); + if (reg < 256) + refuse(pc, "undefined graphics register " + to_string(reg)); + unsigned vgpr = reg - 256; + if (pixel) { + // SPI_PS_INPUT_ADDR allocates enabled inputs consecutively. The + // pull-model barycentrics consume three VGPRs and line stipple one. + unsigned first = 0; + for (unsigned bit = 0; bit < 16; ++bit) { + if (!(stage.pixel_input_address & (1u << bit))) + continue; + const unsigned width = bit == 3 ? 3 : bit < 7 ? 2 : 1; + if (vgpr >= first && vgpr < first + width) { + if (!(stage.pixel_input_enable & (1u << bit))) + break; + if (bit < 7 && bary_modes[bit]) { + // I/J weight vertices one and two. Distinct guest + // pairs may need distinct host system-value elements. + const unsigned mode = bary_modes[bit]; + auto perspective = [](unsigned m) { return m == 2 || m == 3 || m == 6; }; + unsigned index = 0; + for (const auto &r : alu.ir.inputs) { + if (r.kind != 28) continue; + if (r.interpolation == mode) { + index = r.semantic_index; + break; + } + if (perspective(r.interpolation) == perspective(mode)) + refuse(pc, "two barycentric locations in the same perspective mode"); + ++index; + } + alu.ir.features |= 1u << 22; + auto id = row(true, "SV_Barycentrics", index, 28, 9, UINT_MAX, 7, mode); + return load(id, 1 + vgpr - first); + } + if (bit == 15) { + for (const auto &s : stage.input_signature) { + if (s.system != D3D_NAME_POSITION || s.component != 3 || (s.mask & 3) != 3) + continue; + auto id = row(true,"SV_Position",0,3,9,s.row,s.mask,4); + auto coord = [&](unsigned axis) { + auto fp = alu.ir.value("bitcast i32 " + load(id,axis) + " to float"); + return alu.ir.value("fptoui float " + fp + " to i32"); + }; + auto x=coord(0), y=coord(1); + return alu.ir.binary("or", alu.ir.binary("and",x,"65535"), alu.ir.binary("shl",y,"16")); + } + refuse(pc,"packed position requires screen XY"); + } + if (bit == 12) { + for (const auto &s : stage.input_signature) + if (s.system == D3D_NAME_IS_FRONT_FACE && s.mask == 1 && s.component == 1) + return load(row(true, "SV_IsFrontFace", 0, 13, 5, s.row, 1, 1), 0); + refuse(pc, "front face absent from pixel signature"); + } + if (bit < 8 || bit > 11) + break; + unsigned channel = bit - 8; + for (const auto &signature : stage.input_signature) { + if (signature.system != 1 || signature.component != 3 || !(signature.mask & (1u << channel))) + continue; + if (stage.pixel_input_address & 0x11) + refuse(pc, "sample-frequency position input"); + const bool conservative = std::any_of(stage.output_signature.begin(), + stage.output_signature.end(), [](const auto &out) { + return out.system == D3D_NAME_DEPTH_GREATER_EQUAL || + out.system == D3D_NAME_DEPTH_LESS_EQUAL; + }); + return load( + row(true, "SV_Position", 0, 3, 9, signature.row, signature.mask, conservative ? 5 : 4), + channel); + } + refuse(pc, "position absent from pixel input signature"); + } + first += width; + } + refuse(pc, "unsupported pixel entry VGPR " + to_string(vgpr)); + } + if (alu.analysis.result.vertex_fetch) + for (const auto &a : stage.attributes) { + if (vgpr < a.location || vgpr - a.location > a.last_component) + continue; + if (a.usage != 6) + refuse(pc, "unsupported vertex fetch semantic"); + unsigned channel = vgpr - a.location; + return load(generic(true, a.row, channel, 0), channel); + } + if (vgpr != 0 && vgpr != 3) + refuse(pc, "unbound vertex VGPR " + to_string(vgpr)); + string name = vgpr ? "SV_InstanceID" : "SV_VertexID"; + unsigned free = 0; + for (const auto &s : stage.input_signature) { + if (s.name == name) + return load(row(true, name, 0, system(name), 5, s.row, 1, 0), 0); + free = (std::max)(free, s.row + 1); + } + for (unsigned id = 0; id < alu.ir.inputs.size(); ++id) { + const auto &s = alu.ir.inputs[id]; + if (s.name == name && !s.semantic_index && s.kind == system(name)) + return load(id, 0); + free = (std::max)(free, s.row + 1); + } + return load(row(true, name, 0, system(name), 5, free, 1, 0), 0); + } + string quad_source(const Inst &i) { + const unsigned perm = *i.dpp_control; + string word = alu.operand32(i, i.src[0]); + if (perm == 0xe4) + return word; + alu.ir.uses_wave = true; + auto pick = [&](unsigned n) { + return alu.ir.invoke("i32", "quadReadLaneAt.i32", 122, {{"i32", word}, {"i32", to_string(n)}}, "nounwind"); + }; + if (perm == (perm & 3) * 0x55u) + return pick(perm & 3); + if (perm == 0xb1 || perm == 0x4e || perm == 0x1b) + return alu.ir.invoke("i32", "quadOp.i32", 123, + {{"i32", word}, + {"i8", perm == 0xb1 ? "0" + : perm == 0x4e ? "1" + : "2"}}, + "nounwind"); + for (const auto &s : stage.input_signature) { + if (s.system != D3D_NAME_POSITION || s.component != 3 || (s.mask & 3) != 3) + continue; + const bool conservative = + std::any_of(stage.output_signature.begin(), stage.output_signature.end(), [](const auto &out) { + return out.system == D3D_NAME_DEPTH_GREATER_EQUAL || out.system == D3D_NAME_DEPTH_LESS_EQUAL; + }); + auto id = row(true, "SV_Position", 0, 3, 9, s.row, s.mask, conservative ? 5 : 4); + auto parity = [&](unsigned channel) { + auto pos = alu.ir.value("bitcast i32 " + load(id, channel) + " to float"); + auto pixel = alu.ir.invoke("float", "unary.f32", 27, {{"float", pos}}, "nounwind readnone"); + return alu.ir.binary("and", alu.ir.value("fptosi float " + pixel + " to i32"), "1"); + }; + auto x = parity(0), y = parity(1); + auto lane = alu.ir.binary("or", x, alu.ir.binary("shl", y, "1")); + std::array picked; + for (unsigned j = 0; j < 4; ++j) { + unsigned source = (perm >> (2 * j)) & 3; + if (picked[source].empty()) + picked[source] = pick(source); + } + auto result = picked[(perm >> 6) & 3]; + for (int j = 2; j >= 0; --j) + result = alu.select(alu.cmp("eq", lane, to_string(j)), picked[(perm >> (2 * j)) & 3], result); + return result; + } + refuse(i.pc, "general pixel quad permutation requires position XY"); + } + unsigned output(unsigned target, unsigned &channel) { + if (pixel && target < 8) { + // An RTV variant types the target by its format. A signature that says otherwise is not reinterpreted. + const unsigned asked = stage.target_components[target]; + for (const auto &s : stage.output_signature) { + if (s.system != D3D_NAME_TARGET || s.index != target) + continue; + if (s.row != target || !(s.mask & (1u << channel)) || !s.component || s.component > 3) + refuse(pc, "color export incompatible with pixel signature"); + const unsigned component = s.component == 3 ? 9 : s.component == 2 ? 4 : 5; + if (asked && asked != component) + refuse(pc, "RTV variant format disagrees with the pixel signature of target " + to_string(target)); + return row(false, "SV_Target", target, 16, component, s.row, s.mask, 0); + } + if (!stage.output_signature.empty()) + refuse(pc, "color target absent from pixel signature"); + return row(false, "SV_Target", target, 16, asked ? asked : 9, target, 15, 0); + } + if (pixel && target == 8) { + for (const auto &s : stage.output_signature) { + unsigned kind = 0; + if (!channel && s.system == D3D_NAME_DEPTH) + kind = 17; + if (!channel && s.system == D3D_NAME_DEPTH_LESS_EQUAL) + kind = 18; + if (!channel && s.system == D3D_NAME_DEPTH_GREATER_EQUAL) + kind = 19; + if (channel == 1 && s.system == D3D_NAME_STENCIL_REF) + kind = 20; + if (channel == 2 && s.system == D3D_NAME_COVERAGE) + kind = 14; + if (!kind) + continue; + if (s.row != UINT_MAX || s.mask != 1 || s.index || s.component != (channel ? 1u : 3u)) + refuse(pc, "invalid depth, stencil or coverage signature"); + if (kind == 20) + alu.ir.features |= 2048; + return row(false, s.name, 0, kind, channel ? 5 : 9, UINT_MAX, 1, 0); + } + refuse(pc, "unmapped depth, stencil or coverage export"); + } + if (!pixel && target == 12) { + for (const auto &s : stage.output_signature) + if (s.system == 1 || s.name == "SV_Position") + return row(false, "SV_Position", 0, 3, 9, s.row, s.mask, 4); + if (!stage.outputs.empty()) + refuse(pc, "missing position register"); + return row(false, "SV_Position", 0, 3, 9, 0, 15, 4); + } + if (!pixel && (target == 13 || target == 14)) { + // With no misc position vector, POS1 and POS2 pack clip distances + // followed by cull distances, in semantic index/component order. + std::vector distances; + for (const auto &s : stage.output_signature) { + if (s.system == D3D_NAME_RENDER_TARGET_ARRAY_INDEX || s.system == D3D_NAME_VIEWPORT_ARRAY_INDEX || + s.name == "PSIZE") + refuse(pc, "ambiguous clip/cull position export"); + if (s.system == D3D_NAME_CLIP_DISTANCE || s.system == D3D_NAME_CULL_DISTANCE) + distances.push_back(&s); + } + std::sort(distances.begin(), distances.end(), [](const auto *a, const auto *b) { + return std::pair{a->system, a->index} < std::pair{b->system, b->index}; + }); + unsigned index = (target - 13) * 4 + channel; + for (const auto *s : distances) { + if (s->component != 3) + refuse(pc, "non-float clip/cull distance"); + for (unsigned c = 0; c < 4; ++c) + if (s->mask & (1u << c)) { + if (index == 0) { + channel = c; + return row(false, s->name, s->index, s->system == D3D_NAME_CLIP_DISTANCE ? 6 : 7, 9, s->row, + s->mask, 2); + } + --index; + } + } + refuse(pc, "unmapped position export channel"); + } + if (!pixel && target >= 32) + for (const auto &a : stage.outputs) + if (a.location == target - 32 && (!a.mask || (a.mask & (1u << channel)))) { + if (a.usage != 6 || (a.flags & 3)) + refuse(pc, "unsupported packed vertex export"); + return generic(false, a.row, channel, 2); + } + refuse(pc, "unmapped graphics export"); + } + void emit_export(Word first, Word sources) { + const unsigned target = (first >> 4) & 63, mask = first & 15; + const bool compressed = (first & 0x400) != 0; + if ((first & 0x03ffe000) || (compressed && (!pixel || target >= 8 || (mask != 3 && mask != 12 && mask != 15))) || + !exported.emplace(target, mask).second) + refuse(pc, "unsupported graphics export mask or repeated target"); + if (target == 9 || (!pixel && target == 32 && stage.outputs.empty() && + std::none_of(stage.output_signature.begin(), stage.output_signature.end(), + [](const auto &s) { return !s.system; }))) + return; + if (!mask) + refuse(pc, "empty enabled graphics export"); + unsigned signature_mask = 15; + if (!pixel && target >= 32) { + // PARAM exports have four hardware lanes, including padding when + // the logical signature row is narrower. Preserve packed semantics + // belonging to the same row and let stage linkage check all PS reads. + unsigned channels = 0; + for (const auto &a : stage.outputs) { + if (a.location != target - 32 || a.usage != 6 || (a.flags & 3)) continue; + unsigned declared = 0; + for (const auto &s : stage.output_signature) + if (s.row == a.row && !s.system) declared |= s.mask; + if (!declared) refuse(pc, "vertex parameter has no output signature"); + channels |= declared; + } + if (channels) signature_mask = channels; + } + if (pixel && target < 8) + alu.analysis.result.pixel_writes[target] = mask; + for (unsigned c = 0; c < 4; ++c) + if (mask & signature_mask & (1u << c)) { + auto bits = alu.read(256 + ((sources >> (8 * (compressed ? c / 2 : c))) & 255)); + unsigned channel = c; + auto id = output(target, channel); + auto &s = alu.ir.outputs[id]; + if (s.row == UINT_MAX) + channel = 0; + if (channel < s.first || channel >= s.first + s.width) + refuse(pc, "export outside signature"); + const bool fp = s.component == 9; + if (compressed) { + if (!fp) refuse(pc, "packed color export requires floating target"); + auto half = alu.subword(bits, 4 + (c & 1), false); + auto value = alu.ir.invoke("float", "legacyF16ToF32", 131, {{"i32",half}}, "nounwind readnone"); + bits = alu.ir.value("bitcast float " + value + " to i32"); + } + auto v = fp ? alu.ir.value("bitcast i32 " + bits + " to float") : bits; + alu.ir.invoke("void", fp ? "storeOutput.f32" : "storeOutput.i32", 5, + {{"i32", to_string(id)}, + {"i32", "0"}, + {"i8", to_string(channel - s.first)}, + {fp ? "float" : "i32", v}}, + "nounwind"); + s.used |= 1u << (channel - s.first); + if (s.row == UINT_MAX) + continue; + if (alu.ir.loop_dependencies) + alu.ir.output_values[s.row * 4 + channel].push_back(v); + if (auto d = alu.ir.dependencies.find(v); d != alu.ir.dependencies.end()) + alu.ir.output_dependencies[s.row * 4 + channel] |= d->second; + } + } +}; + +// Acyclic scalar branches preserve the rasterizer's per-invocation SSA values. +// An SGPR comparison can select a path without introducing a guest EXEC mask. +struct GraphicsBlock { + size_t begin, end; + std::vector successors; + unsigned predecessors = 0; +}; +// An EXECZ skip over lane-local ALU with an exact restore has a per-lane +// equivalent. Mark that region before building the scalar CFG so the merge +// is a select on each VGPR, including the old value of inactive lanes. +struct GraphicsMaskRegions { + std::set saves, complements, restores; + std::set sample_begins, sample_ends; + std::set compares, cmpx_starts, unions, intersections, inner_saves, inner_restores; + std::map> expired; + std::map enclosing_mask; + std::map branch_saves; + std::map> lane_branches; + std::map branch_merges; + struct MaskCapture { unsigned skip, value; }; + std::map captures; + std::set vertex_anchors, vertex_partitions; + std::map mask_inputs; + std::set vertex_mask_compares, uniform_mask_tests; + std::set scalar_mask_selects; + std::map then_fallthroughs; + std::set scalar_tail_merges; + static unsigned scalar_width(const Inst &i) { + if (i.enc == Encoding::Smem) return memory_count(i); + if (i.enc == Encoding::Vopc) return 2; + if (i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2 || i.enc == Encoding::Sopk) + return i.name.find("64") == Name::npos ? 1 : 2; + return i.name == "v_readfirstlane_b32" || i.name == "v_readlane_b32" ? 1 : 0; + } + // Track pairs equal to the initial EXEC, on every path. An inner save + // followed by a restore may preserve the value even across nested skips. + static bool preserves_exec(const Program &p, size_t begin, size_t end, unsigned parent = 126) { + using Pairs = std::bitset<128>; + std::vector> incoming(end-begin+1); + incoming.front().emplace().set(126).set(parent); + for (size_t j = begin; j < end; ++j) { + const auto &at = incoming[j-begin]; + if (!at) continue; + auto known = *at; + const auto &i = p.code[j]; + const bool was_exec = known[126]; + const bool copy = i.name == "s_mov_b64" && i.src[0] < 128 && known[i.src[0]]; + auto clobber = [&](unsigned dst,unsigned count) { + for (unsigned n = dst; n < dst + count && n < 128; ++n) + known.reset(n & ~1u); + }; + clobber(i.dst, scalar_width(i)); + if (auto carry = carry_destination(i)) clobber(*carry,2); + if (i.name.find("saveexec") != Name::npos) { + known[126] = false; + known[i.dst] = was_exec; + } else if (copy) known[i.dst] = true; + auto edge = [&](size_t target) { + if (target <= j) return false; + if (target > end) return parent != 126; + auto &destination = incoming[target-begin]; + if (destination) *destination &= known; + else destination = known; + return true; + }; + if (i.branch() && !edge(p.at.at(i.target()))) return false; + if ((!i.branch() || i.op != 2) && !edge(j+1)) return false; + } + return incoming.back() && (*incoming.back())[126] && (*incoming.back())[parent]; + } + static bool local_alu(const Inst &i) { + return (i.enc == Encoding::Vop1 || i.enc == Encoding::Vop2 || i.enc == Encoding::Vop3) && + i.dst >= 256 && !i.dpp_control && i.name.find("lane") == Name::npos && + i.name.find("mbcnt") == Name::npos && i.name.find("_co_") == Name::npos; + } + static void skip_proven(Inst &skip) { + skip.enc = Encoding::Sopp; + skip.op = 0; + skip.name = "s_nop"; // VGPR writes use the corresponding lane predicate. + } + void vertex_scalar_tails(const Program &p, const std::multimap &entries) { + const auto &code = p.code; + for (size_t k=0; k+2 104 || (parent & 1) || + (has_else && inv.src[0] != parent)) continue; + // An earlier restore may dominate across a uniform diamond. + // Exclude outside entries and prove that both EXEC and the saved + // pair retain the anchor's value on all paths reaching the mask. + size_t anchor = k; + bool anchored = false; + while (anchor) { + const auto &a = code[--anchor]; + if (a.name != "s_mov_b64" || !((a.dst == 126 && a.src[0] == parent) || + (a.dst == parent && a.src[0] == 126))) continue; + auto entry = entries.upper_bound(a.pc); + for (; entry != entries.end() && entry->first <= mask.pc; ++entry) + if (entry->second < a.pc || entry->second >= mask.pc) break; + anchored = (entry == entries.end() || entry->first > mask.pc) && preserves_exec(p,anchor+1,k,parent); + break; + } + if (!anchored) continue; + for (auto entry=entries.upper_bound(mask.pc); entry!=entries.end() && entry->first<=restore.pc; ++entry) + if (entry->second != skip.pc) + refuse(entry->first,"branch enters a vertex EXEC scalar-tail region"); + std::set modified{106,107,128}; + for (size_t j=k+2; j entries; + for (const auto &i : program.code) + if (i.branch()) entries.emplace(i.target(), i.pc); + // Only carry SCC into a full numeric mask if its reaching producer + // compares ordinary scalar operands, with no join or intervening + // scalar writer. Per-lane predicates cannot establish those 64 bits. + bool scalar_test = false; + auto scalar_data = [](unsigned r) { return r <= 105 || (r >= 128 && r <= 248) || r == 255; }; + for (const auto &i : program.code) { + if (entries.count(i.pc)) scalar_test = false; + if (i.name == "s_cselect_b64" && scalar_test) scalar_mask_selects.insert(i.pc); + if (i.enc == Encoding::Sopc) + scalar_test = (i.name.substr(0,6) == "s_cmp_" || i.name.substr(0,8) == "s_bitcmp") && + scalar_data(i.src[0]) && scalar_data(i.src[1]); + else if (i.branch() || i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2 || i.enc == Encoding::Sopk) + scalar_test = false; + } + // Follow the selected lane's bit from a compare into an explicit + // SGPR pair, through VCC intersections, up to its AND_SAVEEXEC. + // Restrict the chain to one block and the same reaching EXEC. + if (vertex && !wave32) { + const auto &code = program.code; + for (size_t j=0; j 104 || (cmp.dst & 1) || + cmp.name.substr(0,6) != "v_cmp_" || cmp.name.find("class") != Name::npos || + cmp.clamp || cmp.scale || cmp.subword) continue; + unsigned bit = 1024 + cmp.pc; + std::map chain; + for (size_t k=j+1; k= program.code.size()) continue; + const auto &inverse = program.code[middle]; + if (cmpx || from_mask) { + if ((inverse.name != "s_andn2_b64" && inverse.name != mov) || inverse.dst != 126 || + inverse.src[0] > 104 || (inverse.src[0] & 1)) continue; + save.dst = inverse.src[0]; + // A dominating save or restore with no subsequent writer + // identifies the exact parent of this CMPX, including nested + // regions where the currently executing lane is already active. + bool parent = false; + for (size_t back = k; back && !entries.count(program.code[back].pc);) { + const auto &prev = program.code[--back]; + if (prev.name == mov && ((prev.dst == 126 && prev.src[0] == save.dst) || + (prev.dst == save.dst && prev.src[0] == 126))) { + parent = true; + if (prev.src[0] == 126) vertex_anchors.insert(prev.pc); + break; + } + const unsigned width = scalar_width(prev); + auto overlaps = [&](unsigned r) {return width && prev.dst < r+2 && r < prev.dst+width;}; + if (prev.branch() || overlaps(126) || overlaps(save.dst) || carry_destination(prev) || + prev.name.find("saveexec") != Name::npos) break; + } + if (!parent || (captured && capture.dst == save.dst)) continue; + } + if (save.dst > (wave32 ? 105u : 104u) || (!wave32 && (save.dst & 1))) continue; + const bool two_arms = inverse.name == (wave32 ? "s_andn2_b32" : "s_andn2_b64") && + inverse.dst == 126 && inverse.src[0] == save.dst && inverse.src[1] == 126; + if (two_arms && middle + 1 >= program.code.size()) continue; + auto &else_skip = program.code[two_arms ? middle + 1 : middle]; + if (two_arms && (!else_skip.branch() || else_skip.op != 8 || else_skip.target() <= else_skip.next)) continue; + const auto end = two_arms ? program.at.at(else_skip.target()) : middle; + const auto &restore = program.code[end]; + if (restore.name != mov || restore.dst != 126 || restore.src[0] != save.dst) continue; + const auto begin = k + 2 + split; + // For a VS with control flow inside the masked region, keep a + // real lane branch. Victory 9376fd6 ir.rs::without_skips and + // gfx2hlsl.py's EXECZ analysis both require that scalar effects + // of a skipped arm cannot escape. Here the branch guards reads + // and the merge invalidates scalar definitions from either arm. + const bool branched = cmpx || from_mask || saved_mask || (vertex && std::any_of(program.code.begin()+begin,program.code.begin()+end, + [&](const Inst &i) {return i.branch() && (!two_arms || i.pc != else_skip.pc);})); + if (branched) { + for (auto it = entries.upper_bound(save.pc); it != entries.end() && it->first <= restore.pc; ++it) { + const unsigned dst = it->first, src = it->second; + if (src == skip.pc || (two_arms && src == else_skip.pc)) continue; + const unsigned start = two_arms && src >= else_skip.next ? else_skip.next : skip.next; + const unsigned limit = two_arms && src < inverse.pc ? capture.pc : restore.pc; + if (src < start || src >= limit || dst < start || dst > limit || dst <= src) + refuse(dst, "branch enters or crosses a masked vertex arm"); + } + std::set first_writes{106,107,128}, second_writes{106,107,128}; + for (size_t j=begin; j restore.pc)) || + v.name == "s_endpgm" || v.enc == Encoding::Export || v.enc == Encoding::Lds || + v.enc == Encoding::Fetch || v.enc == Encoding::FixedFetch || + (v.enc == Encoding::Image && v.op != 0 && v.op != 1 && v.op != 14 && + v.op != 34 && v.op != 36 && v.op != 39 && v.op != 47 && v.op != 71) || + (v.enc == Encoding::Mubuf && v.name.find("load") == Name::npos)) + refuse(v.pc,"masked vertex arm has an unsupported exit or memory effect"); + auto &writes = two_arms && j > middle ? second_writes : first_writes; + auto record = [&](unsigned dst,unsigned width) { + if (width && dst < save.dst + (wave32 ? 1u : 2u) && save.dst < dst + width) + refuse(v.pc,"masked vertex arm overwrites its saved EXEC"); + for (unsigned x = dst; x < dst + width && x < 128; ++x) writes.insert(x); + }; + record(v.dst,scalar_width(v)); + if (auto carry = carry_destination(v)) record(*carry,2); + const auto arm_start = two_arms && j > middle ? middle+2 : begin; + if (!wave32 && v.name == "s_and_b64" && v.dst <= 104 && v.src[0] == v.dst && + v.src[1] == 126 && j > arm_start) { + const auto &cmp = program.code[j-1]; + auto uniform_source = [](unsigned s) { + return s <= 105 || (s >= 128 && s <= 248) || s == 255; + }; + if (cmp.enc == Encoding::Vopc && cmp.dst == v.dst && cmp.name.substr(0,6) == "v_cmp_" && + cmp.name.find("class") == Name::npos && !cmp.subword && !cmp.clamp && !cmp.scale && + uniform_source(cmp.src[0]) && uniform_source(cmp.src[1]) && !entries.count(v.pc) && + preserves_exec(program,arm_start,j-1)) { + vertex_mask_compares.insert(cmp.pc); + mask_inputs[v.pc] = 1024 + cmp.pc; + uniform_mask_tests.insert(v.pc); + } + } + } + if (two_arms && !preserves_exec(program,begin,join)) + refuse(capture.pc, captured ? "VCC capture requires the reaching CMPX mask on every path" : + "vertex ELSE requires its THEN mask on every path"); + if (captured) { + if (!two_arms) refuse(capture.pc,"VCC capture requires a matching ELSE and restore"); + const unsigned bit = 1024 + capture.pc; + captures.emplace(capture.pc, MaskCapture{skip.pc,bit}); + // Captured pair is numeric poison. A following AND with + // VCC may feed another EXEC-only arm through its bit. + branch_merges.emplace(capture.pc,1024 + save.pc); + if (end+3 < program.code.size() && !second_writes.count(capture.dst) && + !second_writes.count(capture.dst+1)) { + const auto &cmp = program.code[end+1], &andv = program.code[end+2], &act = program.code[end+3]; + if (cmp.enc == Encoding::Vopc && cmp.dst == 106 && andv.name == "s_and_b64" && + andv.dst == capture.dst && andv.src[0] == 106 && andv.src[1] == capture.dst && + act.name == "s_and_b64" && act.dst == 126 && act.src[0] == capture.dst && + act.src[1] == 126 && !entries.count(cmp.pc) && !entries.count(andv.pc) && !entries.count(act.pc)) { + mask_inputs[andv.pc] = bit; + mask_inputs[act.pc] = 1024 + andv.pc; + } + } + } + // Unique virtual register; no guest write aliases it. + const unsigned condition = 1024 + save.pc; + branch_saves.emplace(save.pc,condition); + lane_branches.emplace(skip.pc,std::make_pair(condition,false)); + if (split) skip_proven(program.code[k+1]); + if (two_arms) { + branch_merges.emplace(inverse.pc, condition); + lane_branches.emplace(else_skip.pc,std::make_pair(condition,true)); + expired[inverse.pc].insert(first_writes.begin(),first_writes.end()); + } + branch_merges.emplace(restore.pc, condition); + expired[restore.pc].insert(first_writes.begin(),first_writes.end()); + expired[restore.pc].insert(second_writes.begin(),second_writes.end()); + continue; // inner structured regions still need classification + } + for (auto it = entries.upper_bound(save.pc); it != entries.end() && it->first <= restore.pc; ++it) + if (it->second != skip.pc && (!two_arms || it->second != else_skip.pc)) + refuse(it->first, "branch enters a masked graphics region"); + for (size_t j = k + 2 + split; j < end; ++j) { + const auto &body = program.code[j]; + if (two_arms && (j == middle || j == middle + 1)) continue; + if (body.pc != program.code[j - 1].next || body.next != program.code[j + 1].pc || + !(local_alu(body) || body.name == "s_waitcnt" || body.name == "s_nop" || + (body.enc == Encoding::Image && body.op == 0x27))) + refuse(body.pc, "masked graphics region requires lane-local vector arithmetic"); + } + saves.insert(save.pc); + restores.insert(restore.pc); + if (split) skip_proven(program.code[k + 1]); + skip_proven(skip); + if (two_arms) { + complements.insert(inverse.pc); + skip_proven(else_skip); + } + k = end; + } + // GFX10 CMPX changes EXEC alone. With no wave-wide skip these arms + // still partition a proven enclosing mask. No entry may bypass CMPX. + const auto &code = program.code; + for (size_t k = 0; k < code.size(); ++k) { + const auto &start = code[k]; + auto restore_mask = [wave32](const Inst &i) { + return i.dst == 126 && ((wave32 && i.name == "s_mov_b32" && i.src[0] <= 105) || + (i.name == "s_mov_b64" && i.src[0] <= 104 && !(i.src[0] & 1))); + }; + if (!restore_mask(start)) continue; + size_t end = k + 1; + bool sampled = false; + for (; end < code.size(); ++end) { + const auto &i = code[end]; + if (i.enc == Encoding::Image && i.op >= 0x20 && i.op <= 0x3f) sampled = true; + else if (i.name != "s_waitcnt" && i.name != "s_nop") break; + } + if (!sampled || end == code.size() || !restore_mask(code[end]) || code[end].src[0] == start.src[0]) continue; + auto entry = entries.upper_bound(start.pc); + if (entry != entries.end() && entry->first <= code[end].pc) continue; + sample_begins.insert(start.pc); + sample_ends.insert(code[end].pc); + k = end; + } + for (size_t k = 0; !wave32 && k < code.size(); ++k) { + const auto &cmp = code[k]; + if (cmp.enc != Encoding::Vopc || cmp.name.substr(0,7) != "v_cmpx_" || + cmp.dst != 126 || cmp.scale || cmp.clamp || cmp.subword) continue; + auto local = [&](const Inst &i) { + return local_alu(i) || (i.enc == Encoding::Vopc && i.dst == 106 && + i.name.substr(0,6) == "v_cmp_" && !i.clamp && !i.scale && !i.subword && + i.name.find("class") == Name::npos); + }; + size_t mid = k + 1; + while (mid < code.size() && local(code[mid])) ++mid; + if (mid == code.size()) continue; + const auto &inverse = code[mid]; + if (inverse.name != "s_andn2_b64" || inverse.dst != 126 || inverse.src[0] > 104 || + (inverse.src[0] & 1) || inverse.src[1] != 126) continue; + size_t end = mid + 1; + while (end < code.size() && local(code[end])) ++end; + if (end == code.size()) continue; + const auto &restore = code[end]; + if (restore.name != "s_mov_b64" || restore.dst != 126 || restore.src[0] != inverse.src[0]) continue; + auto entry = entries.upper_bound(cmp.pc); + if (entry != entries.end() && entry->first <= restore.pc) + refuse(entry->first,"branch enters a CMPX region"); + if (vertex) { + // Both arms contain only vector instructions. Each VS + // invocation reaches this point with its own enclosing bit + // set. Prove the complement uses that same saved EXEC. + size_t anchor = k; + while (anchor && (code[anchor-1].name == "s_waitcnt" || code[anchor-1].name == "s_nop")) + --anchor; + if (!anchor) continue; + const auto &save = code[anchor-1]; + const auto entrant = entries.upper_bound(save.pc); + if (save.name != "s_mov_b64" || save.src[0] != 126 || save.dst != inverse.src[0] || + (entrant != entries.end() && entrant->first <= cmp.pc)) continue; + vertex_anchors.insert(save.pc); + vertex_partitions.insert(cmp.pc); + } + cmpx_starts.insert(cmp.pc); + enclosing_mask.emplace(cmp.pc,inverse.src[0]); + complements.insert(inverse.pc); + restores.insert(restore.pc); + k = end; + } + // A second compare may target an SGPR mask and be ORed with VCC. + // Each arm is a straight-line region. Conditional SMEM results are + // usable within their arm only; poison them before lowering its join. + for (size_t k = 0; k + 4 < program.code.size(); ++k) { + auto &code = program.code; + const auto &cmp = code[k], &combine = code[k+1], &active = code[k+2]; + auto &skip = code[k+3]; + if (wave32 || cmp.enc != Encoding::Vopc || cmp.name.substr(0,6) != "v_cmp_" || + cmp.dst > 104 || (cmp.dst & 1) || cmp.subword || cmp.clamp || cmp.scale || + combine.name != "s_or_b64" || combine.src[0] != 106 || combine.src[1] != cmp.dst || + combine.dst != cmp.dst || active.name != "s_and_b64" || active.dst != 126 || + active.src[0] != cmp.dst || active.src[1] != 126 || !skip.branch() || skip.op != 8 || + skip.target() <= skip.next) continue; + const size_t mid = program.at.at(skip.target()); + if (mid + 1 >= code.size()) continue; + const auto &inverse = code[mid]; + auto &skip_else = code[mid+1]; + if (inverse.name != "s_andn2_b64" || inverse.dst != 126 || inverse.src[0] > 104 || + (inverse.src[0] & 1) || inverse.src[1] != 126 || !skip_else.branch() || + skip_else.op != 8 || skip_else.target() <= skip_else.next) continue; + const size_t end = program.at.at(skip_else.target()); + const auto &restore = code[end]; + if (restore.name != "s_mov_b64" || restore.dst != 126 || restore.src[0] != inverse.src[0]) continue; + for (auto it = entries.upper_bound(cmp.pc); it != entries.end() && it->first <= restore.pc; ++it) + if (it->second != skip.pc && it->second != skip_else.pc) + refuse(it->first, "branch enters a partitioned EXEC region"); + for (auto [begin, limit] : {std::pair{k+4,mid}, std::pair{mid+2,end}}) { + unsigned saved = UINT_MAX; + auto &dead = expired[code[limit].pc]; + for (size_t j = begin; j < limit; ++j) { + const auto &i = code[j]; + if (i.next != code[j+1].pc) refuse(i.pc,"noncontiguous EXEC region"); + if (local_alu(i) || i.name == "s_waitcnt" || i.name == "s_nop" || + (i.enc == Encoding::Image && i.op == 0x27)) continue; + unsigned width = 0; + if (i.enc == Encoding::Smem) { + width = memory_count(i); + } else if (i.name == "s_and_saveexec_b64" && saved == UINT_MAX && + i.src[0] <= 104 && !(i.src[0] & 1) && !(i.dst & 1)) { + saved = i.dst; inner_saves.insert(i.pc); width = 2; + } else if (i.name == "s_or_saveexec_b64" && i.src[0] == saved && !(i.dst & 1)) { + saved = UINT_MAX; inner_restores.insert(i.pc); width = 2; + } else refuse(i.pc,"unsupported operation inside partitioned EXEC"); + if (i.dst + width > 106 || + (i.dst < inverse.src[0]+2 && inverse.src[0] < i.dst+width) || + (saved != UINT_MAX && i.enc == Encoding::Smem && i.dst < saved+2 && saved < i.dst+width)) + refuse(i.pc,"clobbered enclosing EXEC mask"); + for (unsigned r = i.dst; r < i.dst + width; ++r) dead.insert(r); + } + if (saved != UINT_MAX) refuse(code[limit].pc, "unbalanced inner EXEC"); + } + compares.insert(cmp.pc); unions.insert(combine.pc); intersections.insert(active.pc); + enclosing_mask.emplace(active.pc,inverse.src[0]); + complements.insert(inverse.pc); restores.insert(restore.pc); + skip_proven(skip); skip_proven(skip_else); + k = end; + } + if (vertex && !wave32) vertex_scalar_tails(program,entries); + } +}; +std::map graphics_blocks(const Program &program, const GraphicsMaskRegions ®ions) { + std::set leaders{0}; + for (auto edge : regions.then_fallthroughs) leaders.insert(edge.second); + for (const auto &i : program.code) { + if (!i.branch()) + continue; + if (i.op != 2 && (i.op < 4 || i.op > 7) && !regions.lane_branches.count(i.pc)) { + const auto k = program.at.at(i.pc); + if (k && (i.op == 8 || i.op == 9)) { + const auto &writer = program.code[k - 1]; + if (writer.next == i.pc && writer.dst == 126 && + (writer.name == "s_wqm_b32" || writer.name == "s_wqm_b64")) + refuse(i.pc, "WQM branch on a wave mask needs the complete guest vote or a quad-local continuation"); + } + refuse(i.pc, "graphics branch on a wave mask"); + } + leaders.insert(i.target()); + if (i.op != 2) + leaders.insert(i.next); + } + std::map blocks; + for (auto it = leaders.begin(); it != leaders.end(); ++it) { + const auto next = std::next(it); + size_t end = next == leaders.end() ? program.code.size() : program.at.at(*next); + auto &block = blocks.emplace(*it, GraphicsBlock{program.at.at(*it), end}).first->second; + const auto &last = program.code[end - 1]; + if (last.branch()) + block.successors.push_back(last.target()); + if (last.name != "s_endpgm" && (!last.branch() || (last.op != 2 && last.target() != last.next))) + block.successors.push_back(regions.then_fallthroughs.count(last.pc) ? + regions.then_fallthroughs.at(last.pc) : last.next); + } + for (const auto &[label, block] : blocks) + for (auto next : block.successors) + ++blocks.at(next).predecessors; + return blocks; +} + +struct GraphicsEdge { + unsigned from; + std::map values; + std::set written; + std::map partial; + std::map exports; +}; + +void join_graphics(GraphicsStage &g, std::vector &edges, const GraphicsMaskRegions ®ions) { + auto &alu = g.alu; + alu.guarded_ij.clear(); + if (edges.size() == 1) { + auto &edge = edges.front(); + alu.graphics_registers = std::move(edge.values); + g.overwritten_inputs = std::move(edge.written); + g.partial = std::move(edge.partial); + g.exported = std::move(edge.exports); + return; + } + alu.graphics_registers.clear(); + g.partial.clear(); + g.exported = edges.front().exports; + g.overwritten_inputs.clear(); + for (const auto &edge : edges) { + if (edge.exports != g.exported) + refuse(g.pc, "inconsistent graphics exports at branch join"); + g.overwritten_inputs.insert(edge.written.begin(), edge.written.end()); + } + for (const auto &[reg, part] : edges.front().partial) { + bool same = std::all_of(edges.begin() + 1, edges.end(), [&](const auto &edge) { + auto it = edge.partial.find(reg); + if (it == edge.partial.end()) + return false; + const auto &v = it->second; + return v.attribute == part.attribute && v.channel == part.channel && v.source == part.source && + v.mode == part.mode; + }); + if (same) + g.partial.emplace(reg, part); + } + DxilModule::InputMask control_inputs; + if (auto merge = regions.branch_merges.find(g.pc); merge != regions.branch_merges.end()) { + for (const auto &edge : edges) + control_inputs |= alu.ir.dependencies[edge.values.at(merge->second)]; + } + for (unsigned r : g.overwritten_inputs) { + if (g.partial.count(r)) + continue; + string first, incoming; + bool same = true, defined = true; + for (const auto &edge : edges) { + auto it = edge.values.find(r); + const string absent; + const auto &value = it != edge.values.end() ? it->second + : edge.written.count(r) ? absent + : g.incoming_input(r); + if (value.empty()) { + defined = false; + break; + } + if (incoming.empty()) + first = value; + else { + same &= value == first; + incoming += ", "; + } + incoming += "[ " + value + ", %g" + to_string(edge.from) + " ]"; + } + alu.graphics_registers[r] = !defined ? string{} : same ? first : alu.ir.value("phi i32 " + incoming); + if (defined && !same) + alu.ir.dependencies[alu.graphics_registers[r]] |= control_inputs; + } +} + +// A loop may consume a VGPR defined on a backedge. Give each requested +// block-entry value a name, then populate its phi once all exits are known. +// Only registers actually read through a block boundary acquire phis. +template +void emit_graphics_loops(GraphicsStage &g, const Program &program, const std::map &blocks, + EmitInstruction emit) { + auto &alu = g.alu; + auto &ir = alu.ir; + using Values = std::map; + using Entry = std::pair; + std::map> preds; + std::map exits; + std::map body, phis; + std::set requested; + std::deque pending; + std::vector predicates; + std::optional> exports; + auto initial = alu.graphics_registers; + auto entry_input = alu.graphics_input; + std::ostringstream prologue; + prologue.swap(ir.body); + ir.loop_dependencies = true; + auto phi = [&](unsigned block, unsigned reg) { + Entry key{block, reg}; + if (requested.insert(key).second) + pending.push_back(key); + return "%p" + to_string(block) + "r" + to_string(reg); + }; + for (const auto &[label, block] : blocks) + for (auto target : block.successors) + preds[target].push_back(label); + for (const auto &[label, block] : blocks) { + g.exported.clear(); + g.partial.clear(); + g.overwritten_inputs.clear(); + alu.graphics_registers.clear(); + alu.graphics_input = [&, label](unsigned r) { + if (g.partial.count(r)) + refuse(g.pc, "intermediate interpolation value consumed in loop"); + return phi(label, r); + }; + for (size_t k = block.begin; k < block.end; ++k) { + const auto &i = program.code[k]; + if (i.branch() || i.name == "s_endpgm") + continue; + if (i.enc == Encoding::Export && !block.successors.empty()) + refuse(i.pc, "looping graphics shader exports before its exit block"); + if ((i.enc == Encoding::Interp || i.enc == Encoding::Fetch) && (label || !preds[label].empty())) + refuse(i.pc, "looping graphics shader uses an entry input operation after a branch"); + emit(i, program.before[k]); + } + if (!g.partial.empty()) + refuse(label, "interpolation pair crosses a loop block boundary"); + const auto &last = program.code[block.end - 1]; + if (block.successors.empty()) { + if (g.exported.empty() || (!g.pixel && !g.exported.count(12)) || (exports && *exports != g.exported)) + refuse(last.pc, "inconsistent loop exit exports"); + exports = g.exported; + ir.body << " br label %graphicsEnd\n"; + } else if (block.successors.size() == 1) { + ir.body << " br label %g" << block.successors.front() << "\n"; + } else { + auto cond = alu.cmp((last.op & 1) ? "ne" : "eq", alu.read(last.op >= 6 ? 106 : 128), "0"); + predicates.push_back(cond); + ir.body << " br i1 " << cond << ", label %g" << last.target() << ", label %g" << last.next << "\n"; + } + exits.emplace(label, std::move(alu.graphics_registers)); + body.emplace(label, ir.body.str()); + ir.body.str({}); + } + if (!exports) + refuse(0, "graphics loop has no reachable exit"); + alu.graphics_input = std::move(entry_input); + ir.body.swap(prologue); + g.partial.clear(); + while (!pending.empty()) { + auto [label, reg] = pending.front(); + pending.pop_front(); + auto name = phi(label, reg); + string incoming; + auto add = [&](const string &v, const string &from) { + if (v.empty()) + refuse(label, "graphics register undefined on an incoming loop edge"); + if (!incoming.empty()) + incoming += ", "; + incoming += "[ " + v + ", %" + from + " ]"; + if (!v.empty() && v.front() == '%') + ir.consumers[v].push_back(name); + }; + if (label == 0) { + auto value = initial.find(reg); + if (value == initial.end()) + value = initial.emplace(reg, g.input(reg)).first; + add(value->second, "entry"); + } + for (unsigned pred : preds[label]) { + const auto &values = exits.at(pred); + auto value = values.find(reg); + add(value != values.end() ? value->second : phi(pred, reg), "g" + to_string(pred)); + } + phis[label] += " " + name + " = phi i32 " + incoming + "\n"; + } + ir.finish_loop_dependencies(); + for (const auto &condition : predicates) + if (ir.dependencies[condition].any()) + refuse(0, "graphics loop condition depends on a varying input"); + ir.body << " br label %g0\n"; + for (const auto &[label, code] : body) + ir.body << "g" << label << ":\n" << phis[label] << code; +} + +// An all-ones EXEC island can use VGPRs as a wave-wide register array. +// Keep separately defined guest lanes in SSA. This also works when the +// desktop PS runs on wave32 or has only a single covered quad. A varying +// pre-island pixel value has no proven address in this guest lane array. +struct GraphicsFullWave { + DirectCompute &alu; + unsigned width; + std::optional saved; + using Lanes = std::vector; + std::map vectors; + + bool emit(const Inst &i, const Program &program) { + const bool narrow = width == 32; + const auto mov = narrow ? "s_mov_b32" : "s_mov_b64"; + if (!saved) { + if (i.name != (narrow ? "s_or_saveexec_b32" : "s_or_saveexec_b64") || i.src[0] != 193) + return false; + if (i.dst > (narrow ? 105u : 104u) || (!narrow && (i.dst & 1)) || !alu.graphics_predicate.empty()) + refuse(i.pc, "invalid full-wave EXEC save"); + auto close = std::find_if(program.code.begin()+program.at.at(i.pc)+1, program.code.end(), + [&](const Inst &j) { return j.branch() || j.name == "s_endpgm" || (j.name == mov && j.dst == 126); }); + if (close == program.code.end() || close->name != mov || close->src[0] != i.dst || + std::any_of(program.code.begin(), program.code.end(), [&](const Inst &j) { + return j.branch() && j.target() > i.pc && j.target() <= close->pc; + })) + refuse(i.pc, "full-wave EXEC island needs a matching restore in the same block"); + saved = i.dst; + alu.write(*saved, {}); + if (!narrow) alu.write(*saved+1, {}); + alu.write(128, "1"); // Nonempty EXEC after OR with all ones. + return true; + } + if (i.name == mov && i.dst == 126 && i.src[0] == *saved) { + for (const auto &[reg, values] : vectors) { + const bool uniform = std::all_of(values.begin()+1, values.end(), + [&](const string &v) { return v == values.front(); }); + alu.write(reg, uniform ? values.front() : string{}); + } + vectors.clear(); + saved.reset(); + return true; + } + if (i.subword || i.abs || i.neg || i.scale || i.clamp || (i.wide && (i.a & 0x7800u))) + refuse(i.pc, "unsupported full-wave operand modifier"); + auto scalar = [&](unsigned r) { + if (r >= 256 || r == *saved || (!narrow && r == *saved+1)) + refuse(i.pc, "full-wave source needs the original pixel lane values"); + if (r == 126 || (!narrow && r == 127)) return to_string(~Word{0}); + auto value = alu.operand32(i,r); + if (alu.ir.loop_dependencies || alu.ir.dependencies[value].any()) + refuse(i.pc, "full-wave scalar source depends on pixel input"); + return value; + }; + auto constant = [&](unsigned r) { + if (r == 126 || (!narrow && r == 127)) return ~Word{0}; + if (r == *saved || (!narrow && r == *saved+1)) refuse(i.pc, "saved EXEC used as a lane selector"); + const auto value = source(i, r, program.before[program.at.at(i.pc)]); + if (value.type != Symbol::Type::constant) refuse(i.pc, "dynamic pixel wave lane selector"); + return value.value; + }; + auto lane_value = [&](unsigned r, unsigned lane) -> string { + if (r < 256) return scalar(r); + auto found = vectors.find(r); + if (found == vectors.end() || found->second[lane].empty()) + refuse(i.pc, "pixel wave register needs an unobserved source lane"); + return found->second[lane]; + }; + if (i.name == "v_writelane_b32") { + auto &lanes = vectors.try_emplace(i.dst, width).first->second; + lanes[constant(i.src[1]) & (width-1)] = scalar(i.src[0]); + return true; + } + if (i.name == "v_readlane_b32") { + if (i.dst == *saved || (!narrow && i.dst == *saved+1)) + refuse(i.pc, "lane read overwrites saved EXEC"); + alu.write(i.dst, lane_value(i.src[0],constant(i.src[1]) & (width-1))); + return true; + } + if (i.name == "v_permlane16_b32" || i.name == "v_permlanex16_b32") { + const Word selectors[]{constant(i.src[1]),constant(i.src[2])}; + const unsigned other = i.name == "v_permlanex16_b32" ? 16 : 0; + Lanes result(width); + for (unsigned lane=0; lane> 3) & 1] >> (4*(lane & 7))) & 15; + result[lane] = lane_value(i.src[0], ((lane & ~15u) ^ other) + pick); + } + vectors[i.dst] = std::move(result); + return true; + } + if (i.name != "v_mov_b32" && i.name != "v_min_u32" && i.name != "v_max_u32" && i.name != "v_xor_b32") + refuse(i.pc, "unsupported pixel full-wave operation " + string(i.name)); + Lanes result(width); + // Broadcasts and reductions frequently leave many equal SSA pairs. + // Reuse each expression so a wave-uniform result can leave the island. + std::map,string> terms; + for (unsigned lane=0; lane> (2*(lane & 3))) & 3); + auto a = lane_value(i.src[0],from); + if (i.name == "v_mov_b32") result[lane] = a; + else { + auto b = lane_value(i.src[1],lane); + auto &term = terms[{a,b}]; + if (term.empty()) + term = i.name == "v_xor_b32" ? alu.ir.binary("xor",a,b) : a == b ? a : + alu.select(alu.cmp(i.name == "v_min_u32" ? "ult" : "ugt",a,b),a,b); + result[lane] = term; + } + } + vectors[i.dst] = std::move(result); + return true; + } +}; + +#include "gfx1013_graphics_wqm.inl" + +NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = 0, unsigned first_sampler = 0, + const GraphicsConstantLayout *linked_constants = nullptr, + const D3D12_ROOT_SIGNATURE_DESC1 &layout = {}, unsigned first_uav = 0) { + Program program; + Emit emitter{{}, program, layout}; + emitter.srv = first_srv; + emitter.uav = first_uav; + emitter.first_sampler = first_sampler; + DirectCompute alu{emitter}; + const bool pixel = stage.stage == GpuStage::ps; + alu.pixel_stage = pixel; + alu.perspective_center_pair = pixel && (stage.pixel_input_address & 3) == 2 && (stage.pixel_input_enable & 2) != 0; + if (pixel && !(stage.pixel_input_address >> 16)) + for (unsigned b = 0; b < 16; ++b) + if (stage.pixel_input_address & (1u << b)) + alu.pixel_entry_vgprs += b == 3 ? 3 : b < 7 ? 2 : 1; + GraphicsStage graphics{stage, alu, pixel}; + alu.untouched_pixel_register = [&](unsigned r) { return !graphics.overwritten_inputs.count(r); }; + alu.ir.track_inputs = true; + alu.graphics_input = [&](unsigned r) { return graphics.input(r); }; + State initial{}; + for (auto &s : initial) + s.type = Symbol::Type::unbound; + std::set assigned; + for (const auto &input : stage.inputs) { + unsigned at = input.user_data; + if (input.type == 1) { + bind_root_address(initial, input, 106); + assigned.insert(at); + assigned.insert(at + 1); + continue; + } + if (input.type != 0 && input.type != 3) + continue; + if (at >= 106 || input.root_parameter >= 16) + refuse(0, "graphics root input outside ABI"); + if (input.type == 3) { + Symbol table{Symbol::Type::table, input.root_parameter}; + if (!assigned.insert(at).second && !(initial[at] == table)) + refuse(0, "ambiguous graphics table"); + initial[at] = table; + } else { + if (!input.sgpr_count || input.sgpr_count > 32 || input.sgpr_count > 106 - at) + refuse(0, "invalid graphics constant count"); + emitter.result.constants.push_back({input.root_parameter, at, input.sgpr_count}); + for (unsigned j = 0; j < input.sgpr_count; ++j) { + if (!assigned.insert(at + j).second) + refuse(0, "overlapping graphics constants"); + initial[at + j] = {}; + } + } + } + alu.after_graphics_write = [&](unsigned r) { + // The provenance of an entry EXEC pair is valid only while both + // halves keep their reaching definition on every predecessor. + if (r <= 105) { + auto tag = 512u + (stage.wave32 ? r : (r & ~1u)); + if (alu.graphics_registers.erase(tag)) graphics.overwritten_inputs.insert(tag); + } + graphics.partial.erase(r); + graphics.overwritten_inputs.insert(r); + }; + // The PS primitive mask follows user data (the legacy graphics entry ABI). + // Keep it symbolic: desktop interpolation supplies the primitive, and a + // numeric use of this SGPR or of M0 must still be refused. + if (pixel && layout.NumParameters) { + unsigned end = 8; + for (unsigned p = 0; p < layout.NumParameters && end < 106; ++p) { + const auto ¶m = layout.pParameters[p]; + end += param.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE ? 1 : + param.ParameterType == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS ? param.Constants.Num32BitValues : 2; + } + end += (layout.Flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) != 0; + end += (layout.Flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) != 0; + if (end < 106 && initial[end].type == Symbol::Type::unbound && + std::none_of(stage.inputs.begin(), stage.inputs.end(), [end](auto &p) {return p.user_data >= end || p.sgpr_count > end - p.user_data;})) + initial[end].type = Symbol::Type::primitive_mask; + } + alu.initialize_constants(linked_constants); + const auto code = stage.full_precision_code(); + program = parse(code, 0, initial, true, true, !stage.wave32, stage.fixed_vertex_abi); + // A pixel discards when its invocation bit is removed from EXEC and the + // only remaining work is local ALU plus its color export. The wave-empty + // shortcut then reaches an empty EXP_NULL/end block. See Victory's pixel + // export/discard lowering and gfx2hlsl.py's masked color export. + unsigned discard_pc = UINT_MAX, combine_pc = UINT_MAX, mask_reg = UINT_MAX; + if (pixel && !stage.wave32 && program.code.size() >= 6) { + auto &ops = program.code; + const size_t null = ops.size() - 2; + const auto &output = ops[null]; + unsigned branches = 0; + for (const auto &i : ops) branches += i.branch(); + if (branches == 1 && output.enc == Encoding::Export && (output.a & 0x1fff) == 0x1890 && + ops.back().name == "s_endpgm" && ops[null-1].name == "s_endpgm") { + for (size_t n = 2; n + 1 < null; ++n) { + auto &skip = ops[n]; + const auto &remove = ops[n-1], &combine = ops[n-2]; + if (!skip.branch() || skip.op != 8 || skip.target() != output.pc || + remove.name != "s_andn2_b64" || remove.dst != 126 || remove.src[0] != 126 || + combine.name != "s_or_b64" || combine.dst > 104 || (combine.dst & 1) || + remove.src[1] != combine.dst || + !((combine.src[0] == combine.dst && combine.src[1] == 106) || + (combine.src[1] == combine.dst && combine.src[0] == 106))) continue; + const bool local = std::all_of(ops.begin()+n+1, ops.begin()+null-1, [](const auto &op) { + return GraphicsMaskRegions::local_alu(op) || op.name == "s_waitcnt" || + (op.enc == Encoding::Export && ((op.a >> 4) & 63) < 8); + }); + if (!local) break; + mask_reg = combine.dst; + combine_pc = combine.pc; + discard_pc = remove.pc; + GraphicsMaskRegions::skip_proven(skip); + program.at.erase(output.pc); + program.at.erase(ops.back().pc); + ops.resize(null); + break; + } + } + } + PixelWqm wqm; + if (pixel) { + wqm.raster_guard(program,stage.wave32); + wqm.raster_vote(program,stage.wave32); + wqm.numeric_guards(program,stage.wave32); + } + GraphicsMaskRegions regions(program, stage.wave32, !pixel); + const auto first_branch = std::find_if(program.code.begin(), program.code.end(), + [](const auto &i) { return i.branch(); }); + const bool straight = first_branch == program.code.end(); + const bool entry_backedge = std::any_of(program.code.begin(), program.code.end(), + [](const auto &i) { return i.branch() && i.target() <= i.pc; }); + const unsigned prologue_end = straight ? UINT_MAX : entry_backedge ? 0 : first_branch->pc; + // Once EXEC returns to coverage for the last time, helper results are + // unobservable if the remaining code only reads local data at explicit + // LOD, packs colors, and exports them. A forward uniform branch can + // cross this suffix without converting coverage into a wave-wide vote. + auto tail_instruction = [](const Inst &i) { + if (i.enc == Encoding::Sopp) + return !i.branch() || i.op == 2 || i.op == 4 || i.op == 5; + return i.enc == Encoding::Interp || i.enc == Encoding::Export || + (i.enc == Encoding::Smem && i.dst + memory_count(i) <= 106) || + (i.enc == Encoding::Image && i.op == 0x27) || i.name == "v_cvt_pkrtz_f16_f32"; + }; + auto last_observer = std::find_if_not(program.code.rbegin(), program.code.rend(), tail_instruction); + // In a terminal straight-line suffix, helper values cannot reach a + // neighboring lane or an externally visible store. Only covered lanes + // commit the color export. Implicit LOD and all mask reductions end it. + auto color_tail = [](const Inst &i) { + if (GraphicsMaskRegions::local_alu(i)) return true; + if (i.enc == Encoding::Export) return true; + if (i.enc == Encoding::Smem) return i.dst + memory_count(i) <= 106; + if (i.enc == Encoding::Image) return i.op == 0 || i.op == 0x27; + if (i.enc == Encoding::Sopp) + return i.name == "s_endpgm" || i.name == "s_waitcnt" || i.name == "s_clause" || i.name == "s_nop"; + if (i.enc == Encoding::Vopc) return i.dst == 106 && i.name.substr(0,6) == "v_cmp_"; + if (i.name == "s_cselect_b64" && i.dst == 106) + return (i.src[0] == 128 || i.src[0] == 193) && (i.src[1] == 128 || i.src[1] == 193); + return (i.enc == Encoding::Sopc || (i.enc == Encoding::Sop2 && i.dst < 106)) && + std::none_of(i.src.begin(),i.src.end(),[](unsigned s) { return s >= 106 && s <= 127; }); + }; + auto terminal_mask = std::find_if_not(program.code.rbegin(),program.code.rend(),color_tail); + auto lane_local = [](const Inst &i) { + if (i.enc == Encoding::Sopp) return !i.branch(); + if (i.enc == Encoding::Interp || i.enc == Encoding::Export) return true; + if (i.enc == Encoding::Sop1) return i.name == "s_mov_b64" || i.name == "s_mov_b32"; + if (i.enc == Encoding::Vop1 || i.enc == Encoding::Vop2 || i.enc == Encoding::Vop3 || i.enc == Encoding::Vopc) + return !i.dpp_control && i.name.find("lane") == Name::npos && i.name.find("mbcnt") == Name::npos; + return false; + }; + const auto last_lane_observer = std::find_if_not(program.code.rbegin(), program.code.rend(), lane_local); + bool whole_quad = false; + bool exact_after_wqm = false; + bool exact_sample_region = false; + std::map saved_exec; + std::string covered; + string discard_lane; + std::string parent_predicate, arm_condition, inner_parent; + bool scalar_entry = true; + std::set uniform_vector_values; + std::set uniform_vcc_values; + auto scalar_operand = [](unsigned s) { return s <= 105 || (s >= 128 && s <= 248) || s == 255; }; + auto covered_lane = [&] { + auto helper = alu.ir.invoke("i1","isHelperLane.i1",221,{},"nounwind readonly"); + alu.ir.dependencies[helper].set(128); + return alu.ir.value("xor i1 " + helper + ", true"); + }; + GraphicsFullWave full_wave{alu, stage.wave32 ? 32u : 64u}; + auto instruction = [&](const Inst &i, const State &state) { + const auto pc = alu.graphics_pc = graphics.pc = i.pc; + if (pixel && full_wave.emit(i,program)) return; + if (wqm.packed.count(pc) && (whole_quad || exact_after_wqm || !alu.graphics_predicate.empty())) + refuse(pc, "numeric EXEC region requires exact pixel entry coverage"); + if (pixel && wqm.emit_packed(alu,i,stage.wave32)) return; + if (wqm.filters.count(pc)) { + const auto tag=alu.graphics_registers.find(512+i.dst); + if (!whole_quad || exact_after_wqm || !alu.graphics_predicate.empty() || + (wqm.survivor.empty() && (tag==alu.graphics_registers.end() || tag->second!="0"))) + refuse(pc,"WQM coverage filter requires saved exact entry EXEC"); + const auto keep=alu.cmp("eq",alu.read(106),"0"); + const auto previous=wqm.survivor.empty() ? covered_lane() : wqm.survivor; + wqm.survivor=alu.ir.value("and i1 "+previous+", "+keep); + alu.write(i.dst,{}); if (!stage.wave32) alu.write(i.dst+1,{}); + alu.write(128,{}); + return; + } + if (auto vote=wqm.vote_masks.find(pc); vote!=wqm.vote_masks.end()) { + if (!whole_quad || exact_after_wqm || !alu.graphics_predicate.empty() || wqm.survivor.empty()) + refuse(pc,"cross-quad EXECZ mask requires whole-quad EXEC after a coverage filter"); + // Every lane of a covered quad, helpers included, is in the + // whole-quad EXEC; the filtered coverage holds only survivors. + const auto keep=alu.cmp("eq",alu.read(106),"0"); + using Source=PixelWqm::MaskSource; + if (vote->second==Source::narrowed && wqm.vote_lane.empty()) + refuse(pc,"cross-quad EXECZ mask narrowed before it is written"); + wqm.vote_lane=vote->second==Source::whole_quad ? keep : + alu.ir.value("and i1 "+(vote->second==Source::survivors ? wqm.survivor : wqm.vote_lane)+", "+keep); + alu.write(i.dst,{}); if (!stage.wave32) alu.write(i.dst+1,{}); + alu.write(128,{}); + return; + } + if (pc==wqm.vote_wqm) { + if (wqm.vote_lane.empty()) refuse(pc,"cross-quad EXECZ vote has no modelled EXEC"); + // EXEC at the branch is the WQM expansion of the mask: OR it over + // the quad (quad reads see helper lanes), then vote over the wave. + alu.ir.uses_wave=true; + auto bit=alu.ir.value("zext i1 "+wqm.vote_lane+" to i32"); + auto quad=bit; + for (unsigned op=0;op<3;++op) + quad=alu.ir.binary("or",quad, + alu.ir.invoke("i32","quadOp.i32",123,{{"i32",bit},{"i8",to_string(op)}},"nounwind")); + auto vote=alu.ir.invoke("i1","waveAnyTrue",113,{{"i1",alu.cmp("ne",quad,"0")}},"nounwind"); + alu.write(128,alu.ir.value("zext i1 "+vote+" to i32")); + return; + } + if (wqm.quad_guards.count(pc)) { + // Helpers have no input coverage bit. Broadcast the four survivor + // bits while the quad is intact. Only a terminal colour region + // proven independent across quads can use this projection. + auto bit=alu.ir.value("zext i1 "+wqm.survivor+" to i32"); + auto any=bit; + alu.ir.uses_wave=true; + for (unsigned axis=0;axis<2;++axis) { + auto peer=alu.ir.invoke("i32","quadOp.i32",123,{{"i32",any},{"i8",to_string(axis)}},"nounwind"); + any=alu.ir.binary("or",any,peer); + } + auto live=alu.cmp("ne",any,"0"); + const auto label=to_string(pc); + alu.ir.body<<" br i1 "<= last_lane_observer->pc); + if (auto it = regions.expired.find(pc); it != regions.expired.end()) + for (auto reg : it->second) alu.write(reg, {}); + if (regions.vertex_anchors.count(pc) || regions.captures.count(pc)) { + // A single invocation observes one bit of this saved wave mask. + // Never substitute that bit for a numeric 64-bit SGPR read. + alu.write(i.dst,{}); + alu.write(i.dst+1,{}); + if (regions.captures.count(pc)) alu.write(128,{}); + return; + } + auto vertex_compare_bit = [&] { + return alu.ir.value("zext i1 " + alu.comparison(i) + " to i32"); + }; + if (regions.vertex_mask_compares.count(pc)) { + alu.write(1024+pc,vertex_compare_bit()); + alu.write(i.dst,{}); alu.write(i.dst+1,{}); + return; + } + if (auto it = regions.branch_saves.find(pc); it != regions.branch_saves.end()) { + if (!alu.graphics_predicate.empty()) + refuse(pc,"vertex EXEC branch requires an active enclosing invocation"); + string bit; + if (i.enc == Encoding::Vopc) { + bit = vertex_compare_bit(); + } else if (auto input = regions.mask_inputs.find(pc); input != regions.mask_inputs.end()) { + bit = alu.read(input->second); + } else { + bit = alu.read(106); + } + if (i.dst != 126) { + alu.write(i.dst,{}); + if (!stage.wave32) alu.write(i.dst+1,{}); + } + alu.write(128,{}); + alu.write(it->second, bit); + return; + } + if (auto input = regions.mask_inputs.find(pc); input != regions.mask_inputs.end()) { + if (regions.uniform_mask_tests.count(pc)) { + auto bit = alu.read(input->second); + if (alu.ir.dependencies[bit].any()) + refuse(pc,"non-uniform compare needs a full guest-wave SCC reduction"); + // We are inside a proven nonempty EXEC arm. Every active + // lane agrees on the comparison, so any(mask) equals it. + alu.write(i.dst,{}); alu.write(i.dst+1,{}); alu.write(128,bit); + return; + } + if (i.dst == 126 || i.name != "s_and_b64") refuse(pc,"mask-fed EXEC has no matching restore"); + auto bit = alu.ir.binary("and",alu.read(106),alu.read(input->second)); + alu.write(1024+pc,bit); + alu.write(i.dst,{}); alu.write(i.dst+1,{}); alu.write(128,{}); + return; + } + if (regions.branch_merges.count(pc) && !regions.scalar_tail_merges.count(pc)) return; + const bool cmpx = regions.cmpx_starts.count(pc) != 0; + if (cmpx || regions.compares.count(pc)) { + if (i.name.find("class") != Name::npos || + ((i.abs || i.neg) && i.name.find("_f") == Name::npos)) + refuse(pc,"unsupported partitioned compare modifiers"); + auto lhs = alu.operand32(i,i.src[0]), rhs = alu.operand32(i,i.src[1]); + arm_condition = alu.comparison(i,lhs,rhs); + if (!cmpx) { + alu.write(i.dst, {}); alu.write(i.dst+1, {}); + return; + } + } + if (regions.unions.count(pc)) { + auto vcc = alu.cmp("ne",alu.read(106),"0"); + arm_condition = alu.ir.value("or i1 " + vcc + ", " + arm_condition); + alu.write(128, {}); + return; + } + if (cmpx || regions.intersections.count(pc)) { + const auto tag = alu.graphics_registers.find(512 + regions.enclosing_mask.at(pc)); + const bool known_parent = regions.vertex_partitions.count(pc) || + (whole_quad && !exact_after_wqm && tag != alu.graphics_registers.end() && tag->second == "1"); + if (!known_parent || !alu.graphics_predicate.empty()) + refuse(pc,"unproven enclosing whole-quad EXEC"); + parent_predicate.clear(); + alu.graphics_predicate = arm_condition; + if (!cmpx) alu.write(128, {}); + return; + } + if (regions.inner_saves.count(pc)) { + const auto tag = alu.graphics_registers.find(512 + i.src[0]); + if (tag == alu.graphics_registers.end() || tag->second != "0") + refuse(pc,"inner EXEC requires saved entry coverage"); + inner_parent = alu.graphics_predicate; + auto exact = covered_lane(); + alu.graphics_predicate = alu.ir.value("and i1 " + inner_parent + ", " + exact); + alu.write(i.dst, {}); alu.write(i.dst+1, {}); alu.write(128, {}); + return; + } + if (regions.inner_restores.count(pc)) { + alu.graphics_predicate = inner_parent; + alu.write(i.dst, {}); alu.write(i.dst+1, {}); alu.write(128, {}); + return; + } + if (regions.saves.count(pc)) { + parent_predicate = alu.graphics_predicate; + arm_condition = alu.cmp("ne", alu.read(106), "0"); + alu.graphics_predicate = parent_predicate.empty() ? arm_condition : + alu.ir.value("and i1 " + parent_predicate + ", " + arm_condition); + saved_exec.erase(i.dst); + alu.write(i.dst, {}); + if (!stage.wave32) alu.write(i.dst + 1, {}); + alu.write(128, {}); + return; + } + if (regions.complements.count(pc)) { + auto other = alu.ir.value("xor i1 " + arm_condition + ", true"); + alu.graphics_predicate = parent_predicate.empty() ? other : + alu.ir.value("and i1 " + parent_predicate + ", " + other); + alu.write(128, {}); + return; + } + if (regions.restores.count(pc)) { + alu.graphics_predicate = parent_predicate; + return; + } + const bool short_mask = stage.wave32 && i.name == "s_mov_b32"; + const bool move_exec = pixel && (short_mask || i.name == "s_mov_b64") && (i.dst == 126 || i.src[0] == 126); + if (move_exec && i.dst == 126 && pc >= prologue_end && !entry_backedge && whole_quad && + alu.graphics_predicate.empty() && terminal_mask != program.code.rend() && terminal_mask->pc == pc) { + const auto tag = alu.graphics_registers.find(512 + i.src[0]); + if (tag == alu.graphics_registers.end() || tag->second != "0") + refuse(pc,"terminal pixel export requires saved entry coverage"); + return; + } + if (pixel && pc >= prologue_end && (regions.sample_begins.count(pc) || regions.sample_ends.count(pc))) { + const bool begin = regions.sample_begins.count(pc) != 0; + const auto saved = alu.graphics_registers.find(512 + i.src[0]); + if (!whole_quad || saved == alu.graphics_registers.end() || saved->second != (begin ? "0" : "1") || + (begin ? !alu.graphics_predicate.empty() : !exact_sample_region)) + refuse(pc,"unproven EXEC for a conditional sample"); + exact_after_wqm = alu.exact_pixel_entry = exact_sample_region = begin; + if (begin) { + // Run read-only sampling with the quad intact for derivatives, + // then merge only the writes made under the guest coverage. + alu.graphics_predicate = covered_lane(); + } else alu.graphics_predicate.clear(); + return; + } + if (!straight && pc >= prologue_end && exact_after_wqm && !exact_sample_region) + refuse(pc, "exact pixel mask crosses a control-flow edge"); + if (move_exec && (short_mask ? i.dst <= 105 : i.dst <= 104 && !(i.dst & 1)) && + i.src[0] == 126 && pc < prologue_end) { + saved_exec[i.dst] = whole_quad && !exact_after_wqm; + // Numeric use of either half needs actual wave-mask lowering. + alu.write(i.dst,{}); + if (!short_mask) alu.write(i.dst+1,{}); + alu.write(512+i.dst, saved_exec.at(i.dst) ? "1" : "0"); + return; + } + if (move_exec && i.dst == 126 && pc < prologue_end && saved_exec.count(i.src[0]) && + alu.graphics_registers.count(512 + i.src[0])) { + exact_after_wqm = whole_quad && !saved_exec.at(i.src[0]); + if (whole_quad && exact_after_wqm && !entry_backedge && + last_observer != program.code.rend() && pc == last_observer->pc) { + while (!alu.guarded_ij.empty()) { + auto it = alu.guarded_ij.begin(); + if (!covered.empty() && it->second.first == covered) { + alu.graphics_registers[it->first] = it->second.second; + alu.guarded_ij.erase(it); + } else { + alu.materialize_ij(it->first); + } + } + whole_quad = false; + exact_after_wqm = false; + alu.exact_pixel_entry = false; + alu.graphics_predicate.clear(); + return; + } + if (exact_after_wqm) { + if (covered.empty()) { + covered = covered_lane(); + } + alu.graphics_predicate = covered; + alu.exact_pixel_entry = true; + } else { + alu.graphics_predicate.clear(); + alu.exact_pixel_entry = false; + } + return; + } + if (i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2 || i.enc == Encoding::Sopk || + i.enc == Encoding::Smem || i.enc == Encoding::Vop3 || i.enc == Encoding::Vop1) { + // Invalidate both halves of a saved mask when scalar code reuses them. + const unsigned width = i.enc == Encoding::Smem ? memory_count(i) : + i.name.find("_b64") != Name::npos ? 2 : 1; + if (i.dst<128) + for (auto it=saved_exec.begin(); it!=saved_exec.end();) + if (i.dstfirst+(stage.wave32 ? 1u : 2u) && it->first= 256 && !i.dpp_control && !i.subword) && + !(i.enc==Encoding::Image && i.op>=0x20 && i.op<=0x3f)) + refuse(pc,"unsupported exact-mask operation after whole-quad entry"); + if ((i.name == "s_wqm_b32" || i.name == "s_wqm_b64") && i.dst == 126 && i.src[0] == 126) { + if (!stage.wave32 && i.name == "s_wqm_b32") + refuse(pc, "whole-quad operation affects only half of the guest EXEC mask"); + if (!pixel || pc >= prologue_end || !scalar_entry || whole_quad) + refuse(pc, "whole-quad mode requires an unmodified pixel entry mask"); + whole_quad = true; + alu.graphics_registers[128] = {}; // SCC describes the physical wave mask. + return; + } + if (i.branch() || !((i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2 || i.enc == Encoding::Smem || + i.enc == Encoding::Sopk) && i.dst < 106) && + i.name != "v_nop" && i.name != "s_nop" && i.name != "s_clause" && + i.name != "s_setprio" && i.name != "s_inst_prefetch" && i.name != "s_waitcnt") + scalar_entry = false; + if (i.dpp_control) { + if (i.mirror_mask()) + refuse(pc, i.mirror_mask() == 7 ? "DPP half-row mirror requires a proven eight-lane pixel layout" + : "DPP row mirror requires a proven sixteen-lane pixel layout"); + // In whole-quad mode all four possible sources participate. At + // exact coverage the desktop helper's VGPR contents are unproven. + if (i.dpp_fetch_inactive && (!whole_quad || exact_after_wqm)) + refuse(pc, "DPP fetch-inactive source requires a proven whole quad"); + if (!whole_quad || exact_after_wqm) + refuse(pc, "pixel quad permutation without whole-quad entry"); + const auto op = alu_rules.find(i.name); + if (i.name != "v_mov_b32" && (op == alu_rules.end() || op->second.arity > 2)) + refuse(pc, "unsupported DPP arithmetic"); + if (i.enc == Encoding::Vop1 && (i.neg & 2 || i.abs & 2)) + refuse(pc, "unexpected second DPP source modifier"); + auto first = graphics.quad_source(i); + alu.arithmetic(i, state, &first); + return; + } + if (i.enc == Encoding::FixedSetup) { + if (pixel || !straight) refuse(pc,"inline vertex fetch requires a straight-line VS"); + for (unsigned r = i.dst; r < i.dst + i.op; ++r) alu.write(r, {}); + if (i.next - pc == 8 && i.op == 1) alu.write(128, {}); // BFE sets SCC. + return; + } + if (i.enc == Encoding::FixedFetch) { + if (pixel || !straight) refuse(pc,"inline vertex fetch requires a straight-line VS"); + const auto &inputs = alu.ir.inputs; + auto prior = std::find_if(inputs.begin(), inputs.end(), [&](const auto &r) { + return r.name == "X2W_RAW_VERTEX" && r.semantic_index == i.literal; + }); + unsigned row = prior != inputs.end() ? prior->row : static_cast(inputs.size()); + const auto id = graphics.row(true, "X2W_RAW_VERTEX", i.literal, 0, i.op == 4 ? 9 : 5, + row, (1u << i.op) - 1, 0); + for (unsigned c = 0; c < i.op; ++c) alu.write(i.dst + c, graphics.load(id, c)); + emitter.result.vertex_fetch=true; + return; + } + if (i.enc == Encoding::Fetch) { + if (pixel) + refuse(pc, "vertex fetch call in a pixel shader"); + if (std::any_of(program.code.begin(),program.code.begin()+program.at.at(pc), + [](const Inst &prefix) { return prefix.name != "v_nop"; })) + refuse(pc, "vertex fetch call outside the entry"); + // The stream fetch ABI supplies each declared input VGPR through + // the input assembler. Its return address is opaque to guest ALU. + if (stage.attributes.empty()) + refuse(pc, "vertex fetch call without fetch records"); + std::bitset<256> destinations; + for (const auto &a : stage.attributes) { + if (a.usage != 6 || !a.location || a.last_component > 3 || (a.mask >> a.last_component) != 1 || + a.location + a.last_component >= 256) + refuse(pc, "invalid vertex fetch record"); + for (unsigned j = 0; j <= a.last_component; ++j) { + if (destinations.test(a.location + j)) + refuse(pc, "overlapping vertex fetch destinations"); + destinations.set(a.location + j); + } + } + emitter.result.vertex_fetch = true; + for (unsigned r : {4u, 5u}) { + alu.graphics_registers[r] = {}; + graphics.overwritten_inputs.insert(r); + } + return; + } + if (i.enc == Encoding::Export) { + graphics.emit_export(i.a, i.b); + return; + } + if (i.enc == Encoding::Interp) { + graphics.interpolate(i.a); + return; + } + if (i.name == "s_nop" || i.name == "v_nop" || i.name == "s_setprio" || i.name == "s_clause" || i.name == "s_inst_prefetch" || + i.name == "s_waitcnt") + return; + if (i.enc == Encoding::Vopc && i.dst <= 106 && i.name.substr(0, 6) == "v_cmp_" && !i.scale && !i.clamp) { + // Keep the invocation bit for CNDMASK and predicated regions. + // A whole-wave VCC branch also requires a uniform condition. + auto pred = alu.comparison(i); + if (!alu.graphics_predicate.empty()) + pred = alu.ir.value("and i1 " + alu.graphics_predicate + ", " + pred); + auto bit = alu.ir.value("zext i1 " + pred + " to i32"); + if (i.dst == 106) alu.write(106,bit); + else { + alu.write(i.dst,{}); + if (!stage.wave32) alu.write(i.dst+1,{}); + alu.write(1024+pc,bit); + } + if (i.dst == 106 && alu.graphics_predicate.empty() && scalar_operand(i.src[0]) && scalar_operand(i.src[1]) && + alu.ir.dependencies[bit].none()) uniform_vcc_values.insert(bit); + return; + } + if (i.name == "v_cndmask_b32" && !i.abs && !i.neg && !i.scale && !i.clamp) { + if (i.wide && (i.a & 0x7800)) refuse(pc,"unsupported graphics CNDMASK operand selection"); + auto a = alu.operand32(i, i.src[0]), b = alu.operand32(i, i.src[1]); + if (i.subword) { + a = alu.subword(a, i.src_select[0], i.src_sext[0]); + b = alu.subword(b, i.src_select[1], i.src_sext[1]); + } + auto mask = alu.graphics_lane_mask(i,state,i.src[2],"unproven graphics CNDMASK source"); + alu.vector_write(i.dst, alu.place_subword(i, alu.select(alu.cmp("ne",mask,"0"), b, a))); + return; + } + if (pixel && i.name == "s_mov_b32" && i.dst == 124 && i.src[0] < 106 && + state[i.src[0]].type == Symbol::Type::primitive_mask) + return; + if (i.name == "v_readfirstlane_b32" && i.dst < 106 && i.src[0] >= 256 && + !i.subword && !i.scale && !i.clamp && !i.abs && !i.neg && alu.graphics_predicate.empty()) { + auto value = alu.read(i.src[0]); + if (!uniform_vector_values.count(value)) + refuse(pc,"graphics readfirstlane requires a wave-uniform reaching value"); + alu.write(i.dst,value); + return; + } + if (whole_quad && !exact_after_wqm && alu.graphics_predicate.empty() && + i.name == "s_and_b64" && i.dst <= 104 && !(i.dst & 1) && + ((i.src[0] == 106 && i.src[1] == 126) || (i.src[1] == 106 && i.src[0] == 126))) { + auto bit = alu.read(106); + if (!uniform_vcc_values.count(bit)) + refuse(pc,"varying VCC requires a full-wave nonzero reduction"); + // An executing invocation belongs to a nonempty guest wave. For + // a uniform comparison VCC & EXEC is nonzero iff its bit is set. + // The numeric SGPR pair still depends on the actual wave mask. + alu.write(i.dst, {}); alu.write(i.dst + 1, {}); alu.write(128,bit); + return; + } + if (i.name == "s_cselect_b64" && i.dst == 106 && + (i.src[0] == 128 || i.src[0] == 193) && (i.src[1] == 128 || i.src[1] == 193)) { + auto scc = alu.read(128); + alu.write(106, alu.select(alu.cmp("ne",scc,"0"),i.src[0] == 193 ? "1" : "0", + i.src[1] == 193 ? "1" : "0")); + alu.write(107, {}); + return; + } + if (i.name == "s_cselect_b64" && i.dst <= 104 && !(i.dst & 1) && + (i.src[0] == 128 || i.src[0] == 193) && (i.src[1] == 128 || i.src[1] == 193)) { + if (!regions.scalar_mask_selects.count(pc) || alu.ir.loop_dependencies) + refuse(pc,"full scalar mask requires a reaching scalar SCC comparison"); + auto scc = alu.read(128); + if (alu.ir.dependencies[scc].any()) + refuse(pc,"full scalar mask depends on a varying SCC"); + auto word = alu.select(alu.cmp("ne",scc,"0"),i.src[0] == 193 ? "4294967295" : "0", + i.src[1] == 193 ? "4294967295" : "0"); + alu.write(i.dst,word); alu.write(i.dst+1,word); + alu.write(1024+pc,word); + return; + } + if (((i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2 || i.enc == Encoding::Sopk) && i.dst >= 106) || + i.branch() || i.enc == Encoding::Sopp || i.enc == Encoding::Lds || i.enc == Encoding::Vopc || + i.name.find("exec") != Name::npos || i.name.find("lane") != Name::npos || + i.name.find("mbcnt") != Name::npos || i.name == "v_cndmask_b32") + refuse(i.pc, "graphics wave or control-flow instruction"); + if (i.enc == Encoding::Smem || i.enc == Encoding::Mubuf) { + if (i.name.find("atomic") != Name::npos) + refuse(i.pc, "graphics buffer atomic"); + alu.memory(i, state); + if (i.name == "buffer_load_format" && (i.a & 0x3ffffu) == 0 && alu.graphics_predicate.empty()) { + // A read-only uniform table entry and the literal element zero + // supply the same bits to every active invocation. + for (unsigned n = 0; n <= (i.op & 3); ++n) { + auto value = alu.read(256 + i.dst + n); + if (alu.ir.dependencies[value].none()) uniform_vector_values.insert(value); + } + } + } else if (i.enc == Encoding::Image) { + alu.image_io(i, state); + } else { + // SGPR values and inline constants are common to the wave. + // Propagate that fact through pure VS arithmetic before a write + // can replace an overlapping source. An FMAC also reads its dst. + bool uniform_vertex = false; + auto rule = alu_rules.find(i.name); + if (!pixel && !alu.ir.loop_dependencies && alu.graphics_predicate.empty() && + !i.subword && GraphicsMaskRegions::local_alu(i) && rule != alu_rules.end()) { + auto uniform = [&](unsigned r) { + if (scalar_operand(r)) return true; + auto source = alu.graphics_registers.find(r); + return r >= 256 && source != alu.graphics_registers.end() && + uniform_vector_values.count(source->second) != 0; + }; + const bool mac = i.name == "v_fmac_f32"; + const unsigned count = mac || i.name == "v_fmamk_f32" || i.name == "v_fmaak_f32" ? 2 : rule->second.arity; + uniform_vertex = std::all_of(i.src.begin(),i.src.begin()+count,uniform) && (!mac || uniform(i.dst)); + } + alu.arithmetic(i, state); + if (uniform_vertex || (pixel && i.name == "v_med3_f32" && alu.graphics_predicate.empty() && + std::all_of(i.src.begin(), i.src.end(), scalar_operand))) { + auto value = alu.read(i.dst); + if (alu.ir.dependencies[value].none()) uniform_vector_values.insert(value); + } + } + }; + auto blocks = graphics_blocks(program, regions); + std::map> edges; + std::vector ready; + if (!blocks.at(0).predecessors) + ready.push_back(0); + std::vector order; + while (!ready.empty()) { + unsigned label = ready.back(); + ready.pop_back(); + order.push_back(label); + for (auto next : blocks.at(label).successors) + if (!--blocks.at(next).predecessors) + ready.push_back(next); + } + if (order.size() != blocks.size()) { + if (!regions.lane_branches.empty()) refuse(0, "masked vertex control flow requires an acyclic graph"); + emit_graphics_loops(graphics, program, blocks, instruction); + } else { + alu.ir.body << " br label %g0\n"; + std::optional> final_exports; + for (unsigned label : order) { + auto &block = blocks.at(label); + alu.ir.body << "g" << label << ":\n"; + graphics.pc = label; + if (label) { + join_graphics(graphics, edges.at(label), regions); + edges.erase(label); + } + for (size_t k = block.begin; k < block.end; ++k) { + const auto &i = program.code[k]; + if (!i.branch() && i.name != "s_endpgm") + instruction(i, program.before[k]); + } + const auto &last = program.code[block.end - 1]; + alu.graphics_pc = last.pc; + if (!block.successors.empty()) { + // Each predecessor must carry the value for covered and helper + // lanes before its definitions become incoming phi operands. + while (!alu.guarded_ij.empty()) alu.materialize_ij(alu.guarded_ij.begin()->first); + } + if (block.successors.empty()) { + if (graphics.exported.empty() || (!pixel && !graphics.exported.count(12)) || + (final_exports && *final_exports != graphics.exported)) + refuse(last.pc, "incomplete or inconsistent terminal graphics exports"); + final_exports = graphics.exported; + alu.ir.body << " br label %graphicsEnd\n"; + } else if (block.successors.size() == 2) { + const auto branch = regions.lane_branches.find(last.pc); + auto condition = branch != regions.lane_branches.end() ? + alu.cmp(branch->second.second ? "ne" : "eq", alu.read(branch->second.first), "0") : + alu.cmp((last.op & 1) ? "ne" : "eq", alu.read(last.op >= 6 ? 106 : 128), "0"); + // The cross-quad EXECZ vote is uniform over the desktop wave; + // its input dependencies still reach the values merged after it. + // Wave intrinsics are undefined on helper lanes, so a helper may + // take the other edge: safe only while nothing after the branch + // reads another lane (raster_vote keeps the tail lane-local). + if (branch == regions.lane_branches.end() && alu.ir.dependencies[condition].any() && + last.pc != wqm.vote_skip) + refuse(last.pc, "graphics scalar condition depends on a varying input"); + alu.ir.body << " br i1 " << condition << ", label %g" << last.target() << ", label %g" << last.next + << "\n"; + } else + alu.ir.body << " br label %g" << block.successors.front() << "\n"; + for (size_t j = 0; j < block.successors.size(); ++j) { + auto &incoming = edges[block.successors[j]]; + if (j + 1 == block.successors.size()) + incoming.push_back({label, std::move(alu.graphics_registers), + std::move(graphics.overwritten_inputs), std::move(graphics.partial), + std::move(graphics.exported)}); + else + incoming.push_back({label, alu.graphics_registers, graphics.overwritten_inputs, graphics.partial, + graphics.exported}); + if (auto capture = regions.captures.find(block.successors[j]); capture != regions.captures.end()) { + auto &edge = incoming.back(); + auto vcc = edge.values.find(106); + const bool skip = last.pc == capture->second.skip; + if (!skip && (vcc == edge.values.end() || vcc->second.empty())) + refuse(last.pc,"missing active VCC contribution to EXEC intersection"); + edge.values[capture->second.value] = skip ? "0" : vcc->second; + edge.written.insert(capture->second.value); + } + } + } + } + emitter.result.instruction_count = static_cast(program.code.size()); + alu.ir.body << "graphicsEnd:\n ret void\n"; + auto copy_signature = [](const auto &rows, auto &out) { + for (const auto &r : rows) + out.push_back( + {r.name, r.semantic_index, r.row, r.first, r.width, r.component, r.used, r.kind, r.interpolation}); + }; + copy_signature(alu.ir.inputs, emitter.result.inputs); + copy_signature(alu.ir.outputs, emitter.result.outputs); + if (!pixel && emitter.uav != first_uav) alu.ir.features |= 1u << 16; // UAVsAtEveryStage + emitter.result.dxil_ir = alu.ir.finish_compute(0, 0, 0, pixel ? "ps" : "vs"); + return std::move(emitter.result); +} diff --git a/src/gfx1013_graphics_wqm.inl b/src/gfx1013_graphics_wqm.inl new file mode 100644 index 000000000..38f1062df --- /dev/null +++ b/src/gfx1013_graphics_wqm.inl @@ -0,0 +1,305 @@ +// A numeric SGPR mask contains every guest lane, independently of the +// desktop wave size. A raster coverage mask instead has one known bit per +// invocation. Keep these two representations distinct. +// See victory-shader 9376fd6, structure.rs (Atom::Quad) and emit/lower.rs +// (wave_wide). The raster path below requires a quad-local live arm. +struct PixelWqm { + std::set packed, packed_reads, packed_restores; + std::set filters, quad_guards; + unsigned exact_restore = UINT_MAX; + string survivor; + // Cross-quad EXECZ (#2907): each write of the branch mask, taken from the + // filtered coverage or the whole-quad EXEC, or narrowing the mask again. + enum class MaskSource { survivors, whole_quad, narrowed }; + std::map vote_masks; + unsigned vote_wqm = UINT_MAX, vote_skip = UINT_MAX; + string vote_lane; + + static bool local(const Inst &i) { + return GraphicsMaskRegions::local_alu(i) || i.name == "s_waitcnt" || i.name == "s_nop" || + (i.dpp_control && !i.mirror_mask() && i.dst >= 256); + } + static bool is_wqm(const Inst &i, bool narrow) { return i.name == (narrow ? "s_wqm_b32" : "s_wqm_b64"); } + // Within a scalar-only diamond the lane bits can be inspected without + // assigning any desktop pixel a guest lane index. The original EXEC must + // be restored before committing vector results. + void numeric_guards(Program &p, bool narrow) { + const auto mov = narrow ? "s_mov_b32" : "s_mov_b64"; + std::multimap incoming; + for (const auto &op : p.code) + if (op.branch()) + incoming.emplace(op.target(), op.pc); + for (size_t n = 0; n + 2 < p.code.size(); ++n) { + const auto &wqm = p.code[n]; + auto &skip = p.code[n + 1]; + if (!is_wqm(wqm, narrow) || wqm.dst != 126 || wqm.src[0] >= 106 || !skip.branch() || + (skip.op != 8 && skip.op != 9) || skip.target() <= skip.pc) + continue; + size_t end = n + 2; + std::vector reads; + for (; end < p.code.size(); ++end) { + const auto &i = p.code[end]; + if (i.name == mov && i.dst == 126) + break; + if (i.name == mov && i.src[0] == 126 && i.dst < 106) { + reads.push_back(i.pc); + continue; + } + if (i.branch() && i.target() > i.pc && (i.op == 2 || i.op == 4 || i.op == 5)) + continue; + if (i.name == "s_nop") + continue; + if ((i.enc != Encoding::Sop1 && i.enc != Encoding::Sop2 && i.enc != Encoding::Sopc && + i.enc != Encoding::Sopk) || + i.dst >= 106 || i.name.find("exec") != Name::npos || + std::any_of(i.src.begin(), i.src.end(), [](unsigned r) { return r == 126 || r == 127; })) + break; + } + if (end == p.code.size()) + continue; + const auto &restore = p.code[end]; + if (restore.name != mov || restore.dst != 126 || restore.src[0] >= 106 || skip.target() > restore.pc) + continue; + bool closed = true; + for (auto it = incoming.upper_bound(wqm.pc); it != incoming.end() && it->first <= restore.pc; ++it) + if (it->second < wqm.pc || it->second >= restore.pc) + closed = false; + for (size_t k = n + 1; k < end; ++k) + if (p.code[k].branch() && p.code[k].target() > restore.pc) + closed = false; + if (!closed) + continue; + packed.insert(wqm.pc); + packed_reads.insert(reads.begin(), reads.end()); + packed_restores.insert(restore.pc); + // SCC from WQM is exactly (lo | hi) != 0. No instruction + // between WQM and the branch can overwrite SCC. + skip.op = skip.op == 8 ? 4 : 5; + skip.name = skip.op == 4 ? "s_cbranch_scc0" : "s_cbranch_scc1"; + } + } + void raster_guard(Program &p, bool narrow) { + auto &code = p.code; + if (code.size() < 8) + return; + const size_t null = code.size() - 2; + if (code[null].enc != Encoding::Export || (code[null].a & 0x1fff) != 0x1890 || + code.back().name != "s_endpgm" || code[null - 1].name != "s_endpgm") + return; + std::vector guards, updates; + unsigned mask = UINT_MAX; + for (size_t k = 0; k < null; ++k) { + if (!code[k].branch()) + continue; + if (k < 2 || code[k].op != 8 || code[k].target() != code[null].pc) + return; + const auto &wqm = code[k - 1]; + if (!is_wqm(wqm, narrow) || wqm.dst != 126 || wqm.src[0] > (narrow ? 105u : 104u) || + (!narrow && (wqm.src[0] & 1)) || (mask != UINT_MAX && mask != wqm.src[0])) + return; + mask = wqm.src[0]; + size_t f = k - 1; + while (f > 0 && local(code[f - 1])) + --f; + if (!f) + return; + const auto &keep = code[f - 1]; + if (keep.name != (narrow ? "s_andn2_b32" : "s_andn2_b64") || keep.dst != mask || keep.src[0] != mask || + keep.src[1] != 106) + return; + if (!guards.empty()) { + // Only intact quads reach another filter. Comparing again + // can remove more covered lanes, never revive a dead quad. + for (size_t j = guards.back() + 1; j < f - 1; ++j) + if (!local(code[j]) && !(code[j].enc == Encoding::Vopc && code[j].dst == 106 && + code[j].name.substr(0, 6) == "v_cmp_")) + return; + } + guards.push_back(k); + updates.push_back(f - 1); + } + if (guards.empty()) + return; + size_t r = guards.back() + 1; + while (r < null - 1 && local(code[r])) + ++r; + if (r >= null - 1 || code[r].name != (narrow ? "s_mov_b32" : "s_mov_b64") || code[r].dst != 126 || + code[r].src[0] != mask) + return; + for (size_t j = r + 1; j < null - 1; ++j) { + const auto &i = code[j]; + if (!(GraphicsMaskRegions::local_alu(i) || i.name == "s_waitcnt" || + (i.enc == Encoding::Export && ((i.a >> 4) & 63) < 8))) + return; + } + // Each surviving quad runs the same finite local instructions as in + // the nonempty guest wave. An empty quad has no observable result + // on either edge: the only exports use the restored survivor bits. + for (size_t j = 0; j < guards.size(); ++j) { + filters.insert(code[updates[j]].pc); + quad_guards.insert(code[guards[j] - 1].pc); + GraphicsMaskRegions::skip_proven(code[guards[j]]); + } + exact_restore = code[r].pc; + p.at.erase(code[null].pc); + p.at.erase(code.back().pc); + code.resize(null); + } + // A scalar instruction that neither reads nor writes EXEC or VCC. + static bool plain_scalar(const Inst &i) { + if (i.enc != Encoding::Sop1 && i.enc != Encoding::Sop2 && i.enc != Encoding::Sopc && + i.enc != Encoding::Sopk) + return false; + return (i.enc == Encoding::Sopc || i.dst < 106) && i.name.find("exec") == Name::npos && + std::none_of(i.src.begin(), i.src.end(), [](unsigned r) { return r >= 106 && r <= 127; }); + } + // Cross-quad EXECZ under WQM (#2907): + // s_mov sE, exec; s_wqm exec, exec + // one or more coverage filters v_cmp_* vcc; s_andn2 sE, sE, vcc + // v_cmp_* vcc; s_andn2 sM, sX, vcc sX = sE (survivors) or exec (whole quads) + // s_wqm exec, sM; s_cbranch_execz J the region writes only scalars + // J: s_mov exec, sE then a terminal colour export + // Lanes are skipped only when EXEC is zero in the whole guest wave, so the + // branch is a vote over the wave. It is lowered over the desktop wave, + // under the #2835 packing contract: a correct program cannot depend on + // which quads share a guest wave. The vote reads EXEC as modelled at the + // branch, OR-ed across the quad, so helper lanes count as on the guest. + void raster_vote(Program &p, bool narrow) { + auto &code = p.code; + const auto mov = narrow ? "s_mov_b32" : "s_mov_b64", andn2 = narrow ? "s_andn2_b32" : "s_andn2_b64"; + const unsigned last_reg = narrow ? 105u : 104u; + auto aligned = [&](unsigned r) { return r <= last_reg && (narrow || !(r & 1)); }; + auto overlaps = [&](const Inst &i, unsigned r) { + const unsigned width = i.name.find("_b64") != Name::npos ? 2 : 1; + return i.enc != Encoding::Sopc && i.dst < r + (narrow ? 1u : 2u) && r < i.dst + width; + }; + auto compare = [](const Inst &i) { + return i.enc == Encoding::Vopc && i.dst == 106 && i.name.substr(0, 6) == "v_cmp_" && + i.name.find("class") == Name::npos; + }; + if (!filters.empty() || code.size() < 10 || code[0].name != mov || code[0].src[0] != 126 || + !aligned(code[0].dst) || !is_wqm(code[1], narrow) || code[1].dst != 126 || code[1].src[0] != 126) + return; + const unsigned entry = code[0].dst; + size_t n = 2; + while (n + 1 < code.size() && !code[n].branch() && !(is_wqm(code[n], narrow) && code[n].dst == 126)) + ++n; + if (n + 1 >= code.size() || code[n].branch() || !code[n + 1].branch() || code[n + 1].op != 8 || + code[n + 1].target() <= code[n + 1].pc) + return; + const auto &wqm = code[n]; + auto &skip = code[n + 1]; + if (!aligned(wqm.src[0]) || wqm.src[0] == entry) + return; + const unsigned mask = wqm.src[0]; + // Before the vote: filters on sE, the mask write and lane-local work. + std::vector filter_pcs; + std::map mask_writes; + bool vcc_from_compare = false; + for (size_t k = 2; k < n; ++k) { + const auto &i = code[k]; + if (compare(i)) { + vcc_from_compare = true; + continue; + } + if (i.name == andn2 && i.src[1] == 106) { + if (!vcc_from_compare) + return; + if (i.dst == entry && i.src[0] == entry && mask_writes.empty()) + filter_pcs.push_back(i.pc); + else if (i.dst == mask && mask_writes.empty() && (i.src[0] == entry || i.src[0] == 126)) + mask_writes.emplace(i.pc, i.src[0] == 126 ? MaskSource::whole_quad : MaskSource::survivors); + else if (i.dst == mask && i.src[0] == mask && !mask_writes.empty()) + mask_writes.emplace(i.pc, MaskSource::narrowed); + else + return; + vcc_from_compare = false; + continue; + } + if (local(i) && !(i.dst < 256 && (i.dst == 106 || i.dst == 107))) + continue; + if (plain_scalar(i) && !overlaps(i, entry) && !overlaps(i, mask)) + continue; + return; + } + if (filter_pcs.empty() || mask_writes.empty()) + return; + // The region: from here on the shape is claimed, so refuse by name. + size_t r = n + 2; + for (; r < code.size() && !(code[r].name == mov && code[r].dst == 126); ++r) { + const auto &i = code[r]; + if (i.name == "s_nop" || i.name == "s_waitcnt") + continue; + if (i.branch()) + refuse(i.pc, "cross-quad EXECZ region contains a branch"); + if (i.name.find("s_setreg") == 0 || i.name.find("s_getreg") == 0) + refuse(i.pc, "cross-quad EXECZ region accesses a hardware register with " + string(i.name)); + if (!plain_scalar(i)) + refuse(i.pc, "cross-quad EXECZ region may only write scalars; " + string(i.name) + + " depends on the lanes the vote leaves out"); + if (overlaps(i, entry)) + refuse(i.pc, "cross-quad EXECZ region overwrites the saved coverage"); + } + if (r == code.size() || code[r].src[0] != entry || skip.target() != code[r].pc) + refuse(skip.pc, "cross-quad EXECZ must branch to the exact coverage restore"); + for (size_t j = r + 1; j < code.size(); ++j) { + const auto &i = code[j]; + if (i.name == "s_endpgm" && j + 1 == code.size()) + break; + if (!(GraphicsMaskRegions::local_alu(i) || i.name == "s_waitcnt" || + (i.enc == Encoding::Export && ((i.a >> 4) & 63) < 8))) + refuse(i.pc, "cross-quad EXECZ needs a terminal colour export after the restore"); + } + for (const auto &i : code) + if (i.branch() && i.pc != skip.pc) + refuse(i.pc, "cross-quad EXECZ program has another branch"); + filters.insert(filter_pcs.begin(), filter_pcs.end()); + vote_masks.insert(mask_writes.begin(), mask_writes.end()); + vote_wqm = wqm.pc; + vote_skip = skip.pc; + exact_restore = code[r].pc; + // SCC carries the vote; it is uniform over the desktop wave. + skip.op = 4; + skip.name = "s_cbranch_scc0"; + } + string expand(DxilModule &ir, const string &mask) const { + auto pair = ir.binary("or", mask, ir.binary("lshr", mask, "1")); + auto nibble = ir.binary("or", pair, ir.binary("lshr", pair, "2")); + return ir.binary("mul", ir.binary("and", nibble, "286331153"), "15"); + } + bool emit_packed(DirectCompute &alu, const Inst &i, bool narrow) const { + if (packed_restores.count(i.pc)) { + auto tag = alu.graphics_registers.find(512 + i.src[0]); + if (tag == alu.graphics_registers.end() || tag->second != "0") + refuse(i.pc, "numeric EXEC region requires saved raster entry coverage"); + alu.write(126, {}); + if (!narrow) + alu.write(127, {}); + return true; + } + if (packed_reads.count(i.pc)) { + if (!narrow && ((i.dst & 1) || i.dst > 104)) + refuse(i.pc, "unaligned EXEC read"); + alu.write(i.dst, alu.read(126)); + if (!narrow) + alu.write(i.dst + 1, alu.read(127)); + return true; + } + const bool to_exec = packed.count(i.pc) != 0; + const bool word = i.name == "s_wqm_b32"; + if (!to_exec && ((!word && i.name != "s_wqm_b64") || i.dst >= 106)) + return false; + if (!alu.graphics_predicate.empty()) + refuse(i.pc, "WQM scalar result inside a lane branch"); + if (i.src[0] >= 106 || (!word && ((i.src[0] | i.dst) & 1))) + refuse(i.pc, "numeric WQM requires an aligned general register source"); + auto low = expand(alu.ir, alu.operand32(i, i.src[0])); + auto high = word ? string{} : expand(alu.ir, alu.operand32(i, i.src[0] + 1)); + auto either = word ? low : alu.ir.binary("or", low, high); + alu.write(i.dst, low); + if (!word) + alu.write(i.dst + 1, high); + alu.write(128, alu.ir.value("zext i1 " + alu.cmp("ne", either, "0") + " to i32")); + return true; + } +}; diff --git a/src/gfx1013_isa.cpp b/src/gfx1013_isa.cpp new file mode 100644 index 000000000..f90925089 --- /dev/null +++ b/src/gfx1013_isa.cpp @@ -0,0 +1,143 @@ +#include "gfx1013_isa.h" +#include +#include +#include +#include + +namespace x2w::gfx1013 { +namespace { +#include "gfx1013_isa_tables.inl" +struct Names { + const char *const *data; + size_t size; +}; +template constexpr Names names(const char *const (&a)[N]) { return {a, N}; } +constexpr Names table[]{names(sopp_names), names(sop1_names), names(sop2_names), names(sopc_names), + names(sopk_names), names(vop1_names), names(vop2_names), names(vopc_names), + names(vop3_names), names(vop3p_names), names(vintrp_names), names(smem_names), + names(mubuf_names), names(mtbuf_names), names(mimg_names), names(ds_names), + names(flat_names), names(global_names), names(scratch_names)}; +std::string_view lookup(Form form, unsigned index) { + if (form == Form::exp) + return "exp"; + const auto &t = table[static_cast(form)]; + return index < t.size && t.data[index] ? t.data[index] : ""; +} +} // namespace +Instruction instruction(std::string_view code, unsigned pc) { + auto word = [&](unsigned index) { + uint64_t at = uint64_t(pc) + 4 * index; + if ((pc & 3) || at > code.size() || code.size() - at < 4) + throw std::runtime_error("truncated or misaligned gfx1013 instruction at byte " + std::to_string(pc)); + uint32_t n; + std::memcpy(&n, code.data() + at, 4); + return n; + }; + const auto a = word(0); + const unsigned top = a >> 26, major = a >> 25; + Form form; + unsigned op, count = 1; + if (!(a >> 31)) { + form = major == 63 ? Form::vop1 : major == 62 ? Form::vopc : Form::vop2; + op = form == Form::vop1 ? (a >> 9) & 255 : form == Form::vopc ? (a >> 17) & 255 : major; + const auto src = a & 511; + bool extension = src == 233 || src == 234 || src == 249 || src == 250 || src == 255; + if (form == Form::vop2) { + const auto name = lookup(form, op); + extension |= name.find("madmk") != name.npos || name.find("madak") != name.npos || + name.find("fmamk") != name.npos || name.find("fmaak") != name.npos; + } + count += extension; + } else if ((a >> 30) == 2) { + switch (a >> 23) { + case 0x17d: + form = Form::sop1; + op = (a >> 8) & 255; + count += (a & 255) == 255; + break; + case 0x17e: + form = Form::sopc; + op = (a >> 16) & 127; + count += (a & 255) == 255 || ((a >> 8) & 255) == 255; + break; + case 0x17f: + form = Form::sopp; + op = (a >> 16) & 127; + break; + default: + if ((a >> 28) == 11) { + form = Form::sopk; + op = (a >> 23) & 31; + count += lookup(form, op) == "s_setreg_imm32_b32"; + } else { + form = Form::sop2; + op = (a >> 23) & 127; + count += (a & 255) == 255 || ((a >> 8) & 255) == 255; + } + } + } else { + count = 2; + switch (top) { + case 0x32: + form = Form::vintrp; + op = (a >> 16) & 3; + count = 1; + break; + case 0x33: + case 0x35: { + form = top == 0x33 ? Form::vop3p : Form::vop3; + op = (a >> 16) & (top == 0x33 ? 127 : 1023); + auto b = word(1); + count += ((b & 511) == 255 || ((b >> 9) & 511) == 255 || ((b >> 18) & 511) == 255); + break; + } + case 0x36: + form = Form::ds; + op = (a >> 18) & 255; + break; + case 0x37: { + unsigned segment = (a >> 14) & 3; + if (segment == 3) + throw std::runtime_error("reserved FLAT segment at byte " + std::to_string(pc)); + form = segment == 0 ? Form::flat : segment == 1 ? Form::scratch : Form::global; + op = (a >> 18) & 127; + break; + } + case 0x38: + form = Form::mubuf; + op = (a >> 18) & 255; + break; + case 0x3a: + form = Form::mtbuf; + op = ((a >> 16) & 7) | ((word(1) >> 18) & 8); + break; + case 0x3c: + form = Form::mimg; + op = ((a >> 18) & 127) | ((a & 1) << 7); + count += (a >> 1) & 3; + break; + case 0x3d: + form = Form::smem; + op = (a >> 18) & 255; + break; + case 0x3e: + form = Form::exp; + op = 0; + break; + default: + throw std::runtime_error("unknown gfx1013 instruction format at byte " + std::to_string(pc)); + } + } + word(count - 1); + auto name = lookup(form, op); + if (form == Form::vop3 && name.empty()) { + if (op < 0x100) + name = lookup(Form::vopc, op); + else if (op < 0x140) + name = lookup(Form::vop2, op - 0x100); + else if (op >= 0x180 && op < 0x200) + name = lookup(Form::vop1, op - 0x180); + } + return {form, op, 4 * count, name}; +} +} // namespace x2w::gfx1013 diff --git a/src/gfx1013_isa.h b/src/gfx1013_isa.h new file mode 100644 index 000000000..1200dd314 --- /dev/null +++ b/src/gfx1013_isa.h @@ -0,0 +1,34 @@ +#pragma once +#include +#include + +namespace x2w::gfx1013 { +enum class Form { + sopp, + sop1, + sop2, + sopc, + sopk, + vop1, + vop2, + vopc, + vop3, + vop3p, + vintrp, + smem, + mubuf, + mtbuf, + mimg, + ds, + flat, + global, + scratch, + exp +}; +struct Instruction { + Form form; + unsigned opcode, size; + std::string_view name; +}; +Instruction instruction(std::string_view code, unsigned pc); +} // namespace x2w::gfx1013 diff --git a/src/gfx1013_isa_tables.inl b/src/gfx1013_isa_tables.inl new file mode 100644 index 000000000..8e68357a1 --- /dev/null +++ b/src/gfx1013_isa_tables.inl @@ -0,0 +1,748 @@ +// GFX10 opcode names, generated from Mesa's src/amd/compiler/aco_opcodes.py +// (tag mesa-22.3.0, GFX10 column), which carries this notice: +// +// Copyright (c) 2018 Valve Corporation +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the "Software"), +// to deal in the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, +// and/or sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice (including the next +// paragraph) shall be included in all copies or substantial portions of the +// Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. +// + +// Generated by tools/startup/import_gfx10_tables.py. +// The secondary entries come from X2W's gfx1013 disassembler. + +constexpr const char* sopp_names[] = { + "s_nop", "s_endpgm", "s_branch", "s_wakeup", + "s_cbranch_scc0", "s_cbranch_scc1", "s_cbranch_vccz", "s_cbranch_vccnz", + "s_cbranch_execz", "s_cbranch_execnz", "s_barrier", "s_setkill", + "s_waitcnt", "s_sethalt", "s_sleep", "s_setprio", + "s_sendmsg", "s_sendmsghalt", "s_trap", "s_icache_inv", + "s_incperflevel", "s_decperflevel", "s_ttracedata", "s_cbranch_cdbgsys", + "s_cbranch_cdbguser", "s_cbranch_cdbgsys_or_user", "s_cbranch_cdbgsys_and_user", "s_endpgm_saved", + nullptr, nullptr, "s_endpgm_ordered_ps_done", "s_code_end", + "s_inst_prefetch", "s_clause", "s_wait_idle", "s_waitcnt_depctr", + "s_round_mode", "s_denorm_mode", nullptr, nullptr, + "s_ttracedata_imm", +}; + +constexpr const char* sop1_names[] = { + nullptr, nullptr, nullptr, "s_mov_b32", + "s_mov_b64", "s_cmov_b32", "s_cmov_b64", "s_not_b32", + "s_not_b64", "s_wqm_b32", "s_wqm_b64", "s_brev_b32", + "s_brev_b64", "s_bcnt0_i32_b32", "s_bcnt0_i32_b64", "s_bcnt1_i32_b32", + "s_bcnt1_i32_b64", "s_ff0_i32_b32", "s_ff0_i32_b64", "s_ff1_i32_b32", + "s_ff1_i32_b64", "s_flbit_i32_b32", "s_flbit_i32_b64", "s_flbit_i32", + "s_flbit_i32_i64", "s_sext_i32_i8", "s_sext_i32_i16", "s_bitset0_b32", + "s_bitset0_b64", "s_bitset1_b32", "s_bitset1_b64", "s_getpc_b64", + "s_setpc_b64", "s_swappc_b64", "s_rfe_b64", nullptr, + "s_and_saveexec_b64", "s_or_saveexec_b64", "s_xor_saveexec_b64", "s_andn2_saveexec_b64", + "s_orn2_saveexec_b64", "s_nand_saveexec_b64", "s_nor_saveexec_b64", "s_xnor_saveexec_b64", + "s_quadmask_b32", "s_quadmask_b64", "s_movrels_b32", "s_movrels_b64", + "s_movreld_b32", "s_movreld_b64", nullptr, nullptr, + "s_abs_i32", "s_mov_fed_b32", nullptr, "s_andn1_saveexec_b64", + "s_orn1_saveexec_b64", "s_andn1_wrexec_b64", "s_andn2_wrexec_b64", "s_bitreplicate_b64_b32", + "s_and_saveexec_b32", "s_or_saveexec_b32", "s_xor_saveexec_b32", "s_andn2_saveexec_b32", + "s_orn2_saveexec_b32", "s_nand_saveexec_b32", "s_nor_saveexec_b32", "s_xnor_saveexec_b32", + "s_andn1_saveexec_b32", "s_orn1_saveexec_b32", "s_andn1_wrexec_b32", "s_andn2_wrexec_b32", + nullptr, "s_movrelsd_2_b32", +}; + +constexpr const char* sop2_names[] = { + "s_add_u32", "s_sub_u32", "s_add_i32", "s_sub_i32", + "s_addc_u32", "s_subb_u32", "s_min_i32", "s_min_u32", + "s_max_i32", "s_max_u32", "s_cselect_b32", "s_cselect_b64", + nullptr, nullptr, "s_and_b32", "s_and_b64", + "s_or_b32", "s_or_b64", "s_xor_b32", "s_xor_b64", + "s_andn2_b32", "s_andn2_b64", "s_orn2_b32", "s_orn2_b64", + "s_nand_b32", "s_nand_b64", "s_nor_b32", "s_nor_b64", + "s_xnor_b32", "s_xnor_b64", "s_lshl_b32", "s_lshl_b64", + "s_lshr_b32", "s_lshr_b64", "s_ashr_i32", "s_ashr_i64", + "s_bfm_b32", "s_bfm_b64", "s_mul_i32", "s_bfe_u32", + "s_bfe_i32", "s_bfe_u64", "s_bfe_i64", nullptr, + "s_absdiff_i32", nullptr, "s_lshl1_add_u32", "s_lshl2_add_u32", + "s_lshl3_add_u32", "s_lshl4_add_u32", "s_pack_ll_b32_b16", "s_pack_lh_b32_b16", + "s_pack_hh_b32_b16", "s_mul_hi_u32", "s_mul_hi_i32", +}; + +constexpr const char* sopc_names[] = { + "s_cmp_eq_i32", "s_cmp_lg_i32", "s_cmp_gt_i32", "s_cmp_ge_i32", + "s_cmp_lt_i32", "s_cmp_le_i32", "s_cmp_eq_u32", "s_cmp_lg_u32", + "s_cmp_gt_u32", "s_cmp_ge_u32", "s_cmp_lt_u32", "s_cmp_le_u32", + "s_bitcmp0_b32", "s_bitcmp1_b32", "s_bitcmp0_b64", "s_bitcmp1_b64", + nullptr, nullptr, "s_cmp_eq_u64", "s_cmp_lg_u64", +}; + +constexpr const char* sopk_names[] = { + "s_movk_i32", "s_version", "s_cmovk_i32", "s_cmpk_eq_i32", + "s_cmpk_lg_i32", "s_cmpk_gt_i32", "s_cmpk_ge_i32", "s_cmpk_lt_i32", + "s_cmpk_le_i32", "s_cmpk_eq_u32", "s_cmpk_lg_u32", "s_cmpk_gt_u32", + "s_cmpk_ge_u32", "s_cmpk_lt_u32", "s_cmpk_le_u32", "s_addk_i32", + "s_mulk_i32", nullptr, "s_getreg_b32", "s_setreg_b32", + nullptr, "s_setreg_imm32_b32", "s_call_b64", "s_waitcnt_vscnt", + "s_waitcnt_vmcnt", "s_waitcnt_expcnt", "s_waitcnt_lgkmcnt", "s_subvector_loop_begin", + "s_subvector_loop_end", +}; + +constexpr const char* vop1_names[] = { + "v_nop", "v_mov_b32", "v_readfirstlane_b32", "v_cvt_i32_f64", + "v_cvt_f64_i32", "v_cvt_f32_i32", "v_cvt_f32_u32", "v_cvt_u32_f32", + "v_cvt_i32_f32", nullptr, "v_cvt_f16_f32", "v_cvt_f32_f16", + "v_cvt_rpi_i32_f32", "v_cvt_flr_i32_f32", "v_cvt_off_f32_i4", "v_cvt_f32_f64", + "v_cvt_f64_f32", "v_cvt_f32_ubyte0", "v_cvt_f32_ubyte1", "v_cvt_f32_ubyte2", + "v_cvt_f32_ubyte3", "v_cvt_u32_f64", "v_cvt_f64_u32", "v_trunc_f64", + "v_ceil_f64", "v_rndne_f64", "v_floor_f64", "v_pipeflush", + nullptr, nullptr, nullptr, nullptr, + "v_fract_f32", "v_trunc_f32", "v_ceil_f32", "v_rndne_f32", + "v_floor_f32", "v_exp_f32", nullptr, "v_log_f32", + nullptr, nullptr, "v_rcp_f32", "v_rcp_iflag_f32", + nullptr, nullptr, "v_rsq_f32", "v_rcp_f64", + nullptr, "v_rsq_f64", nullptr, "v_sqrt_f32", + "v_sqrt_f64", "v_sin_f32", "v_cos_f32", "v_not_b32", + "v_bfrev_b32", "v_ffbh_u32", "v_ffbl_b32", "v_ffbh_i32", + "v_frexp_exp_i32_f64", "v_frexp_mant_f64", "v_fract_f64", "v_frexp_exp_i32_f32", + "v_frexp_mant_f32", "v_clrexcp", "v_movreld_b32", "v_movrels_b32", + "v_movrelsd_b32", nullptr, nullptr, nullptr, + "v_movrelsd_2_b32", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "v_cvt_f16_u16", "v_cvt_f16_i16", "v_cvt_u16_f16", "v_cvt_i16_f16", + "v_rcp_f16", "v_sqrt_f16", "v_rsq_f16", "v_log_f16", + "v_exp_f16", "v_frexp_mant_f16", "v_frexp_exp_i16_f16", "v_floor_f16", + "v_ceil_f16", "v_trunc_f16", "v_rndne_f16", "v_fract_f16", + "v_sin_f16", "v_cos_f16", "v_sat_pk_u8_i16", "v_cvt_norm_i16_f16", + "v_cvt_norm_u16_f16", "v_swap_b32", nullptr, nullptr, + "v_swaprel_b32", +}; + +constexpr const char* vop2_names[] = { + nullptr, "v_cndmask_b32", "v_dot2c_f32_f16", "v_add_f32", + "v_sub_f32", "v_subrev_f32", "v_mac_legacy_f32", "v_mul_legacy_f32", + "v_mul_f32", "v_mul_i32_i24", "v_mul_hi_i32_i24", "v_mul_u32_u24", + "v_mul_hi_u32_u24", "v_dot4c_i32_i8", nullptr, "v_min_f32", + "v_max_f32", "v_min_i32", "v_max_i32", "v_min_u32", + "v_max_u32", nullptr, "v_lshrrev_b32", nullptr, + "v_ashrrev_i32", nullptr, "v_lshlrev_b32", "v_and_b32", + "v_or_b32", "v_xor_b32", "v_xnor_b32", "v_mac_f32", + "v_madmk_f32", "v_madak_f32", nullptr, nullptr, + nullptr, "v_add_nc_u32", "v_sub_nc_u32", "v_subrev_nc_u32", + "v_add_co_ci_u32", "v_sub_co_ci_u32", "v_subrev_co_ci_u32", "v_fmac_f32", + "v_fmamk_f32", "v_fmaak_f32", nullptr, "v_cvt_pkrtz_f16_f32", + nullptr, nullptr, "v_add_f16", "v_sub_f16", + "v_subrev_f16", "v_mul_f16", "v_fmac_f16", "v_fmamk_f16", + "v_fmaak_f16", "v_max_f16", "v_min_f16", "v_ldexp_f16", + "v_pk_fmac_f16", +}; + +constexpr const char* vopc_names[] = { + "v_cmp_f_f32", "v_cmp_lt_f32", "v_cmp_eq_f32", "v_cmp_le_f32", + "v_cmp_gt_f32", "v_cmp_lg_f32", "v_cmp_ge_f32", "v_cmp_o_f32", + "v_cmp_u_f32", "v_cmp_nge_f32", "v_cmp_nlg_f32", "v_cmp_ngt_f32", + "v_cmp_nle_f32", "v_cmp_neq_f32", "v_cmp_nlt_f32", "v_cmp_tru_f32", + "v_cmpx_f_f32", "v_cmpx_lt_f32", "v_cmpx_eq_f32", "v_cmpx_le_f32", + "v_cmpx_gt_f32", "v_cmpx_lg_f32", "v_cmpx_ge_f32", "v_cmpx_o_f32", + "v_cmpx_u_f32", "v_cmpx_nge_f32", "v_cmpx_nlg_f32", "v_cmpx_ngt_f32", + "v_cmpx_nle_f32", "v_cmpx_neq_f32", "v_cmpx_nlt_f32", "v_cmpx_tru_f32", + "v_cmp_f_f64", "v_cmp_lt_f64", "v_cmp_eq_f64", "v_cmp_le_f64", + "v_cmp_gt_f64", "v_cmp_lg_f64", "v_cmp_ge_f64", "v_cmp_o_f64", + "v_cmp_u_f64", "v_cmp_nge_f64", "v_cmp_nlg_f64", "v_cmp_ngt_f64", + "v_cmp_nle_f64", "v_cmp_neq_f64", "v_cmp_nlt_f64", "v_cmp_tru_f64", + "v_cmpx_f_f64", "v_cmpx_lt_f64", "v_cmpx_eq_f64", "v_cmpx_le_f64", + "v_cmpx_gt_f64", "v_cmpx_lg_f64", "v_cmpx_ge_f64", "v_cmpx_o_f64", + "v_cmpx_u_f64", "v_cmpx_nge_f64", "v_cmpx_nlg_f64", "v_cmpx_ngt_f64", + "v_cmpx_nle_f64", "v_cmpx_neq_f64", "v_cmpx_nlt_f64", "v_cmpx_tru_f64", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "v_cmp_f_i32", "v_cmp_lt_i32", "v_cmp_eq_i32", "v_cmp_le_i32", + "v_cmp_gt_i32", "v_cmp_ne_i32", "v_cmp_ge_i32", "v_cmp_t_i32", + "v_cmp_class_f32", "v_cmp_lt_i16", "v_cmp_eq_i16", "v_cmp_le_i16", + "v_cmp_gt_i16", "v_cmp_ne_i16", "v_cmp_ge_i16", "v_cmp_class_f16", + "v_cmpx_f_i32", "v_cmpx_lt_i32", "v_cmpx_eq_i32", "v_cmpx_le_i32", + "v_cmpx_gt_i32", "v_cmpx_ne_i32", "v_cmpx_ge_i32", "v_cmpx_t_i32", + "v_cmpx_class_f32", "v_cmpx_lt_i16", "v_cmpx_eq_i16", "v_cmpx_le_i16", + "v_cmpx_gt_i16", "v_cmpx_ne_i16", "v_cmpx_ge_i16", "v_cmpx_class_f16", + "v_cmp_f_i64", "v_cmp_lt_i64", "v_cmp_eq_i64", "v_cmp_le_i64", + "v_cmp_gt_i64", "v_cmp_ne_i64", "v_cmp_ge_i64", "v_cmp_t_i64", + "v_cmp_class_f64", "v_cmp_lt_u16", "v_cmp_eq_u16", "v_cmp_le_u16", + "v_cmp_gt_u16", "v_cmp_ne_u16", "v_cmp_ge_u16", nullptr, + "v_cmpx_f_i64", "v_cmpx_lt_i64", "v_cmpx_eq_i64", "v_cmpx_le_i64", + "v_cmpx_gt_i64", "v_cmpx_ne_i64", "v_cmpx_ge_i64", "v_cmpx_t_i64", + "v_cmpx_class_f64", "v_cmpx_lt_u16", "v_cmpx_eq_u16", "v_cmpx_le_u16", + "v_cmpx_gt_u16", "v_cmpx_ne_u16", "v_cmpx_ge_u16", nullptr, + "v_cmp_f_u32", "v_cmp_lt_u32", "v_cmp_eq_u32", "v_cmp_le_u32", + "v_cmp_gt_u32", "v_cmp_ne_u32", "v_cmp_ge_u32", "v_cmp_t_u32", + "v_cmp_f_f16", "v_cmp_lt_f16", "v_cmp_eq_f16", "v_cmp_le_f16", + "v_cmp_gt_f16", "v_cmp_lg_f16", "v_cmp_ge_f16", "v_cmp_o_f16", + "v_cmpx_f_u32", "v_cmpx_lt_u32", "v_cmpx_eq_u32", "v_cmpx_le_u32", + "v_cmpx_gt_u32", "v_cmpx_ne_u32", "v_cmpx_ge_u32", "v_cmpx_t_u32", + "v_cmpx_f_f16", "v_cmpx_lt_f16", "v_cmpx_eq_f16", "v_cmpx_le_f16", + "v_cmpx_gt_f16", "v_cmpx_lg_f16", "v_cmpx_ge_f16", "v_cmpx_o_f16", + "v_cmp_f_u64", "v_cmp_lt_u64", "v_cmp_eq_u64", "v_cmp_le_u64", + "v_cmp_gt_u64", "v_cmp_ne_u64", "v_cmp_ge_u64", "v_cmp_t_u64", + "v_cmp_u_f16", "v_cmp_nge_f16", "v_cmp_nlg_f16", "v_cmp_ngt_f16", + "v_cmp_nle_f16", "v_cmp_neq_f16", "v_cmp_nlt_f16", "v_cmp_tru_f16", + "v_cmpx_f_u64", "v_cmpx_lt_u64", "v_cmpx_eq_u64", "v_cmpx_le_u64", + "v_cmpx_gt_u64", "v_cmpx_ne_u64", "v_cmpx_ge_u64", "v_cmpx_t_u64", + "v_cmpx_u_f16", "v_cmpx_nge_f16", "v_cmpx_nlg_f16", "v_cmpx_ngt_f16", + "v_cmpx_nle_f16", "v_cmpx_neq_f16", "v_cmpx_nlt_f16", "v_cmpx_tru_f16", +}; + +constexpr const char* vop3_names[] = { + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "v_add_co_ci_u32", "v_sub_co_ci_u32", "v_subrev_co_ci_u32", nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "v_mad_legacy_f32", "v_mad_f32", "v_mad_i32_i24", "v_mad_u32_u24", + "v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32", "v_cubema_f32", + "v_bfe_u32", "v_bfe_i32", "v_bfi_b32", "v_fma_f32", + "v_fma_f64", "v_lerp_u8", "v_alignbit_b32", "v_alignbyte_b32", + "v_mullit_f32", "v_min3_f32", "v_min3_i32", "v_min3_u32", + "v_max3_f32", "v_max3_i32", "v_max3_u32", "v_med3_f32", + "v_med3_i32", "v_med3_u32", "v_sad_u8", "v_sad_hi_u8", + "v_sad_u16", "v_sad_u32", "v_cvt_pk_u8_f32", "v_div_fixup_f32", + "v_div_fixup_f64", nullptr, nullptr, nullptr, + "v_add_f64", "v_mul_f64", "v_min_f64", "v_max_f64", + "v_ldexp_f64", "v_mul_lo_u32", "v_mul_hi_u32", "v_mul_lo_i32", + "v_mul_hi_i32", "v_div_scale_f32", "v_div_scale_f64", "v_div_fmas_f32", + "v_div_fmas_f64", "v_msad_u8", "v_qsad_pk_u16_u8", "v_mqsad_pk_u16_u8", + "v_trig_preop_f64", "v_mqsad_u32_u8", "v_mad_u64_u32", "v_mad_i64_i32", + "v_xor3_b32", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, "v_interp_mov_f32", nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, "v_lshlrev_b64", + "v_lshrrev_b64", "v_ashrrev_i64", nullptr, "v_add_nc_u16", + "v_sub_nc_u16", "v_mul_lo_u16", nullptr, "v_lshrrev_b16", + "v_ashrrev_i16", "v_max_u16", "v_max_i16", "v_min_u16", + "v_min_i16", "v_add_nc_i16", "v_sub_nc_i16", "v_add_co_u32", + "v_sub_co_u32", "v_pack_b32_f16", "v_cvt_pknorm_i16_f16", "v_cvt_pknorm_u16_f16", + "v_lshlrev_b16", nullptr, nullptr, nullptr, + nullptr, "v_subrev_co_u32", nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "v_mad_u16", nullptr, "v_interp_p1ll_f16", "v_interp_p1lv_f16", + "v_perm_b32", "v_xad_u32", "v_lshl_add_u32", "v_add_lshl_u32", + nullptr, nullptr, nullptr, "v_fma_f16", + nullptr, nullptr, nullptr, nullptr, + nullptr, "v_min3_f16", "v_min3_i16", "v_min3_u16", + "v_max3_f16", "v_max3_i16", "v_max3_u16", "v_med3_f16", + "v_med3_i16", "v_med3_u16", "v_interp_p2_f16", nullptr, + nullptr, nullptr, "v_mad_i16", "v_div_fixup_f16", + "v_readlane_b32", "v_writelane_b32", "v_ldexp_f32", "v_bfm_b32", + "v_bcnt_u32_b32", "v_mbcnt_lo_u32_b32", "v_mbcnt_hi_u32_b32", nullptr, + "v_cvt_pknorm_i16_f32", "v_cvt_pknorm_u16_f32", "v_cvt_pk_u16_u32", "v_cvt_pk_i16_i32", + nullptr, "v_add3_u32", nullptr, "v_lshl_or_b32", + nullptr, "v_and_or_b32", "v_or3_b32", "v_mad_u32_u16", + nullptr, "v_mad_i32_i16", "v_sub_nc_i32", "v_permlane16_b32", + "v_permlanex16_b32", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, "v_add_nc_i32", +}; + +constexpr const char* vop3p_names[] = { + "v_pk_mad_i16", "v_pk_mul_lo_u16", "v_pk_add_i16", "v_pk_sub_i16", + "v_pk_lshlrev_b16", "v_pk_lshrrev_b16", "v_pk_ashrrev_i16", "v_pk_max_i16", + "v_pk_min_i16", "v_pk_mad_u16", "v_pk_add_u16", "v_pk_sub_u16", + "v_pk_max_u16", "v_pk_min_u16", "v_pk_fma_f16", "v_pk_add_f16", + "v_pk_mul_f16", "v_pk_min_f16", "v_pk_max_f16", "v_dot2_f32_f16", + "v_dot2_i32_i16", "v_dot2_u32_u16", "v_dot4_i32_i8", "v_dot4_u32_u8", + "v_dot8_i32_i4", "v_dot8_u32_u4", nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "v_fma_mix_f32", "v_fma_mixlo_f16", "v_fma_mixhi_f16", +}; + +constexpr const char* vintrp_names[] = { + "v_interp_p1_f32", "v_interp_p2_f32", "v_interp_mov_f32", +}; + +constexpr const char* smem_names[] = { + "s_load_dword", "s_load_dwordx2", "s_load_dwordx4", "s_load_dwordx8", + "s_load_dwordx16", "s_scratch_load_dword", "s_scratch_load_dwordx2", "s_scratch_load_dwordx4", + "s_buffer_load_dword", "s_buffer_load_dwordx2", "s_buffer_load_dwordx4", "s_buffer_load_dwordx8", + "s_buffer_load_dwordx16", nullptr, nullptr, nullptr, + "s_store_dword", "s_store_dwordx2", "s_store_dwordx4", nullptr, + nullptr, "s_scratch_store_dword", "s_scratch_store_dwordx2", "s_scratch_store_dwordx4", + "s_buffer_store_dword", "s_buffer_store_dwordx2", "s_buffer_store_dwordx4", nullptr, + nullptr, nullptr, nullptr, "s_gl1_inv", + "s_dcache_inv", "s_dcache_wb", nullptr, nullptr, + "s_memtime", "s_memrealtime", "s_atc_probe", "s_atc_probe_buffer", + "s_dcache_discard", "s_dcache_discard_x2", "s_get_waveid_in_workgroup", nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "s_buffer_atomic_swap", "s_buffer_atomic_cmpswap", "s_buffer_atomic_add", "s_buffer_atomic_sub", + "s_buffer_atomic_smin", "s_buffer_atomic_umin", "s_buffer_atomic_smax", "s_buffer_atomic_umax", + "s_buffer_atomic_and", "s_buffer_atomic_or", "s_buffer_atomic_xor", "s_buffer_atomic_inc", + "s_buffer_atomic_dec", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "s_buffer_atomic_swap_x2", "s_buffer_atomic_cmpswap_x2", "s_buffer_atomic_add_x2", "s_buffer_atomic_sub_x2", + "s_buffer_atomic_smin_x2", "s_buffer_atomic_umin_x2", "s_buffer_atomic_smax_x2", "s_buffer_atomic_umax_x2", + "s_buffer_atomic_and_x2", "s_buffer_atomic_or_x2", "s_buffer_atomic_xor_x2", "s_buffer_atomic_inc_x2", + "s_buffer_atomic_dec_x2", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "s_atomic_swap", "s_atomic_cmpswap", "s_atomic_add", "s_atomic_sub", + "s_atomic_smin", "s_atomic_umin", "s_atomic_smax", "s_atomic_umax", + "s_atomic_and", "s_atomic_or", "s_atomic_xor", "s_atomic_inc", + "s_atomic_dec", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "s_atomic_swap_x2", "s_atomic_cmpswap_x2", "s_atomic_add_x2", "s_atomic_sub_x2", + "s_atomic_smin_x2", "s_atomic_umin_x2", "s_atomic_smax_x2", "s_atomic_umax_x2", + "s_atomic_and_x2", "s_atomic_or_x2", "s_atomic_xor_x2", "s_atomic_inc_x2", + "s_atomic_dec_x2", +}; + +constexpr const char* mubuf_names[] = { + "buffer_load_format_x", "buffer_load_format_xy", "buffer_load_format_xyz", "buffer_load_format_xyzw", + "buffer_store_format_x", "buffer_store_format_xy", "buffer_store_format_xyz", "buffer_store_format_xyzw", + "buffer_load_ubyte", "buffer_load_sbyte", "buffer_load_ushort", "buffer_load_sshort", + "buffer_load_dword", "buffer_load_dwordx2", "buffer_load_dwordx4", "buffer_load_dwordx3", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "buffer_store_byte", "buffer_store_byte_d16_hi", "buffer_store_short", "buffer_store_short_d16_hi", + "buffer_store_dword", "buffer_store_dwordx2", "buffer_store_dwordx4", "buffer_store_dwordx3", + "buffer_load_ubyte_d16", "buffer_load_ubyte_d16_hi", "buffer_load_sbyte_d16", "buffer_load_sbyte_d16_hi", + "buffer_load_short_d16", "buffer_load_short_d16_hi", "buffer_load_format_d16_hi_x", "buffer_store_format_d16_hi_x", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "buffer_atomic_swap", "buffer_atomic_cmpswap", "buffer_atomic_add", "buffer_atomic_sub", + "buffer_atomic_csub", "buffer_atomic_smin", "buffer_atomic_umin", "buffer_atomic_smax", + "buffer_atomic_umax", "buffer_atomic_and", "buffer_atomic_or", "buffer_atomic_xor", + "buffer_atomic_inc", "buffer_atomic_dec", "buffer_atomic_fcmpswap", "buffer_atomic_fmin", + "buffer_atomic_fmax", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "buffer_atomic_swap_x2", "buffer_atomic_cmpswap_x2", "buffer_atomic_add_x2", "buffer_atomic_sub_x2", + nullptr, "buffer_atomic_smin_x2", "buffer_atomic_umin_x2", "buffer_atomic_smax_x2", + "buffer_atomic_umax_x2", "buffer_atomic_and_x2", "buffer_atomic_or_x2", "buffer_atomic_xor_x2", + "buffer_atomic_inc_x2", "buffer_atomic_dec_x2", "buffer_atomic_fcmpswap_x2", "buffer_atomic_fmin_x2", + "buffer_atomic_fmax_x2", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, "buffer_gl0_inv", "buffer_gl1_inv", nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "buffer_load_format_d16_x", "buffer_load_format_d16_xy", "buffer_load_format_d16_xyz", "buffer_load_format_d16_xyzw", + "buffer_store_format_d16_x", "buffer_store_format_d16_xy", "buffer_store_format_d16_xyz", "buffer_store_format_d16_xyzw", +}; + +constexpr const char* mtbuf_names[] = { + "tbuffer_load_format_x", "tbuffer_load_format_xy", "tbuffer_load_format_xyz", "tbuffer_load_format_xyzw", + "tbuffer_store_format_x", "tbuffer_store_format_xy", "tbuffer_store_format_xyz", "tbuffer_store_format_xyzw", + "tbuffer_load_format_d16_x", "tbuffer_load_format_d16_xy", "tbuffer_load_format_d16_xyz", "tbuffer_load_format_d16_xyzw", + "tbuffer_store_format_d16_x", "tbuffer_store_format_d16_xy", "tbuffer_store_format_d16_xyz", "tbuffer_store_format_d16_xyzw", +}; + +constexpr const char* mimg_names[] = { + "image_load", "image_load_mip", "image_load_pck", "image_load_pck_sgn", + "image_load_mip_pck", "image_load_mip_pck_sgn", nullptr, nullptr, + "image_store", "image_store_mip", "image_store_pck", "image_store_mip_pck", + nullptr, nullptr, "image_get_resinfo", "image_atomic_swap", + "image_atomic_cmpswap", "image_atomic_add", "image_atomic_sub", nullptr, + "image_atomic_smin", "image_atomic_umin", "image_atomic_smax", "image_atomic_umax", + "image_atomic_and", "image_atomic_or", "image_atomic_xor", "image_atomic_inc", + "image_atomic_dec", "image_atomic_fcmpswap", "image_atomic_fmin", "image_atomic_fmax", + "image_sample", "image_sample_cl", "image_sample_d", "image_sample_d_cl", + "image_sample_l", "image_sample_b", "image_sample_b_cl", "image_sample_lz", + "image_sample_c", "image_sample_c_cl", "image_sample_c_d", "image_sample_c_d_cl", + "image_sample_c_l", "image_sample_c_b", "image_sample_c_b_cl", "image_sample_c_lz", + "image_sample_o", "image_sample_cl_o", "image_sample_d_o", "image_sample_d_cl_o", + "image_sample_l_o", "image_sample_b_o", "image_sample_b_cl_o", "image_sample_lz_o", + "image_sample_c_o", "image_sample_c_cl_o", "image_sample_c_d_o", "image_sample_c_d_cl_o", + "image_sample_c_l_o", "image_sample_c_b_o", "image_sample_c_b_cl_o", "image_sample_c_lz_o", + "image_gather4", "image_gather4_cl", nullptr, nullptr, + "image_gather4_l", "image_gather4_b", "image_gather4_b_cl", "image_gather4_lz", + "image_gather4_c", "image_gather4_c_cl", nullptr, nullptr, + "image_gather4_c_l", "image_gather4_c_b", "image_gather4_c_b_cl", "image_gather4_c_lz", + "image_gather4_o", "image_gather4_cl_o", nullptr, nullptr, + "image_gather4_l_o", "image_gather4_b_o", "image_gather4_b_cl_o", "image_gather4_lz_o", + "image_gather4_c_o", "image_gather4_c_cl_o", nullptr, nullptr, + "image_gather4_c_l_o", "image_gather4_c_b_o", "image_gather4_c_b_cl_o", "image_gather4_c_lz_o", + "image_get_lod", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "image_sample_cd", "image_sample_cd_cl", "image_sample_c_cd", "image_sample_c_cd_cl", + "image_sample_cd_o", "image_sample_cd_cl_o", "image_sample_c_cd_o", "image_sample_c_cd_cl_o", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "image_msaa_load", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, "image_sample_d_g16", "image_sample_d_cl_g16", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, "image_sample_c_d_g16", "image_sample_c_d_cl_g16", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, "image_sample_d_o_g16", "image_sample_d_cl_o_g16", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, "image_sample_c_d_o_g16", "image_sample_c_d_cl_o_g16", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, "image_bvh_intersect_ray", "image_bvh64_intersect_ray", + "image_sample_cd_g16", "image_sample_cd_cl_g16", "image_sample_c_cd_g16", "image_sample_c_cd_cl_g16", + "image_sample_cd_o_g16", "image_sample_cd_cl_o_g16", "image_sample_c_cd_o_g16", "image_sample_c_cd_cl_o_g16", +}; + +constexpr const char* ds_names[] = { + "ds_add_u32", "ds_sub_u32", "ds_rsub_u32", "ds_inc_u32", + "ds_dec_u32", "ds_min_i32", "ds_max_i32", "ds_min_u32", + "ds_max_u32", "ds_and_b32", "ds_or_b32", "ds_xor_b32", + "ds_mskor_b32", "ds_write_b32", "ds_write2_b32", "ds_write2st64_b32", + "ds_cmpst_b32", "ds_cmpst_f32", "ds_min_f32", "ds_max_f32", + "ds_nop", "ds_add_f32", nullptr, nullptr, + "ds_gws_sema_release_all", "ds_gws_init", "ds_gws_sema_v", "ds_gws_sema_br", + "ds_gws_sema_p", "ds_gws_barrier", "ds_write_b8", "ds_write_b16", + "ds_add_rtn_u32", "ds_sub_rtn_u32", "ds_rsub_rtn_u32", "ds_inc_rtn_u32", + "ds_dec_rtn_u32", "ds_min_rtn_i32", "ds_max_rtn_i32", "ds_min_rtn_u32", + "ds_max_rtn_u32", "ds_and_rtn_b32", "ds_or_rtn_b32", "ds_xor_rtn_b32", + "ds_mskor_rtn_b32", "ds_wrxchg_rtn_b32", "ds_wrxchg2_rtn_b32", "ds_wrxchg2st64_rtn_b32", + "ds_cmpst_rtn_b32", "ds_cmpst_rtn_f32", "ds_min_rtn_f32", "ds_max_rtn_f32", + "ds_wrap_rtn_b32", "ds_swizzle_b32", "ds_read_b32", "ds_read2_b32", + "ds_read2st64_b32", "ds_read_i8", "ds_read_u8", "ds_read_i16", + "ds_read_u16", "ds_consume", "ds_append", "ds_ordered_count", + "ds_add_u64", "ds_sub_u64", "ds_rsub_u64", "ds_inc_u64", + "ds_dec_u64", "ds_min_i64", "ds_max_i64", "ds_min_u64", + "ds_max_u64", "ds_and_b64", "ds_or_b64", "ds_xor_b64", + "ds_mskor_b64", "ds_write_b64", "ds_write2_b64", "ds_write2st64_b64", + "ds_cmpst_b64", "ds_cmpst_f64", "ds_min_f64", "ds_max_f64", + nullptr, "ds_add_rtn_f32", nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "ds_add_rtn_u64", "ds_sub_rtn_u64", "ds_rsub_rtn_u64", "ds_inc_rtn_u64", + "ds_dec_rtn_u64", "ds_min_rtn_i64", "ds_max_rtn_i64", "ds_min_rtn_u64", + "ds_max_rtn_u64", "ds_and_rtn_b64", "ds_or_rtn_b64", "ds_xor_rtn_b64", + "ds_mskor_rtn_b64", "ds_wrxchg_rtn_b64", "ds_wrxchg2_rtn_b64", "ds_wrxchg2st64_rtn_b64", + "ds_cmpst_rtn_b64", "ds_cmpst_rtn_f64", "ds_min_rtn_f64", "ds_max_rtn_f64", + nullptr, nullptr, "ds_read_b64", "ds_read2_b64", + "ds_read2st64_b64", nullptr, nullptr, nullptr, + nullptr, nullptr, "ds_condxchg32_rtn_b64", nullptr, + "ds_add_src2_u32", "ds_sub_src2_u32", "ds_rsub_src2_u32", "ds_inc_src2_u32", + "ds_dec_src2_u32", "ds_min_src2_i32", "ds_max_src2_i32", "ds_min_src2_u32", + "ds_max_src2_u32", "ds_and_src2_b32", "ds_or_src2_b32", "ds_xor_src2_b32", + nullptr, "ds_write_src2_b32", nullptr, nullptr, + nullptr, nullptr, "ds_min_src2_f32", "ds_max_src2_f32", + nullptr, "ds_add_src2_f32", nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "ds_write_b8_d16_hi", "ds_write_b16_d16_hi", "ds_read_u8_d16", "ds_read_u8_d16_hi", + "ds_read_i8_d16", "ds_read_i8_d16_hi", "ds_read_u16_d16", "ds_read_u16_d16_hi", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "ds_write_addtid_b32", "ds_read_addtid_b32", "ds_permute_b32", "ds_bpermute_b32", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "ds_add_src2_u64", "ds_sub_src2_u64", "ds_rsub_src2_u64", "ds_inc_src2_u64", + "ds_dec_src2_u64", "ds_min_src2_i64", "ds_max_src2_i64", "ds_min_src2_u64", + "ds_max_src2_u64", "ds_and_src2_b64", "ds_or_src2_b64", "ds_xor_src2_b64", + nullptr, "ds_write_src2_b64", nullptr, nullptr, + nullptr, nullptr, "ds_min_src2_f64", "ds_max_src2_f64", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, "ds_write_b96", "ds_write_b128", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, "ds_read_b96", "ds_read_b128", +}; + +constexpr const char* flat_names[] = { + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "flat_load_ubyte", "flat_load_sbyte", "flat_load_ushort", "flat_load_sshort", + "flat_load_dword", "flat_load_dwordx2", "flat_load_dwordx4", "flat_load_dwordx3", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "flat_store_byte", "flat_store_byte_d16_hi", "flat_store_short", "flat_store_short_d16_hi", + "flat_store_dword", "flat_store_dwordx2", "flat_store_dwordx4", "flat_store_dwordx3", + "flat_load_ubyte_d16", "flat_load_ubyte_d16_hi", "flat_load_sbyte_d16", "flat_load_sbyte_d16_hi", + "flat_load_short_d16", "flat_load_short_d16_hi", nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "flat_atomic_swap", "flat_atomic_cmpswap", "flat_atomic_add", "flat_atomic_sub", + nullptr, "flat_atomic_smin", "flat_atomic_umin", "flat_atomic_smax", + "flat_atomic_umax", "flat_atomic_and", "flat_atomic_or", "flat_atomic_xor", + "flat_atomic_inc", "flat_atomic_dec", "flat_atomic_fcmpswap", "flat_atomic_fmin", + "flat_atomic_fmax", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "flat_atomic_swap_x2", "flat_atomic_cmpswap_x2", "flat_atomic_add_x2", "flat_atomic_sub_x2", + nullptr, "flat_atomic_smin_x2", "flat_atomic_umin_x2", "flat_atomic_smax_x2", + "flat_atomic_umax_x2", "flat_atomic_and_x2", "flat_atomic_or_x2", "flat_atomic_xor_x2", + "flat_atomic_inc_x2", "flat_atomic_dec_x2", "flat_atomic_fcmpswap_x2", "flat_atomic_fmin_x2", + "flat_atomic_fmax_x2", +}; + +constexpr const char* global_names[] = { + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "global_load_ubyte", "global_load_sbyte", "global_load_ushort", "global_load_sshort", + "global_load_dword", "global_load_dwordx2", "global_load_dwordx4", "global_load_dwordx3", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, "global_load_dword_addtid", "global_store_dword_addtid", + "global_store_byte", "global_store_byte_d16_hi", "global_store_short", "global_store_short_d16_hi", + "global_store_dword", "global_store_dwordx2", "global_store_dwordx4", "global_store_dwordx3", + "global_load_ubyte_d16", "global_load_ubyte_d16_hi", "global_load_sbyte_d16", "global_load_sbyte_d16_hi", + "global_load_short_d16", "global_load_short_d16_hi", nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "global_atomic_swap", "global_atomic_cmpswap", "global_atomic_add", "global_atomic_sub", + "global_atomic_csub", "global_atomic_smin", "global_atomic_umin", "global_atomic_smax", + "global_atomic_umax", "global_atomic_and", "global_atomic_or", "global_atomic_xor", + "global_atomic_inc", "global_atomic_dec", "global_atomic_fcmpswap", "global_atomic_fmin", + "global_atomic_fmax", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "global_atomic_swap_x2", "global_atomic_cmpswap_x2", "global_atomic_add_x2", "global_atomic_sub_x2", + nullptr, "global_atomic_smin_x2", "global_atomic_umin_x2", "global_atomic_smax_x2", + "global_atomic_umax_x2", "global_atomic_and_x2", "global_atomic_or_x2", "global_atomic_xor_x2", + "global_atomic_inc_x2", "global_atomic_dec_x2", "global_atomic_fcmpswap_x2", "global_atomic_fmin_x2", + "global_atomic_fmax_x2", +}; + +constexpr const char* scratch_names[] = { + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "scratch_load_ubyte", "scratch_load_sbyte", "scratch_load_ushort", "scratch_load_sshort", + "scratch_load_dword", "scratch_load_dwordx2", "scratch_load_dwordx4", "scratch_load_dwordx3", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "scratch_store_byte", "scratch_store_byte_d16_hi", "scratch_store_short", "scratch_store_short_d16_hi", + "scratch_store_dword", "scratch_store_dwordx2", "scratch_store_dwordx4", "scratch_store_dwordx3", + "scratch_load_ubyte_d16", "scratch_load_ubyte_d16_hi", "scratch_load_sbyte_d16", "scratch_load_sbyte_d16_hi", + "scratch_load_short_d16", "scratch_load_short_d16_hi", +}; diff --git a/src/gfx1013_pixel.cpp b/src/gfx1013_pixel.cpp new file mode 100644 index 000000000..0dd516ceb --- /dev/null +++ b/src/gfx1013_pixel.cpp @@ -0,0 +1,96 @@ +#include "gfx1013_pixel.h" +#include +#include +#include +#include +#include +#include + +static std::array decode_color(std::string_view code) { + std::array, 256> vgpr{}; + size_t pc = 0; + auto word = [&]() { + if (code.size() - pc < 4) + throw std::runtime_error("truncated pixel program at " + std::to_string(pc)); + uint32_t value; + std::memcpy(&value, code.data() + pc, 4); + pc += 4; + return value; + }; + std::optional> result; + while (pc < code.size()) { + const auto address = pc; + const auto op = word(); + if (op == 0xbf810000 && result.has_value() && pc == code.size()) + return *result; + if (result.has_value()) + throw std::runtime_error("expected final s_endpgm at " + std::to_string(address)); + if ((op & 0xfe01fe00u) == 0x7e000200u) { + const auto src = op & 511; + auto &dst = vgpr[(op >> 17) & 255]; + if (src >= 256 && vgpr[src - 256]) + dst = vgpr[src - 256]; + else if (src == 255) + dst = word(); + else if (src >= 128 && src <= 192) + dst = src - 128; + else if (src >= 193 && src <= 208) + dst = 192u - src; + else if (src >= 240 && src <= 247) { + constexpr uint32_t floats[]{0x3f000000, 0xbf000000, 0x3f800000, 0xbf800000, + 0x40000000, 0xc0000000, 0x40800000, 0xc0800000}; + dst = floats[src - 240]; + } else + throw std::runtime_error("unresolved v_mov source at " + std::to_string(address)); + } else if (op == 0xf800180f) { + const auto sources = word(); + result.emplace(); + for (unsigned component = 0; component < 4; ++component) { + const auto &value = vgpr[(sources >> (component * 8)) & 255]; + if (!value) + throw std::runtime_error("uninitialized export VGPR at " + std::to_string(address)); + (*result)[component] = *value; + } + } else + throw std::runtime_error("unsupported pixel instruction at " + std::to_string(address)); + } + throw std::runtime_error("missing final MRT0 export or s_endpgm"); +} + +std::string x2w::translate_gfx1013_constant_pixel(std::string_view code) { + std::string out = "float4 main() : SV_Target0 { return asfloat(uint4("; + for (auto word : decode_color(code)) + out += std::to_string(word) + "u,"; + out.back() = ')'; + return out + "); }"; +} + +std::string x2w::direct_gfx1013_constant_pixel(std::string_view code) { + auto color = decode_color(code); + std::ostringstream out; + out << "target triple = \"dxil-ms-dx\"\ndefine void @main() {\n"; + for (unsigned c = 0; c < color.size(); ++c) + out << " call void @dx.op.storeOutput.f32(i32 5, i32 0, i32 0, i8 " << c << ", float bitcast (i32 " + << color[c] << " to float))\n"; + out << R"( ret void +} +declare void @dx.op.storeOutput.f32(i32,i32,i32,i8,float) nounwind +!llvm.ident = !{!0} +!dx.version = !{!1} +!dx.valver = !{!1} +!dx.shaderModel = !{!2} +!dx.viewIdState = !{!3} +!dx.entryPoints = !{!4} +!0 = !{!"x2w"} +!1 = !{i32 1, i32 0} +!2 = !{!"ps", i32 6, i32 0} +!3 = !{[2 x i32] [i32 0, i32 4]} +!4 = !{void ()* @main, !"main", !5, null, null} +!5 = !{null, !6, null} +!6 = !{!7} +!7 = !{i32 0, !"SV_Target", i8 9, i8 16, !8, i8 0, i32 1, i8 4, i32 0, i8 0, !9} +!8 = !{i32 0} +!9 = !{i32 3, i32 15} +)"; + return out.str(); +} diff --git a/src/gfx1013_pixel.h b/src/gfx1013_pixel.h new file mode 100644 index 000000000..c8c839752 --- /dev/null +++ b/src/gfx1013_pixel.h @@ -0,0 +1,10 @@ +#pragma once +#include +#include + +namespace x2w { +// Accepts a headerless, little-endian gfx1013 pixel program with one full, +// uncompressed float MRT0 export. Unknown instructions and entry VGPRs fail. +std::string direct_gfx1013_constant_pixel(std::string_view code); +std::string translate_gfx1013_constant_pixel(std::string_view code); +} // namespace x2w diff --git a/src/gfx1013_rect_geometry.cpp b/src/gfx1013_rect_geometry.cpp new file mode 100644 index 000000000..82429d4d6 --- /dev/null +++ b/src/gfx1013_rect_geometry.cpp @@ -0,0 +1,119 @@ +#include "dxil_module.h" +#include "gfx1013_compute_native.h" + +namespace x2w { +// Apply the startup rectangle rule (indexed_rect_geometry.h) to post-VS +// values. IA, base vertex, instance IDs and the original VS stay intact. +std::string native_rectangle_geometry(const std::vector &outputs, + const std::vector &pixel_inputs) { + using std::string; + using std::to_string; + if (std::any_of(pixel_inputs.begin(), pixel_inputs.end(), [](const auto &input) { return input.kind == 28; })) + throw UnsupportedComputeShader("numeric barycentrics on an expanded rectangle"); + struct Channel { + unsigned id, column, scalar; + bool floating, flat; + std::array vertex; + string a, b, fourth; + }; + DxilModule ir; + std::vector channels; + std::array, 3> position; + DxilModule::InputMask guard_inputs; + bool has_position = false; + for (const auto &r : outputs) { + const bool pos = r.kind == 3; + if (r.row >= 32 || !r.width || r.first + r.width > 4 || (!pos && r.kind != 0 && r.kind != 6 && r.kind != 7)) + throw UnsupportedComputeShader("unsupported rectangle stage interface"); + if (pos && (has_position || r.component != 9 || r.first || r.used != 15 || r.width != 4)) + throw UnsupportedComputeShader("rectangle requires a complete float4 position"); + has_position |= pos; + auto consumer = std::find_if(pixel_inputs.begin(), pixel_inputs.end(), + [&](const auto &p) { return p.name == r.name && p.index == r.index; }); + const bool flat = + !pos && (r.component != 9 || (consumer != pixel_inputs.end() && consumer->interpolation == 1)); + const unsigned id = static_cast(ir.inputs.size()); + ir.inputs.push_back({r.name, r.index, r.kind, r.component, r.row, r.first, r.width, r.interpolation, r.used}); + ir.outputs.push_back(ir.inputs.back()); + if (flat) + ir.outputs.back().interpolation = 1; + for (unsigned col = 0; col < r.width; ++col) { + if (!(r.used & (1u << col))) + continue; + Channel c{id, col, r.row * 4 + r.first + col, r.component == 9, flat}; + for (unsigned v = 0; v < (flat ? 1u : 3u); ++v) { + c.vertex[v] = + ir.invoke(c.floating ? "float" : "i32", c.floating ? "loadInput.f32" : "loadInput.i32", 4, + {{"i32", to_string(id)}, {"i32", "0"}, {"i8", to_string(col)}, {"i32", to_string(v)}}, + "nounwind readnone"); + if (pos) + position[v][col] = c.vertex[v]; + } + if (pos) + guard_inputs.set(c.scalar); + channels.push_back(std::move(c)); + } + } + if (!has_position) + throw UnsupportedComputeShader("rectangle requires a position"); + auto both = [&](const string &a, const string &b) { return ir.value("and i1 " + a + ", " + b); }; + auto either = [&](const string &a, const string &b) { return ir.value("or i1 " + a + ", " + b); }; + auto compare = [&](const char *relation, const string &a, const string &b) { + return ir.value("fcmp " + string(relation) + " float " + a + ", " + b); + }; + auto finite = [&](const string &v) { + return ir.invoke("i1", "isSpecialFloat.f32", 10, {{"float", v}}, "nounwind readnone"); + }; + string valid = compare("ogt", position[0][3], "0.000000e+00"); + for (unsigned i = 0; i < 3; ++i) { + for (const auto &v : position[i]) + valid = both(valid, finite(v)); + if (i) + valid = both(valid, compare("oeq", position[0][3], position[i][3])); + } + std::array corner; + for (unsigned i = 0; i < 3; ++i) { + auto &p = position[i], &a = position[(i + 1) % 3], &b = position[(i + 2) % 3]; + auto x = compare("oeq", p[0], a[0]), y = compare("oeq", p[1], b[1]); + auto other_x = compare("oeq", p[0], b[0]), other_y = compare("oeq", p[1], a[1]); + corner[i] = both(either(both(x, y), both(other_x, other_y)), + both(compare("one", a[0], b[0]), compare("one", a[1], b[1]))); + } + valid = both(valid, either(corner[0], either(corner[1], corner[2]))); + // Only a non-degenerate rectangle has a unique matching corner. + for (auto &c : channels) { + if (c.flat) + continue; + auto rotate = [&](unsigned n) { + auto rest = ir.value("select i1 " + corner[1] + ", float " + c.vertex[(n + 1) % 3] + ", float " + + c.vertex[(n + 2) % 3]); + return ir.value("select i1 " + corner[0] + ", float " + c.vertex[n] + ", float " + rest); + }; + c.a = rotate(1); + c.b = rotate(2); + auto sum = ir.value("fadd float " + c.a + ", " + c.b); + c.fourth = ir.value("fsub float " + sum + ", " + rotate(0)); + if (ir.outputs[c.id].kind == 3) + valid = both(valid, finite(c.fourth)); + } + ir.body << " br i1 " << valid << ", label %draw, label %done\ndraw:\n"; + for (unsigned v = 0; v < 6; ++v) { + for (const auto &c : channels) { + const auto &value = c.flat ? c.vertex[0] : v < 3 ? c.vertex[v] : v == 3 ? c.a : v == 4 ? c.fourth : c.b; + ir.invoke("void", c.floating ? "storeOutput.f32" : "storeOutput.i32", 5, + {{"i32", to_string(c.id)}, + {"i32", "0"}, + {"i8", to_string(c.column)}, + {c.floating ? "float" : "i32", value}}, + "nounwind"); + ir.output_dependencies[c.scalar] = guard_inputs; + ir.output_dependencies[c.scalar].set(c.scalar); + } + ir.invoke("void", "emitStream", 97, {{"i8", "0"}}, "nounwind"); + if (v == 2 || v == 5) + ir.invoke("void", "cutStream", 98, {{"i8", "0"}}, "nounwind"); + } + ir.body << " br label %done\ndone:\n ret void\n"; + return ir.finish_compute(0, 0, 0, "gs"); +} +} // namespace x2w diff --git a/src/gfx1013_sampled_pixel.cpp b/src/gfx1013_sampled_pixel.cpp new file mode 100644 index 000000000..ff3d8ac4c --- /dev/null +++ b/src/gfx1013_sampled_pixel.cpp @@ -0,0 +1,289 @@ +#include "gfx1013_sampled_pixel.h" +#include +#include +#include +#include +#include +#include +#include + +namespace { +using Word = uint32_t; +using std::string; +enum class Type { undefined, constant, table, descriptor_word, value, primitive_mask }; +struct Scalar { + Type type{}; + Word number{}, offset{}; + string value; +}; +struct Vector { + string value; + std::array halves{}; + int interpolation = -1; +}; +struct Binding { + Word table, offset; + bool texture; +}; + +class PixelProgram { + std::string_view code; + size_t pc{}, start{}; + std::optional instruction_literal; + unsigned temporary{}; + std::array scalars{}; + std::array vectors{}; + std::vector resources; + std::vector> samplers; + bool primitive_mask=false; + std::array exported{}; + bool done=false; + string declarations, body, bindings; + + [[noreturn]] void fail(const char* why) const { + throw std::runtime_error(string(why)+" at pixel byte "+std::to_string(start)); + } + void require(bool ok,const char* why) const { if(!ok) fail(why); } + Word word() { + require(code.size()-pc>=4,"truncated instruction"); + Word v; std::memcpy(&v,code.data()+pc,4); pc+=4; return v; + } + string symbol(const char* type,const string& expression) { + auto name="p"+std::to_string(temporary++); + body+=" "+string(type)+" "+name+" = "+expression+";\n"; + return name; + } + Scalar source(Word index) { + if(index=128 && index<=192) bits=index-128; + else if(index>=193 && index<=208) bits=192u-index; + else if(index>=240 && index<=247) { + constexpr Word floats[]{0x3f000000,0xbf000000,0x3f800000,0xbf800000,0x40000000,0xc0000000,0x40800000,0xc0800000}; + bits=floats[index-240]; + } else if(index==255) { + // Every literal selector in the instruction names the same trailing dword. + if(!instruction_literal) instruction_literal=word(); + bits=*instruction_literal; + } + else fail("unsupported scalar operand"); + return {Type::constant,bits}; + } + static string literal(Word bits) {return std::to_string(bits)+"u";} + string as_float(Word index) { + if(index>=256) { + const auto& v=vectors[index-256]; + require(!v.value.empty(),"undefined float VGPR"); + return v.value; + } + auto s=source(index); + if(s.type==Type::value) return "asfloat("+s.value+")"; + require(s.type==Type::constant,"expected float operand"); + return "asfloat("+literal(s.number)+")"; + } + void put(Word reg,const string& expr) { + vectors[reg]=Vector{symbol("float",expr)}; + } + string resource(Word base,unsigned words,bool texture) { + require(base+words<=scalars.size(),"invalid descriptor SGPR range"); + auto first=scalars[base]; + require(first.type==Type::descriptor_word && first.offset%32==0,"unresolved descriptor base"); + for(unsigned i=1;i":"ByteAddressBuffer")+string(" r")+n+" : register(t"+n+");\n"; + bindings+="srv "+n+(texture?" tex2d table ":" buf table ")+std::to_string(first.number)+" "+std::to_string(first.offset)+"\n"; + resources.push_back({first.number,first.offset,texture}); + return "r"+n; + } + std::array sampler_words(Word base) { + require(base+4<=scalars.size(),"invalid sampler SGPR range"); + std::array bits{}; + for(unsigned i=0;i<4;++i) { + require(scalars[base+i].type==Type::constant,"unresolved sampler"); + bits[i]=scalars[base+i].number; + } + return bits; + } + string sampler(const std::array& bits) { + unsigned i=0; + for(const auto& s:samplers) {if(s==bits) return "q"+std::to_string(i); ++i;} + auto n=std::to_string(i); + declarations+="SamplerState q"+n+" : register(s"+n+");\n"; + bindings+="sampler "+n; + for(auto b:bits) bindings+=" "+std::to_string(b); + bindings+="\n"; + samplers.push_back(bits); + return "q"+n; + } + void scalar_load(Word op) { + auto base=(op&63)*2, dst=(op>>6)&127; + auto imm=word(); + require((imm&0xfff00000)==0xfa000000,"unsupported scalar byte offset"); + unsigned off=imm&0xfffff; + if((op&~0x1fffu)==0xf4240000) { + require(dst+2<=scalars.size() && off%4==0,"invalid buffer load"); + auto r=resource(base,4,false); + for(unsigned i=0;i<2;++i) + scalars[dst+i]={Type::value,0,0,symbol("uint",r+".Load("+literal(off+4*i)+")")}; + return; + } + unsigned count=(op&~0x1fffu)==0xf4080000 ? 4 : 16; + require(base+1>8)&255, mask=(op>>8)&15; + require(!(args&0xfc000000) && mask && addr<255,"invalid image_sample_lz"); + auto r=resource(((args>>16)&31)*4,8,true); + auto bits=sampler_words(((args>>21)&31)*4); + const bool implicit = (op & 0xfffff0ff) == 0xf0800008; + const int bias = int((bits[2] & 0x3fff) ^ 0x2000) - 0x2000; + const unsigned mip_filter = (bits[2] >> 26) & 3; + require(!(bits[2] & 0xfc000), "unsupported secondary sampler bias"); + require(!implicit || mip_filter == 1 || mip_filter == 2, "unsupported implicit mip filter"); + // The primary s6.8 field must fit the desktop SampleBias range [-16, 15.99]. + require(!bias || (implicit && bias >= -4096 && bias <= 4093), + "unsupported primary sampler bias"); + require((bits[1]&0xfff) <= ((bits[1]>>12)&0xfff), "inverted sampler LOD limits"); + bits[2] &= ~0x3fffu; + auto q=sampler(bits); + auto uv="float2("+as_float(256+addr)+","+as_float(257+addr)+")"; + string call; + if (bias) call=r+".SampleBias("+q+","+uv+","+std::to_string(bias)+".0/256.0)"; + else if (implicit) call=r+".Sample("+q+","+uv+")"; + else call=r+".SampleLevel("+q+","+uv+",0)"; + auto value=symbol("float4",call); + for(unsigned bit=0;bit<4;++bit) if(mask&(1u<>4)&63; + require(mrt<2 && !exported[mrt],"unexpected render target export"); + require((op&15)==(mrt?3u:15u) && (args&0xffff0000)==0x80800000,"unsupported compressed export mask"); + unsigned channels=mrt?1:3; + string value; + for(unsigned i=0;i>(8*(i/2)))&255]; + auto half=v.halves[i%2]; + require(!half.empty(),"undefined live render target channel"); + if(i) value+=","; + value+="f16tof32("+half+")"; + } + body+=" o.c"+std::to_string(mrt)+" = "+(mrt?value:"float3("+value+")")+";\n"; + exported[mrt]=true; + done=(op&0x800)!=0; + } + void instruction(Word op) { + auto dst=(op>>16)&127; + if((op>>16)==0xbfa0 || (op>>16)==0xbfa1 || (op>>16)==0xbf8c) return; // prefetch, clause and waitcnt + if((op&0xff80ff00)==0xbe800300 || (op&0xff80ff00)==0xbe800400) { + auto s=source(op&255); + if(dst==124) { + require(((op>>8)&255)==3 && s.type==Type::primitive_mask,"unsupported m0 write"); + primitive_mask=true;return; + } + require(dst>8)&255)==4) { + const unsigned selector=op&255; + require(dst+1>31)) { + scalars[dst+1]={Type::constant,0}; + } else { + require(selector>=128 && selector<=208,"unsupported 64-bit scalar constant"); + scalars[dst+1]={Type::constant,selector<=192?0u:0xffffffffu}; + } + } + scalars[dst]=s; + } else if((op&0xff800000)==0xb0000000) { + require(dst(static_cast(op))}; + } else if((op&0xff800000)==0x92000000 || (op&0xff800000)==0x92800000) { + auto a=source(op&255),b=source((op>>8)&255); + require(dst(mask)}; + scalars[dst+1]={Type::constant,static_cast(mask>>32)}; + } else scalars[dst]={Type::constant,((1u<<(a.number&31))-1)<<(b.number&31)}; + } else if((op&~0x1fffu)==0xf4080000 || (op&~0x1fffu)==0xf4100000 || (op&~0x1fffu)==0xf4240000) { + scalar_load(op); + } else if((op&0xfc000000)==0xc8000000) { + unsigned d=(op>>18)&255, attr=(op>>10)&63, component=(op>>8)&3, phase=(op>>16)&3; + require(primitive_mask && attr==0 && phase<2 && (op&255)==phase,"unsupported interpolation interface"); + require(vectors[phase].value.empty() && vectors[phase].interpolation==-1 && + vectors[phase].halves[0].empty() && vectors[phase].halves[1].empty(),"overwritten IJ input"); + if(!phase) { vectors[d]={}; vectors[d].interpolation=component; } + else { + require(vectors[d].interpolation==int(component),"interpolation phase mismatch"); + put(d,"param0."+string(1,"xyzw"[component])); + } + } else if((op&0xfffff0ff)==0xf09c0008 || (op&0xfffff0ff)==0xf0800008) { + sample(op); + } else if((op&0xffffff00)==0xd54b0000 || (op&0xffffff00)==0xcc214000 || (op&0xffffff00)==0xcc224000) { + auto args=word(), d=op&255; + auto a=as_float(args&511), b=as_float((args>>9)&511); + if((op>>16)==0xd54b) { + require(!(args&0xf8000000),"unsupported FMA modifiers"); + auto c=as_float((args>>18)&511); + put(d,"mad("+a+","+b+","+c+")"); + } else { + require((args&0xfffc0000)==0x82000000,"expected negated zero half addend"); + unsigned half=(op>>16)==0xcc22; + auto& v=vectors[d]; + if(!v.value.empty()) { + v.halves[0]="(asuint("+v.value+") & 65535u)"; + v.halves[1]="(asuint("+v.value+") >> 16)"; + } + v.value.clear();v.interpolation=-1; + v.halves[half]=symbol("uint","f32tof16(mad("+a+","+b+",asfloat(0x80000000u)))"); + } + } else if(op>>25==3 || op>>25==5 || op>>25==43) { + auto d=(op>>17)&255; + auto a=as_float(op&511), b=as_float(256+((op>>9)&255)); + if(op>>25==43) put(d,"mad("+a+","+b+","+as_float(256+d)+")"); + else put(d,op>>25==3?a+"+"+b:b+"-"+a); + } else if(op==0xf800040f || op==0xf8001c13) export_mrt(op); + else fail("unsupported sampled pixel instruction"); + } +public: + explicit PixelProgram(std::string_view bytes) : code(bytes) {} + x2w::SampledPixel translate() { + scalars[8]={Type::table,0};scalars[9]={Type::table,1};scalars[10]={Type::primitive_mask}; + while(pc +#include + +namespace x2w { +struct SampledPixel { + std::string hlsl; + std::string bindings; +}; + +// Straight-line pixel programs with two entry descriptor tables (s8/s9), +// primitive mask in s10, perspective-center IJ in v0/v1, attr0 -> PARAM0, +// and R11G11B10_FLOAT/R16_FLOAT targets. The caller verifies this interface. +// code spans the instructions from entry through s_endpgm, without padding. +SampledPixel translate_gfx1013_sampled_pixel(std::string_view code); +} diff --git a/src/gfx1013_vertex_id.cpp b/src/gfx1013_vertex_id.cpp new file mode 100644 index 000000000..d8ed79ffb --- /dev/null +++ b/src/gfx1013_vertex_id.cpp @@ -0,0 +1,290 @@ +#include "gfx1013_vertex_id.h" +#include +#include +#include +#include +#include +#include + +namespace { +using Word = std::uint32_t; + +class VertexProgram { + std::string_view code; + std::size_t pc = 0, address = 0; + std::array values; + std::optional literal; + bool position = false; + std::array parameters{}; + const bool buffered; + enum class Kind { undefined, value, table, vb_table, vb_tagged_high, vb_high, zero_high, desc }; + struct Scalar { + Kind kind{}; + int table{}; + unsigned offset{}; + std::string value; + }; + std::array scalars{}; + std::vector> buffers; + std::string declarations, bindings; + unsigned next = 0; + std::string body; + + [[noreturn]] void fail(const char *reason) const { + throw std::runtime_error(std::string(reason) + " at vertex byte " + std::to_string(address)); + } + Word read() { + if (code.size() - pc < sizeof(Word)) fail("truncated instruction"); + Word result; + std::memcpy(&result, code.data() + pc, sizeof(result)); + pc += sizeof(result); + return result; + } + std::string operand(Word selector) { + if (selector >= 256) { + const auto &value = values[selector - 256]; + if (value.empty()) fail("undefined VGPR"); + return value; + } + if (buffered && selector < scalars.size()) { + if (scalars[selector].kind == Kind::zero_high) return "0u"; + if (scalars[selector].kind != Kind::value) fail("unresolved scalar input"); + return scalars[selector].value; + } + Word bits = 0; + if (selector >= 128 && selector <= 192) + bits = selector - 128; + else if (selector >= 193 && selector <= 208) + bits = 192u - selector; + else if (selector >= 240 && selector <= 247) { + constexpr Word constants[]{0x3f000000, 0xbf000000, 0x3f800000, 0xbf800000, + 0x40000000, 0xc0000000, 0x40800000, 0xc0800000}; + bits = constants[selector - 240]; + } else if (selector == 255) { + if (!literal) literal = read(); + bits = *literal; + } else + fail("unsupported input selector"); + return std::to_string(bits) + "u"; + } + std::string temporary(const std::string &expression) { + auto name = "r" + std::to_string(next++); + body += " uint " + name + " = " + expression + ";\n"; + return name; + } + void assign(Word reg, const std::string &expression) { values[reg] = temporary(expression); } + std::string buffer(Word base, bool vertex) { + if (base + 4 > scalars.size()) fail("invalid buffer descriptor range"); + const auto &first = scalars[base]; + if (first.kind != Kind::desc || (first.table < 0) != vertex) fail("unexpected buffer descriptor"); + for (unsigned i = 1; i < 4; ++i) { + const auto &part = scalars[base + i]; + if (part.kind != Kind::desc || part.table != first.table || part.offset != first.offset + 4 * i) + fail("overwritten buffer descriptor"); + } + const auto id = std::make_pair(first.table, first.offset); + unsigned reg = 0; + for (const auto &entry : buffers) { + if (entry == id) break; + ++reg; + } + const auto number = std::to_string(reg); + if (reg == buffers.size()) { + buffers.push_back(id); + declarations += "ByteAddressBuffer b" + number + " : register(t" + number + ");\n"; + bindings += + "srv " + number + " buf " + + (vertex ? "vb 0" : "table " + std::to_string(first.table) + " " + std::to_string(first.offset)) + + "\n"; + } + return "b" + number; + } + void scalar_load(Word op) { + const Word base = (op & 63) * 2, dest = (op >> 6) & 127, offset_word = read(); + if ((offset_word & 0xfff00003) != 0xfa000000) fail("unsupported scalar load offset"); + const Word offset = offset_word & 0xfffff; + const auto opcode = op & ~0x1fffu; + const unsigned count = opcode == 0xf4300000 ? 16 : 4; + if (base + 1 >= scalars.size() || dest + count > scalars.size()) fail("scalar load register range"); + if (opcode == 0xf4080000) { + const auto pointer = scalars[base]; + const auto high = scalars[base + 1].kind; + if (pointer.kind == Kind::vb_table) { + if (offset || high != Kind::vb_high) fail("expected vertex stream zero"); + } else if (pointer.kind != Kind::table || high != Kind::zero_high || offset % 32) + fail("unresolved root table"); + for (unsigned i = 0; i < count; ++i) + scalars[dest + i] = {Kind::desc, pointer.table, offset + 4 * i}; + } else { + const auto resource = buffer(base, false); + for (unsigned i = 0; i < count; ++i) + scalars[dest + i] = {Kind::value, 0, 0, + temporary(resource + ".Load(" + std::to_string(offset + 4 * i) + "u)")}; + } + } + void load_vertex(Word op) { + const auto args = read(); + if ((args & 0xffe00000) != 0x80000000) fail("unsupported vertex load operands"); + const auto resource = buffer(((args >> 16) & 31) * 4, true); + const unsigned count = (op & 0xfffff000) == 0xe03c2000 ? 3 : 2; + const unsigned dest = (args >> 8) & 255; + if (dest + count > values.size()) fail("vertex load destination range"); + const auto address = + temporary(operand(256 + (args & 255)) + " * ud3 + " + std::to_string(op & 4095) + "u"); + for (unsigned i = 0; i < count; ++i) + assign(dest + i, resource + ".Load(" + address + "+" + std::to_string(4 * i) + "u)"); + } + bool buffer_instruction(Word op) { + const auto dest = (op >> 16) & 127, src = op & 255; + if ((op & 0xff80ff00) == 0xbe800300 || (op & 0xff80ff00) == 0xbe800400) { + if (dest >= scalars.size()) fail("invalid scalar destination"); + if (((op >> 8) & 255) == 4) { + if (dest + 1 >= scalars.size() || src + 1 >= scalars.size() || src % 2 || dest % 2 || + scalars[src].kind == Kind::undefined || scalars[src + 1].kind == Kind::undefined) + fail("unsupported scalar pair"); + const auto low = scalars[src], high = scalars[src + 1]; + scalars[dest] = low; + scalars[dest + 1] = high; + } else if (src == 128) + scalars[dest] = {Kind::zero_high}; + else if (src < scalars.size() && scalars[src].kind != Kind::undefined) + scalars[dest] = scalars[src]; + else + fail("unsupported scalar move"); + } else if ((op & 0xff80ff00) == 0x9380ff00) { + if (read() != 0x80000 || dest >= scalars.size() || src >= scalars.size() || + scalars[src].kind != Kind::vb_tagged_high) + fail("unsupported vertex address high word"); + scalars[dest] = {Kind::vb_high}; + } else if ((op & ~0x1fffu) == 0xf4080000 || (op & ~0x1fffu) == 0xf4280000 || + (op & ~0x1fffu) == 0xf4300000) { + scalar_load(op); + } else if ((op & 0xfffff000) == 0xe03c2000 || (op & 0xfffff000) == 0xe0342000) { + load_vertex(op); + } else if ((op & 0xfe01fe00) == 0x7e005c00) { + assign((op >> 17) & 255, "asuint(rsqrt(asfloat(" + operand(op & 511) + ")))"); + } else if ((op & 0xffffff00) == 0xd5030000) { + const auto args = read(); + if (args & 0x9ffc0000) fail("unsupported add modifiers"); + const auto a = operand(args & 511), b = operand((args >> 9) & 511); + assign(op & 255, std::string("asuint(") + ((args >> 29) & 1 ? "-" : "") + "asfloat(" + a + ") + " + + ((args >> 30) & 1 ? "-" : "") + "asfloat(" + b + "))"); + } else if (op >> 25 == 3 || op >> 25 == 4 || op >> 25 == 5 || op >> 25 == 8 || op >> 25 == 37 || + op >> 25 == 43) { + const auto d = (op >> 17) & 255; + auto a = operand(op & 511), b = operand(256 + ((op >> 9) & 255)); + if (op >> 25 == 37) + assign(d, a + " + " + b); + else { + a = "asfloat(" + a + ")"; + b = "asfloat(" + b + ")"; + if (op >> 25 == 5) std::swap(a, b); + const auto value = op >> 25 == 43 ? "mad(" + a + "," + b + ",asfloat(" + operand(256 + d) + "))" + : a + + (op >> 25 == 8 ? " * " + : op >> 25 == 3 ? " + " + : " - ") + + b; + assign(d, "asuint(" + value + ")"); + } + } else + return (op >> 16) == 0xbfa1 || (op >> 16) == 0xbf8c; // clause and waitcnt + return true; + } + void export_value(bool pos, Word mask, unsigned param = 0) { + if (pos ? position : parameters[param]) fail("duplicate vertex export"); + const Word sources = read(); + std::string vector; + for (unsigned i = 0; i < 4; ++i) { + if (i) vector += ", "; + const Word reg = (sources >> (8 * i)) & 255; + if (mask & (1u << i)) + vector += "asfloat(" + operand(256 + reg) + ")"; + else { + if (reg != 128) fail("unexpected disabled export operand"); + vector += "0.0"; + } + } + body += (pos ? " o.pos" : " o.param" + std::to_string(param)) + " = float4(" + vector + ");\n"; + (pos ? position : parameters[param]) = true; + } + + public: + VertexProgram(std::string_view bytes, bool uses_buffers) : code(bytes), buffered(uses_buffers) { + values[0] = "vid"; + scalars[0] = {Kind::vb_table, -1}; + scalars[1] = {Kind::vb_tagged_high}; + scalars[2] = {Kind::value, 0, 0, "ud1"}; + scalars[8] = {Kind::table, 0}; + scalars[9] = {Kind::table, 1}; + } + x2w::BufferedVertex translate() { + while (pc < code.size()) { + address = pc; + literal.reset(); + const auto op = read(); + if (op == 0xbf810000) { + if (!position || !parameters[0] || pc != code.size()) + fail("incomplete exports or trailing instructions"); + const std::string param1 = parameters[1] ? "float4 param1 : PARAM1; " : ""; + return {declarations + "cbuffer entry : register(b0) { uint ud0; uint ud1; uint ud2; " + + (buffered ? "uint ud3; " : "") + "};\nstruct Out { float4 param0 : PARAM0; " + param1 + + "float4 pos : SV_Position; };\nOut vertex(uint vid) {\n Out o;\n" + body + + R"( return o; +} +Out main(uint vid : SV_VertexID) { + if (!ud0) return vertex(vid); + uint first = (vid / 6) * 3, corner = vid % 6; + if (corner < 3) return vertex(first + corner); + if (corner == 3) return vertex(first); + if (corner == 4) return vertex(first + 2); + Out a = vertex(first), b = vertex(first + 1), c = vertex(first + 2), o; + o.pos = a.pos + c.pos - b.pos; + o.param0 = a.param0 + c.param0 - b.param0; +)" + (parameters[1] ? " o.param1 = a.param1 + c.param1 - b.param1;\n" : "") + + R"( return o; +} +)", + bindings}; + } + if ((op >> 16) == 0xbfa0 || (op & ~3u) == 0xbf8f0000) continue; // prefetch and priority + if (buffered && buffer_instruction(op)) continue; + if ((op & 0xfe01fe00) == 0x7e000200 || (op & 0xfe01fe00) == 0x7e000a00) { + auto value = operand(op & 511); + if ((op & 0x1fe00) == 0xa00) value = "asuint(float(asint(" + value + ")))"; + assign((op >> 17) & 255, value); + } else if (op >> 25 == 26 || op >> 25 == 27) { + auto a = operand(op & 511); + auto b = operand(256 + ((op >> 9) & 255)); + assign((op >> 17) & 255, op >> 25 == 26 ? b + " << (" + a + " & 31u)" : a + " & " + b); + } else if ((op & 0xffffff00) == 0xd54b0000) { + const auto args = read(); + if (args & (buffered ? 0x18000000u : 0xf8000000u)) fail("unsupported FMA modifiers"); + auto a = operand(args & 511); + auto b = operand((args >> 9) & 511); + auto c = operand((args >> 18) & 511); + const auto f = [&](const std::string &v, unsigned bit) { + return ((args >> bit) & 1 ? "-asfloat(" : "asfloat(") + v + ")"; + }; + assign(op & 255, "asuint(mad(" + f(a, 29) + ", " + f(b, 30) + ", " + f(c, 31) + "))"); + } else if (op == 0xf80008cf) { + export_value(true, 15); + } else if ((op & ~15u) == 0xf8000200 && (op & 15)) { + export_value(false, op & 15); + } else if (buffered && (op & ~15u) == 0xf8000210 && (op & 15)) { + export_value(false, op & 15, 1); + } else + fail("unsupported vertex instruction"); + } + fail("missing endpgm"); + } +}; +} // namespace + +std::string x2w::translate_gfx1013_vertex_id(std::string_view code) { + return VertexProgram(code, false).translate().hlsl; +} + +x2w::BufferedVertex x2w::translate_gfx1013_buffered_vertex(std::string_view code) { + return VertexProgram(code, true).translate(); +} diff --git a/src/gfx1013_vertex_id.h b/src/gfx1013_vertex_id.h new file mode 100644 index 000000000..21c1b961c --- /dev/null +++ b/src/gfx1013_vertex_id.h @@ -0,0 +1,17 @@ +#pragma once +#include +#include + +namespace x2w { +// Raw straight-line vertex entry with SV_VertexID in v0, POS0 and PARAM0. +// Root constant b0.x selects the runtime's rectangle-list expansion. +std::string translate_gfx1013_vertex_id(std::string_view code); + +struct BufferedVertex { + std::string hlsl; + std::string bindings; +}; +// Vertex-buffer table in s[0:1], base vertex in s2, root tables in s8/s9. +// One indexed raw vertex stream, float PARAM0/1, no input-layout fetch routine. +BufferedVertex translate_gfx1013_buffered_vertex(std::string_view code); +} diff --git a/src/guest_shader_container.cpp b/src/guest_shader_container.cpp new file mode 100644 index 000000000..2cb15f274 --- /dev/null +++ b/src/guest_shader_container.cpp @@ -0,0 +1,215 @@ +#include "guest_shader_container.h" +#include "startup_stubs/inflate.h" +#include +#include + +// Xbox DXIL/XDAT, XBCH and FSSM record fields follow the native-stage layout +// documented in victory-shader native.rs at 9376fd6. The parser and bounds +// checks below are independently implemented using the repository's inflater. +namespace x2w { +namespace { +using Span = std::string_view; +Span slice(Span data, uint64_t offset, uint64_t size) { + if (offset > data.size() || size > data.size() - offset) + throw std::runtime_error("shader record outside its parent"); + return data.substr(static_cast(offset), static_cast(size)); +} +template T le(Span data, uint64_t offset) { + T v; + std::memcpy(&v, slice(data, offset, sizeof v).data(), sizeof v); + return v; +} +uint32_t u32(Span s, uint64_t off) { return le(s, off); } +uint64_t u64(Span s, uint64_t off) { return le(s, off); } +std::vector read_signature(Span part, bool extended) { + std::vector result; + auto count = u32(part, 0); + if (count > 128) + throw std::runtime_error("invalid signature element count"); + const unsigned stride = extended ? 32 : 24; + auto rows = slice(part, u32(part, 4), size_t(count) * stride); + for (unsigned i = 0; i < count; ++i) { + auto row = rows.substr(i * stride, stride); + if (extended && u32(row, 0) != 0) + throw std::runtime_error("unsupported signature stream"); + if (extended) + row.remove_prefix(4); + auto start = u32(row, 0); + auto end = part.find(char(0), start); + if (end == Span::npos || end == start || end - start > 255) + throw std::runtime_error("invalid shader semantic name"); + auto name = part.substr(start, end - start); + result.push_back({std::string(name), u32(row, 4), u32(row, 8), u32(row, 12), u32(row, 16), uint8_t(row[20]), + uint8_t(row[21])}); + } + return result; +} +void graphics_io(GuestShaderStage &stage, Span io) { + const bool pixel = stage.stage == GpuStage::ps; + auto attributes = [&](unsigned offset, unsigned size, unsigned count_at, bool output) { + auto count = u32(io, count_at); + if (count > 32) + throw std::runtime_error("too many native shader attributes"); + auto records = slice(io, offset, uint64_t(count) * size); + for (unsigned n = 0; n < count; ++n) { + auto e = records.substr(n * size, size); + ShaderAttribute a{}; + a.usage = uint8_t(e[0]); + a.row = uint8_t(e[1]); + if (output) { + a.location = uint8_t(e[2]); + a.flags = uint8_t(e[5]); + } else { + a.mask = uint8_t(e[2]) & 15; + a.location = uint8_t(e[3]); + if (pixel) { + a.second_row = uint8_t(e[5]); + a.flags = uint8_t(e[7]); + } else a.last_component = uint8_t(e[4]); + } + (output ? stage.outputs : stage.attributes).push_back(a); + } + }; + if (pixel) { + attributes(0x24, 8, 0x124, false); + stage.pixel_input_address = u32(io, 0x134); + stage.depth_control = u32(io, 0x138); + unsigned words = u32(io, 0x148); + if (words > 10) + throw std::runtime_error("invalid pixel export patch size"); + for (unsigned mrt = 0; mrt < 8; ++mrt) { + unsigned at = 0x14c + mrt * 404, where = u32(io, at); + if (where == UINT32_MAX) + continue; + slice(stage.code, uint64_t(where) * 4, 4 * words); + for (const auto &other : stage.exports) + if (words && uint64_t(where) < other.word_offset + other.full_precision.size() / 4 && + uint64_t(other.word_offset) < uint64_t(where) + words) + throw std::runtime_error("overlapping pixel export patches"); + stage.exports.push_back({mrt, where, std::string(slice(io, at + 4 + 360, 4 * words))}); + } + } else { + attributes(0x24, 5, 0xc4, false); + attributes(0xc8, 6, 0x188, true); + if (stage.stage == GpuStage::ms) { + stage.mesh_clip_control = u32(io, 0x194); + stage.threads[0] = le(io, 0x448); + stage.max_vertices = le(io, 0x44a); + stage.max_primitives = le(io, 0x44c); + stage.topology = le(io, 0x44f); + } + } +} +void stages(Span packed, std::vector &result, size_t &total) { + if (slice(packed, 0, 4) != "XBCH" || u32(packed, 4) != 3) + throw std::runtime_error("unsupported native blob version"); + auto payload = slice(packed, 24, u64(packed, 8)); + auto size = u64(packed, 16); + if (size < 16 || size > 16u << 20 || total + size > 64u << 20) + throw std::runtime_error("native stage size out of range"); + total += static_cast(size); + std::string inflated(static_cast(size), 0); + size_t produced = 0; + if (!x2w_inflate::inflate_zlib(reinterpret_cast(payload.data()), payload.size(), + reinterpret_cast(inflated.data()), inflated.size(), + &produced) || + produced != size) + throw std::runtime_error("native stage inflation failed"); + if (slice(inflated, 0, 4) != "FSSM" || u32(inflated, 4) != 0x101 || u64(inflated, 8) != size - 16) + throw std::runtime_error("invalid FSSM header"); + auto body = slice(inflated, 16, size - 16); + if (u64(body, 0) != 6) + throw std::runtime_error("unknown FSSM slot layout"); + constexpr unsigned offsets[]{8, 16, 24, 32, 40, 48, 72, 96}; + for (unsigned i = 0; i < 8; ++i) { + auto off = u64(body, offsets[i]); + if (off == 0xdeadbeefdeadbeefull) + continue; + auto record = slice(body, off, 84); + GuestShaderStage stage{}; + stage.stage = static_cast(i); + stage.wave32 = (u32(record, 20) & 32) != 0; + stage.vgprs = u32(record, 80) & 1023; + stage.lds_bytes = u32(record, 76); + if (stage.vgprs > 256) + throw std::runtime_error("invalid native register count"); + auto code = slice(body, u64(record, 0), u64(record, 8)); + if (code.size() > 1u << 20) + throw std::runtime_error("native instruction stream too large"); + stage.code = code; + if (stage.code.empty() || stage.code.size() % 4) + throw std::runtime_error("invalid native code size"); + for (unsigned t = 0; t < 2; ++t) { + auto count = u32(record, 56 + t * 4); + if (!count) + continue; + if (count > 65536) + throw std::runtime_error("native resource layout too large"); + auto entries = slice(body, u64(record, 40 + t * 8), uint64_t(count) * 20); + for (unsigned j = 0; j < count; ++j) { + auto e = entries.substr(20ull * j, 20); + if (t == 0) + stage.inputs.push_back( + {u32(e, 0), u32(e, 4), u32(e, 8), u32(e, 12), uint8_t(e[16]), uint8_t(e[17])}); + else + stage.resources.push_back({uint8_t(e[0]), uint8_t(e[1]), u32(e, 4), u32(e, 8), u32(e, 12), + uint8_t(e[16]), uint8_t(e[17]), uint8_t(e[18])}); + } + } + if (stage.stage == GpuStage::cs) { + auto io = slice(body, off + 84 + 36, 16); + stage.rsrc2 = u32(io, 0); + for (unsigned j = 0; j < 3; ++j) + stage.threads[j] = u32(io, 4 + j * 4); + } + if (stage.stage == GpuStage::vs || stage.stage == GpuStage::ms || stage.stage == GpuStage::ps) + graphics_io(stage, body.substr(static_cast(off) + 84)); + result.push_back(std::move(stage)); + } +} +} // namespace +std::string GuestShaderStage::full_precision_code() const { + auto patched = code; + for (const auto &p : exports) + patched.replace(size_t(p.word_offset) * 4, p.full_precision.size(), p.full_precision); + return patched; +} +std::vector read_guest_shader_container(std::string_view bytes) { + if (slice(bytes, 0, 4) != "DXBC" || u32(bytes, 24) != bytes.size()) + throw std::runtime_error("invalid DXBC length"); + std::vector result; + size_t total = 0; + std::vector inputs, outputs; + const auto count = u32(bytes, 28); + if (count > 4096) + throw std::runtime_error("invalid DXBC part count"); + auto offsets = slice(bytes, 32, 4ull * count); + for (unsigned i = 0; i < count; ++i) { + uint64_t part = u32(offsets, 4ull * i); + auto data = slice(bytes, part + 8, u32(bytes, part + 4)); + auto kind = slice(bytes, part, 4); + if (kind == "ISG1" || kind == "ISGN") + inputs = read_signature(data, kind == "ISG1"); + if (kind == "OSG1" || kind == "OSGN") + outputs = read_signature(data, kind == "OSG1"); + if (kind != "DXIL" || data.size() < 36 || data.substr(24, 4) != "XDAT") + continue; + auto n = u32(data, 28); + if (n > 64) + throw std::runtime_error("invalid XDAT entry count"); + auto entries = slice(data, 36, 12ull * n); + for (unsigned j = 0; j < n; ++j) { + auto row = entries.substr(12ull * j, 12); + auto chunk = slice(data, u32(row, 4), u32(row, 8)); + if (u32(row, 0) == 13) + stages(chunk, result, total); + } + } + for (auto &stage : result) + if (stage.stage == GpuStage::vs || stage.stage == GpuStage::ps || stage.stage == GpuStage::ms) { + stage.input_signature = inputs; + stage.output_signature = outputs; + } + return result; +} +} // namespace x2w diff --git a/src/guest_shader_container.h b/src/guest_shader_container.h new file mode 100644 index 000000000..422ac25c9 --- /dev/null +++ b/src/guest_shader_container.h @@ -0,0 +1,52 @@ +#pragma once +#include +#include +#include +#include +#include + +namespace x2w { +enum class GpuStage { ls, hs, es, gs, vs, ps, ms, cs }; +struct ShaderRootInput { + uint32_t type, offset_dwords, sgpr_count, base_register; + uint8_t user_data, root_parameter; +}; +struct ShaderResourceUse { + uint8_t type, root_type; + uint32_t offset_dwords, lower_bound, stride; + uint8_t dwords, user_data, root_parameter; +}; +struct ShaderAttribute { + uint8_t usage, row, mask, location, second_row, flags; + uint8_t last_component{}; +}; +struct PixelExportPatch { + unsigned target, word_offset; + std::string full_precision; +}; +struct ShaderSemantic { + std::string name; + unsigned index, system, component, row; + uint8_t mask, io_mask; +}; +struct GuestShaderStage { + GpuStage stage; + bool wave32; + bool fixed_vertex_abi{}; + unsigned vgprs, lds_bytes; + std::string code; + std::vector inputs; + std::vector resources; + std::array threads{}; + unsigned rsrc2{}; + std::vector attributes, outputs; + std::vector exports; + std::vector input_signature, output_signature; + unsigned pixel_input_address{}, pixel_input_enable = ~0u, depth_control{}; + // The signature component (9 f32, 5 u32, 4 i32) an RTV variant request asks of each color target; 0 when none. + std::array target_components{}; + unsigned mesh_clip_control{}, max_vertices{}, max_primitives{}, topology{}; + std::string full_precision_code() const; +}; +std::vector read_guest_shader_container(std::string_view container); +} // namespace x2w diff --git a/src/native_buffer_store_view.h b/src/native_buffer_store_view.h new file mode 100644 index 000000000..592d611ed --- /dev/null +++ b/src/native_buffer_store_view.h @@ -0,0 +1,76 @@ +#pragma once +#include "gfx1013_compute_native.h" +#include "startup_stubs/native_buffer_stride.h" +#include + +// Preserve the guest view window. The HLSL resource type determines the desktop component type. +namespace x2w { +inline bool native_buffer_store_view(const ComputeViewBinding &binding, D3D12_UNORDERED_ACCESS_VIEW_DESC &view, + UINT64 resource_bytes, IndexedAtomicView *atomic = nullptr) { + if (view.ViewDimension != D3D12_UAV_DIMENSION_BUFFER || view.Buffer.CounterOffsetInBytes || + !view.Buffer.NumElements) + return false; + if (binding.kind == ComputeViewKind::indexed_atomic_uav) { + if (!atomic) return false; + // Victory's view_stride: structured indices advance by StructureByteStride, + // raw indices are byte offsets and typed indices advance by format width. + const bool raw = view.Buffer.Flags == D3D12_BUFFER_UAV_FLAG_RAW; + const UINT structured = view.Buffer.StructureByteStride; + if (raw) { + if (structured || view.Format != DXGI_FORMAT_R32_TYPELESS) return false; + } else if (view.Buffer.Flags) { + return false; + } else if (structured) { + if (view.Format != DXGI_FORMAT_UNKNOWN || structured % 4 || + structured > D3D12_REQ_MULTI_ELEMENT_STRUCTURE_SIZE_IN_BYTES) return false; + } else if (view.Format != DXGI_FORMAT_R32_UINT && view.Format != DXGI_FORMAT_R32_SINT) { + return false; + } + UINT guest_stride = 0; + if (!x2w_startup::native_view_stride(19, &view, sizeof(view), guest_stride)) return false; + const UINT bytes_per_element = raw ? 4 : guest_stride; + const UINT64 bytes = UINT64(view.Buffer.NumElements) * bytes_per_element; + const UINT64 capacity = resource_bytes / bytes_per_element; + if (bytes > UINT32_MAX || view.Buffer.FirstElement > capacity || + view.Buffer.NumElements > capacity - view.Buffer.FirstElement) return false; + const UINT64 start = view.Buffer.FirstElement * bytes_per_element; + if (start % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) return false; + *atomic = {guest_stride, raw ? UINT(bytes - 3) : view.Buffer.NumElements}; + view.Format = DXGI_FORMAT_R32_TYPELESS; + view.Buffer.FirstElement = start / 4; + view.Buffer.NumElements = UINT(bytes / 4); + view.Buffer.StructureByteStride = 0; + view.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + return true; + } + if (view.Buffer.StructureByteStride) return false; + UINT stride = binding.required_bytes; + if (binding.kind == ComputeViewKind::raw_buffer_uav) { + if (view.Format != DXGI_FORMAT_R32_TYPELESS || view.Buffer.Flags != D3D12_BUFFER_UAV_FLAG_RAW) + return false; + stride = 4; + } else if (view.Buffer.Flags) { + return false; + } else if (binding.kind == ComputeViewKind::half_buffer_uav) { + if (!((stride == 2 && view.Format == DXGI_FORMAT_R16_FLOAT) || + (stride == 4 && view.Format == DXGI_FORMAT_R16G16_FLOAT) || + (stride == 8 && view.Format == DXGI_FORMAT_R16G16B16A16_FLOAT))) + return false; + } else if (binding.kind == ComputeViewKind::typed_buffer_uav) { + const DXGI_FORMAT formats[][3] = { + {DXGI_FORMAT_R32_UINT,DXGI_FORMAT_R32_SINT,DXGI_FORMAT_R32_FLOAT}, + {DXGI_FORMAT_R32G32_UINT,DXGI_FORMAT_R32G32_SINT,DXGI_FORMAT_R32G32_FLOAT}, + {DXGI_FORMAT_R32G32B32_UINT,DXGI_FORMAT_R32G32B32_SINT,DXGI_FORMAT_R32G32B32_FLOAT}, + {DXGI_FORMAT_R32G32B32A32_UINT,DXGI_FORMAT_R32G32B32A32_SINT,DXGI_FORMAT_R32G32B32A32_FLOAT} + }; + if (stride < 4 || stride > 16 || stride % 4) return false; + const auto &shape = formats[stride / 4 - 1]; + if (view.Format != shape[0] && view.Format != shape[1] && view.Format != shape[2]) return false; + view.Format = shape[0]; + } else { + return false; + } + const UINT64 capacity = resource_bytes / stride; + return view.Buffer.FirstElement <= capacity && view.Buffer.NumElements <= capacity - view.Buffer.FirstElement; +} +} diff --git a/src/native_compute_pipeline.cpp b/src/native_compute_pipeline.cpp new file mode 100644 index 000000000..4ca6ff947 --- /dev/null +++ b/src/native_compute_pipeline.cpp @@ -0,0 +1,133 @@ +#include "native_compute_pipeline.h" +#include "direct_compute_cache.h" +#include "startup_stubs/translated_sampler_bindings.h" +#include +#include +#include + +namespace x2w { +namespace { +using Clock = std::chrono::steady_clock; +double elapsed(Clock::time_point start) { + return std::chrono::duration(Clock::now() - start).count(); +} +bool is_uav(const ComputeViewBinding &binding) { return compute_uav(binding.kind); } +} // namespace + +NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, ShaderDxilCompiler &compiler, + const std::filesystem::path &marker, unsigned entry, + const std::filesystem::path &cache, bool direct_dxil, + HeapViewContract heap_view) { + if (!direct_dxil && heap_view != HeapViewContract::none) + throw std::runtime_error("a heap view contract needs the direct DXIL path"); + NativeComputePipeline pipeline; + auto start = Clock::now(); + auto program = direct_dxil + ? prepare_direct_compute(marker,entry,marker.extension()==L".cdx",cache,pipeline.frontend_cache_hit,heap_view) + : translate_compute(read_compute_request(marker), entry, direct_dxil); + pipeline.instructions = program.instruction_count; + pipeline.bindings = std::move(program.bindings); + std::sort(pipeline.bindings.begin(), pipeline.bindings.end(), [](auto &a, auto &b) { + if (is_uav(a) != is_uav(b)) + return !is_uav(a); + return a.shader_register < b.shader_register; + }); + + UINT counts[2]{}; + for (const auto &binding : pipeline.bindings) { + if (compute_heap_binding(binding.kind)) { + pipeline.heap_indexed = true; // ResourceDescriptorHeap reads: no table register + continue; + } + auto &count = counts[is_uav(binding)]; + if (binding.shader_register != count++) + throw std::runtime_error("noncontiguous compute register range"); + } + pipeline.uav_count = counts[1]; + pipeline.constants = std::move(program.constants); + for (const auto &block : pipeline.constants) + pipeline.constant_words += block.count; + pipeline.srv_count = counts[0]; + std::vector samplers; + for (const auto &sampler : program.samplers) { + samplers.push_back(x2w_startup::decode_sampler(sampler.words, static_cast(samplers.size()), sampler.comparison, + sampler.explicit_lod)); + } + pipeline.frontend_ms = elapsed(start); + start = Clock::now(); + auto shader = compiler.compile(direct_dxil ? program.dxil_ir : program.hlsl, L"cs_6_6", cache, + direct_dxil ? ShaderSourceFormat::dxil_ir : ShaderSourceFormat::hlsl); + pipeline.backend_ms = elapsed(start); + pipeline.cache_hit = shader.cache_hit; + + start = Clock::now(); + D3D12_DESCRIPTOR_RANGE ranges[2]{}; + for (const auto &b : pipeline.bindings) + pipeline.atomic_views += b.kind == ComputeViewKind::indexed_atomic_uav; + if (unsigned(bool(counts[0])) + unsigned(bool(counts[1])) + pipeline.constant_words + + 2 * pipeline.atomic_views > D3D12_MAX_ROOT_COST) + throw UnsupportedComputeShader("indexed atomic view metadata exceeds root parameter budget"); + std::vector params(3 + pipeline.atomic_views); + unsigned param_count = 0; + for (UINT i = 0; i < 2; ++i) { + if (!counts[i]) + continue; + auto ¶m = params[param_count++]; + ranges[i].RangeType = i ? D3D12_DESCRIPTOR_RANGE_TYPE_UAV : D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + ranges[i].NumDescriptors = counts[i]; + param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + param.DescriptorTable = {1, &ranges[i]}; + } + if (pipeline.constant_words) { + auto ¶m = params[param_count++]; + param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + param.Constants.Num32BitValues = pipeline.constant_words; + } + for (const auto &b : pipeline.bindings) { + if (b.kind != ComputeViewKind::indexed_atomic_uav) continue; + auto ¶m = params[param_count++]; + param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + param.Constants = {b.shader_register + 1, 0, 2}; + } + D3D12_ROOT_SIGNATURE_DESC desc{param_count, params.data(), static_cast(samplers.size()), samplers.data(), + pipeline.heap_indexed ? static_cast(0x400) // CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED + : D3D12_ROOT_SIGNATURE_FLAG_NONE}; + Microsoft::WRL::ComPtr blob; + if (FAILED(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr)) || + FAILED(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), + IID_PPV_ARGS(&pipeline.root)))) + throw std::runtime_error("native compute root signature creation failed"); + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = pipeline.root.Get(); + pso.CS = {shader.dxil.data(), shader.dxil.size()}; + if (FAILED(device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&pipeline.state)))) + throw std::runtime_error("native compute PSO creation failed"); + pipeline.pipeline_ms = elapsed(start); + return pipeline; +} + +void NativeComputePipeline::bind(ID3D12GraphicsCommandList *list, ID3D12DescriptorHeap *heap, + D3D12_GPU_DESCRIPTOR_HANDLE first, UINT increment, const unsigned *words, + const std::vector &atomic) const { + if (constant_words && !words) + throw std::runtime_error("compute root constants missing"); + if (atomic.size() != atomic_views) + throw std::runtime_error("indexed atomic view metadata missing"); + if (srv_count || uav_count || heap_indexed) + list->SetDescriptorHeaps(1, &heap); + list->SetComputeRootSignature(root.Get()); + list->SetPipelineState(state.Get()); + unsigned parameter = 0; + if (srv_count) + list->SetComputeRootDescriptorTable(parameter++, first); + first.ptr += UINT64(srv_count) * increment; + if (uav_count) + list->SetComputeRootDescriptorTable(parameter++, first); + if (constant_words) + list->SetComputeRoot32BitConstants(parameter++, constant_words, words, 0); + for (const auto &shape : atomic) { + const unsigned pair[]{shape.stride, shape.count}; + list->SetComputeRoot32BitConstants(parameter++, 2, pair, 0); + } +} +} // namespace x2w diff --git a/src/native_compute_pipeline.h b/src/native_compute_pipeline.h new file mode 100644 index 000000000..9951cc67d --- /dev/null +++ b/src/native_compute_pipeline.h @@ -0,0 +1,37 @@ +#pragma once + +#include "gfx1013_compute_native.h" +#include "shader_dxil_compiler.h" +#include + +namespace x2w { + +// Bindings are in desktop heap order: t0..tN followed by u0..uM. +// Each entry retains the guest table and byte offset determined by translation. +struct NativeComputePipeline { + Microsoft::WRL::ComPtr root; + Microsoft::WRL::ComPtr state; + std::vector bindings; + std::vector constants; + unsigned srv_count = 0; + unsigned uav_count = 0; + unsigned constant_words = 0, atomic_views = 0; + unsigned instructions = 0; + bool cache_hit = false, frontend_cache_hit = false; + bool heap_indexed = false; // reads ResourceDescriptorHeap: the root signature indexes the heap directly, which must be set + // on the list (bind() does it) and holds the selectable slots from index 0 + double frontend_ms = 0; + double backend_ms = 0; + double pipeline_ms = 0; + + void bind(ID3D12GraphicsCommandList *list, ID3D12DescriptorHeap *heap, D3D12_GPU_DESCRIPTOR_HANDLE first, + UINT increment, const unsigned *words = nullptr, + const std::vector &atomic = {}) const; +}; + +NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, ShaderDxilCompiler &compiler, + const std::filesystem::path &marker, unsigned entry, + const std::filesystem::path &cache, bool direct_dxil = false, + HeapViewContract heap_view = HeapViewContract::none); + +} // namespace x2w diff --git a/src/native_graphics_bindings.h b/src/native_graphics_bindings.h new file mode 100644 index 000000000..65d3f2989 --- /dev/null +++ b/src/native_graphics_bindings.h @@ -0,0 +1,35 @@ +#pragma once + +#include "gfx1013_compute_native.h" +#include "startup_stubs/translated_sampler_bindings.h" + +namespace x2w { +// Registers were assigned by the pair linker in vertex, then pixel order. +// Preserve the guest source of each SRV and both sampler modes through PSO creation. +struct NativeGraphicsBindings { + std::vector views; + unsigned srv_count = 0; + x2w_startup::TranslatedSamplers samplers; + + explicit NativeGraphicsBindings(const DirectGraphicsPair &pair) { + std::vector writes; + for (const auto *stage : {&pair.vertex, &pair.pixel}) { + for (const auto &v : stage->bindings) { + auto &range = compute_uav(v.kind) ? writes : views; + if (v.shader_register != range.size()) + throw std::runtime_error("unsupported graphics register order"); + range.push_back(v); + } + for (const auto &s : stage->samplers) { + samplers.statics.push_back(s.words); + samplers.comparison.push_back(s.comparison); + samplers.lod_limits.push_back(s.explicit_lod); + } + } + srv_count = static_cast(views.size()); + views.insert(views.end(), writes.begin(), writes.end()); + if (views.size() > 32) + throw std::runtime_error("graphics root capacity exceeded"); + } +}; +} diff --git a/src/native_texture_store_view.h b/src/native_texture_store_view.h new file mode 100644 index 000000000..a8b68d0f3 --- /dev/null +++ b/src/native_texture_store_view.h @@ -0,0 +1,20 @@ +#pragma once +#include "gfx1013_compute_native.h" +#include + +namespace x2w { +struct NativeHalfStoreFormat { + DXGI_FORMAT typed{}, typeless{}; + bool accepts(DXGI_FORMAT view, DXGI_FORMAT resource) const { + return view == typed && (resource == typed || resource == typeless); + } +}; +inline NativeHalfStoreFormat native_half_store_format(ComputeViewKind kind) { + switch (kind) { + case ComputeViewKind::half_scalar_uav: return {DXGI_FORMAT_R16_FLOAT, DXGI_FORMAT_R16_TYPELESS}; + case ComputeViewKind::half2_texture_uav: return {DXGI_FORMAT_R16G16_FLOAT, DXGI_FORMAT_R16G16_TYPELESS}; + case ComputeViewKind::half4_texture_uav: return {DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_TYPELESS}; + default: return {}; + } +} +} diff --git a/src/shader_compute_request.cpp b/src/shader_compute_request.cpp new file mode 100644 index 000000000..31cf4be79 --- /dev/null +++ b/src/shader_compute_request.cpp @@ -0,0 +1,271 @@ +#include "shader_compute_request.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; +namespace { +using Bytes = std::string; +template T read(const Bytes &data, size_t offset) { + if (offset > data.size() || sizeof(T) > data.size() - offset) + throw std::runtime_error("truncated compute request"); + T value; + std::memcpy(&value, data.data() + offset, sizeof(value)); + return value; +} +Bytes part(fs::path path, const char *suffix, size_t limit) { + path.replace_extension(suffix); + std::ifstream file(path, std::ios::binary | std::ios::ate); + auto size = file.tellg(); + if (size < 0 || size > static_cast(limit)) + throw std::runtime_error(std::string("missing or oversized ") + suffix); + Bytes bytes(static_cast(size), 0); + file.seekg(0); + if (size && !file.read(bytes.data(), size)) + throw std::runtime_error("short read"); + return bytes; +} +void hash_bytes(uint64_t &key, const void *data, size_t size) { + const auto *bytes = static_cast(data); + for (size_t i = 0; i < size; ++i) + key = (key ^ bytes[i]) * 1099511628211ull; +} +bool lower_hex(std::string_view text) { + if (text.empty()) return false; + for (char c : text) + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) + return false; + return true; +} +uint64_t parse_request_stem(std::string_view stem, const char *error_message) { + const std::string_view digits = stem.substr(4); + uint64_t expected = 0; + if (!lower_hex(digits)) + throw std::runtime_error(error_message); + const auto end = digits.data() + digits.size(); + const auto parsed = std::from_chars(digits.data(), end, expected, 16); + if (parsed.ec != std::errc{} || parsed.ptr != end) + throw std::runtime_error(error_message); + return expected; +} +void parse_pixel_inputs(const fs::path &marker, uint64_t expected, Bytes &entry, Bytes &description) { + fs::path path = marker; + path.replace_extension(".psin"); + std::ifstream file(path, std::ios::binary | std::ios::ate); + const auto size = file.tellg(); + if (size < 0 || size > 128) + throw std::runtime_error("invalid pixel input description"); + Bytes raw(static_cast(size), 0); + file.seekg(0); + if (size && !file.read(raw.data(), size)) + throw std::runtime_error("short read"); + std::string_view line = raw; + if (!line.empty() && line.back() == '\n') + line.remove_suffix(1); + if (line.size() < 22 || line.substr(0, 6) != "psin1 " || line.find_first_of("\r\n") != std::string_view::npos) + throw std::runtime_error("invalid pixel input description"); + const std::string_view key_hex = line.substr(6, 16); + if (!lower_hex(key_hex)) + throw std::runtime_error("invalid pixel input description"); + uint64_t described_key = 0; + const auto key_end = key_hex.data() + key_hex.size(); + if (std::from_chars(key_hex.data(), key_end, described_key, 16).ptr != key_end) + throw std::runtime_error("invalid pixel input description"); + bool has_ena = false, has_addr = false; + uint32_t ena = 0, addr = 0; + unsigned fields = 0; + size_t pos = 22; + while (pos < line.size()) { + if (line[pos] != ' ' || ++fields > 2) + throw std::runtime_error("invalid pixel input description"); + ++pos; + const size_t next = line.find(' ', pos); + const std::string_view token = line.substr(pos, next == std::string_view::npos ? line.size() - pos : next - pos); + pos = next == std::string_view::npos ? line.size() : next; + const bool is_ena = token.substr(0, 6) == "ena=0x"; + const bool is_addr = token.substr(0, 7) == "addr=0x"; + if (!is_ena && !is_addr) + throw std::runtime_error("invalid pixel input description"); + const std::string_view mask_hex = token.substr(is_ena ? 6 : 7); + if (mask_hex.empty() || mask_hex.size() > 4 || !lower_hex(mask_hex) || (is_ena ? has_ena : has_addr)) + throw std::runtime_error("invalid pixel input description"); + uint32_t value = 0; + const auto mask_end = mask_hex.data() + mask_hex.size(); + if (std::from_chars(mask_hex.data(), mask_end, value, 16).ptr != mask_end) + throw std::runtime_error("invalid pixel input description"); + if (is_ena) { + has_ena = true; + ena = value; + } else { + has_addr = true; + addr = value; + } + } + if (described_key != expected) + throw std::runtime_error("pixel input description names another pipeline"); + if (!has_ena) + throw std::runtime_error("pixel input enable mask missing from the stream description"); + if (!has_addr) + throw std::runtime_error("pixel input address mask missing from the stream description"); + if (ena & ~addr) + throw std::runtime_error("contradictory pixel input enable/address masks"); + entry.assign("psin1", 5); + const uint32_t words[2]{ena, addr}; + entry.append(reinterpret_cast(words), sizeof(words)); + char text[64]; + std::snprintf(text, sizeof(text), "psin1 %016llx ena=0x%04x addr=0x%04x\n", + static_cast(expected), ena, addr); + description = text; +} +// tools/startup/gfx2hlsl.py request_source: at most 256 bytes of "rtv1 ..." in decimal with one to +// eight formats and nothing else, whose FNV-1a hash is the key in the file name. The variant is translated from its +// base request's parts, which are read and checked against the base key like any base request. +x2w::GraphicsRequest read_rtv_variant(const fs::path &marker) { + const auto stem = marker.stem().string(); + if (stem.size() != 20 || stem.compare(0, 4, "req_")) + throw std::runtime_error("expected req_<16 hex digits>.rtv"); + const uint64_t expected = parse_request_stem(stem, "invalid RTV variant request key"); + Bytes text; + try { + text = part(marker, ".rtv", 256); + } catch (const std::runtime_error &) { + throw std::runtime_error("invalid RTV variant request"); + } + uint64_t key = 1469598103934665603ull; + hash_bytes(key, text.data(), text.size()); + std::vector tokens; + std::string_view rest = text; + bool valid = rest.substr(0, 5) == "rtv1 "; + if (valid) rest.remove_prefix(5); + while (valid) { + const size_t end = rest.find(' '); + const auto token = rest.substr(0, end); + valid = !token.empty() && token.size() <= (tokens.empty() ? 20u : 10u) && + token.find_first_not_of("0123456789") == token.npos; + tokens.push_back(token); + if (end == rest.npos) break; + rest.remove_prefix(end + 1); + } + if (!valid || tokens.size() < 2 || tokens.size() > 9 || key != expected) + throw std::runtime_error("invalid RTV variant request"); + uint64_t base = 0; + std::vector formats; + for (size_t i = 0; i < tokens.size(); ++i) { + uint64_t value = 0; + const auto parsed = std::from_chars(tokens[i].data(), tokens[i].data() + tokens[i].size(), value); + if (parsed.ec != std::errc{} || (i && value > 0xffffffffull)) + throw std::runtime_error("invalid RTV variant values"); + if (!i) base = value; + else formats.push_back(static_cast(value)); + } + char name[32]; + std::snprintf(name, sizeof(name), "req_%016llx.a", static_cast(base)); + x2w::GraphicsRequest request; + try { + request = x2w::read_graphics_request(marker.parent_path() / name); + } catch (const std::runtime_error &error) { + throw std::runtime_error(std::string("RTV variant source: ") + error.what()); + } + request.key = expected; + request.rtv_request = std::move(text); + request.rtv_formats = std::move(formats); + return request; +} +} // namespace + +x2w::GraphicsRequest x2w::read_graphics_request(const fs::path &marker) { + if (marker.extension() == ".rtv") return read_rtv_variant(marker); + auto stem = marker.stem().string(); + if (marker.extension() != ".a" || stem.size() != 20 || stem.compare(0, 4, "req_")) + throw std::runtime_error("expected req_<16 hex digits>.a"); + const uint64_t expected = parse_request_stem(stem, "invalid graphics request key"); + GraphicsRequest request{part(marker, ".a", 64 << 20), part(marker, ".b", 64 << 20), + part(marker, ".root", 16 << 20), {}, {}, {}, expected}; + if (fs::exists(fs::path(marker).replace_extension(".ia"))) + 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); + const auto request_key = [&](std::string_view revision) { + uint64_t key = 1469598103934665603ull; + hash_bytes(key, revision.data(), revision.size()); + for (const auto *p : {&request.a, &request.b, &request.root, &request.input_layout, &request.pixel_entry}) + hash_bytes(key, p->data(), p->size()); + return key; + }; + if (request.root.empty()) + throw std::runtime_error("graphics request key mismatch or missing root"); + // Match new runtime captures and keep revision-28 archives replayable. + constexpr char revision[] = "x2w-startup-shader-29"; + if (request_key(revision) != expected && request_key("x2w-startup-shader-28") != expected) { + if (!request.pixel_entry.empty()) + throw std::runtime_error("stale pixel input description: graphics request key mismatch"); + throw std::runtime_error("graphics request key mismatch or missing root"); + } + return request; +} + +x2w::ComputeRequest x2w::read_compute_request(const fs::path &marker) { + auto name = marker.stem().string(); + if (marker.extension() != ".c67" || name.size() != 20 || name.compare(0, 4, "req_")) + throw std::runtime_error("expected req_<16 hex digits>.c67"); + const uint64_t expected = parse_request_stem(name, "invalid request key"); + auto code = part(marker, ".c67", 1 << 20), data = part(marker, ".data", 1 << 20), + root = part(marker, ".root", 16 << 20); + auto desc = part(marker, ".desc", 96), sa = part(marker, ".sa", 4096), sb = part(marker, ".sb", 4096); + if (desc.size() != 96 || read(desc, 48) != code.size() || read(desc, 64) != data.size() || + read(desc, 16) != sa.size() || read(desc, 32) != sb.size()) + throw std::runtime_error("inconsistent compute request"); + const auto request_key = [&](std::string_view revision) { + uint64_t key = 1469598103934665603ull; + hash_bytes(key, revision.data(), revision.size()); + for (const auto *p : {&code, &data, &root, &desc, &sa, &sb}) { + uint64_t size = p->size(); + hash_bytes(key, &size, sizeof(size)); + hash_bytes(key, p->data(), p->size()); + } + return key; + }; + constexpr char revision[] = "x2w-startup-shader-29cs"; + if (request_key(revision) != expected && request_key("x2w-startup-shader-28cs") != expected) + throw std::runtime_error("compute request key mismatch"); + if (root.empty() || sa.size() != 28 || code.empty() || data.empty() || code.size() % 4) + throw std::runtime_error(sa.size() != 28 ? "compute state block A is not 28 bytes" + : "inconsistent compute request"); + return {std::move(code), std::move(data), std::move(root), std::move(desc), std::move(sa), std::move(sb), expected}; +} + +std::string x2w::read_shader_container_bytes(const fs::path &file) { + std::ifstream stream(file, std::ios::binary | std::ios::ate); + auto length = stream.tellg(); + if (length < 32 || length > 64 * 1024 * 1024) + throw std::runtime_error("missing or oversized shader container"); + std::string bytes(static_cast(length), 0); + stream.seekg(0); + if (!stream.read(bytes.data(), length)) throw std::runtime_error("truncated shader container"); + return bytes; +} +x2w::ComputeContainer x2w::read_compute_container(const fs::path &file) { + auto bytes=read_shader_container_bytes(file); + const auto stem=file.stem().string(); + if (stem.compare(0,4,"req_") != 0) return {std::move(bytes), {}}; + uint64_t expected=0; + if (stem.size()!=20 || file.extension()!=".cdx") + throw std::runtime_error("invalid container request filename"); + auto parsed=std::from_chars(stem.data()+4,stem.data()+stem.size(),expected,16); + if(parsed.ec!=std::errc{} || parsed.ptr!=stem.data()+stem.size()) + throw std::runtime_error("invalid container request key"); + auto root=part(file,".root",16<<20); + uint64_t key=1469598103934665603ull, size=root.size(); + constexpr char revision[]="native-container-1"; + hash_bytes(key,revision,sizeof(revision)-1); + hash_bytes(key,&size,sizeof(size)); + hash_bytes(key,root.data(),root.size()); + hash_bytes(key,bytes.data(),bytes.size()); + if (root.empty() || key!=expected) throw std::runtime_error("container request key mismatch"); + return {std::move(bytes),std::move(root)}; +} diff --git a/src/shader_compute_request.h b/src/shader_compute_request.h new file mode 100644 index 000000000..90470c272 --- /dev/null +++ b/src/shader_compute_request.h @@ -0,0 +1,29 @@ +#pragma once +#include +#include +#include +#include + +namespace x2w { +struct ComputeRequest { + std::string code, data, root, description, sa, sb; + uint64_t key; +}; +struct ComputeContainer { + std::string bytes, root; +}; +struct GraphicsRequest { + std::string a, b, root, input_layout, pixel_entry, pixel_input_description; + uint64_t key{}; + // An RTV variant (req_.rtv): its "rtv1 ..." text and the ordered target formats. The + // parts above are then its base request's, checked against the base key, and key is the variant's. + std::string rtv_request; + std::vector rtv_formats; +}; +// marker: req_.a, or req_.rtv for an RTV variant of a base request in the same directory. +GraphicsRequest read_graphics_request(const std::filesystem::path &marker); +std::string read_shader_container_bytes(const std::filesystem::path &file); +ComputeContainer read_compute_container(const std::filesystem::path &file); +// Verify the content key over all six immutable capture parts before exposing any bytes. +ComputeRequest read_compute_request(const std::filesystem::path &marker); +} // namespace x2w diff --git a/src/shader_dxil_compiler.cpp b/src/shader_dxil_compiler.cpp new file mode 100644 index 000000000..520f4af79 --- /dev/null +++ b/src/shader_dxil_compiler.cpp @@ -0,0 +1,209 @@ +#include +#include +#include "shader_dxil_compiler.h" +#include "gfx1013_compute_ir.h" +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; +using Microsoft::WRL::ComPtr; +namespace { +using Bytes = std::vector; +bool try_read_file(const fs::path& path, Bytes& bytes) { + HANDLE handle = CreateFileW(path.c_str(), GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (handle == INVALID_HANDLE_VALUE) return false; + LARGE_INTEGER size{}; + const bool sized = GetFileSizeEx(handle, &size) && size.QuadPart >= 0 && size.QuadPart <= 256ll * 1024 * 1024; + bool ok = sized; + if (sized) { + bytes.resize(static_cast(size.QuadPart)); + DWORD read_bytes = 0; + ok = !size.QuadPart || (ReadFile(handle, bytes.data(), static_cast(size.QuadPart), &read_bytes, nullptr) && + read_bytes == static_cast(size.QuadPart)); + } + CloseHandle(handle); + return ok; +} +Bytes read_file(const fs::path& path) { + Bytes bytes; + if (!try_read_file(path, bytes)) throw std::runtime_error("unreadable or oversized input"); + return bytes; +} +std::string digest(const void* data, size_t size) { + if (size > ULONG_MAX) throw std::length_error("digest input too large"); + std::array hash{}; + if (BCryptHash(BCRYPT_SHA256_ALG_HANDLE,nullptr,0, + static_cast(const_cast(data)),static_cast(size), + hash.data(),static_cast(hash.size())) < 0) throw std::runtime_error("SHA-256 failed"); + std::string result; + constexpr char hex[] = "0123456789abcdef"; + for (auto byte : hash) { result += hex[byte >> 4]; result += hex[byte & 15]; } + return result; +} +void checked(HRESULT status) { + if (FAILED(status)) throw std::runtime_error("DXC API failure " + std::to_string(status)); +} +} +namespace x2w { +std::string shader_digest(std::string_view bytes) { return digest(bytes.data(),bytes.size()); } +struct ShaderDxilCompiler::Sdk { + struct Module { + HMODULE handle{}; + bool process_lifetime{}; + ~Module() { if (handle && !process_lifetime) FreeLibrary(handle); } + Module() = default; + Module(const Module&) = delete; + Module& operator=(const Module&) = delete; + } validator, compiler; + std::string identity; + DxcCreateInstanceProc create{}; + explicit Sdk(const fs::path& directory); +}; + +ShaderDxilCompiler::Sdk::Sdk(const fs::path& sdk_directory) { + auto load = [&](Module& module, const wchar_t* name) { + auto path = fs::canonical(sdk_directory / name); + auto file = read_file(path); + identity += digest(file.data(), file.size()); + module.handle = LoadLibraryExW(path.c_str(),nullptr,LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32); + if (!module.handle) throw std::runtime_error("could not load DXC SDK module"); + }; + load(validator, L"dxil.dll"); + load(compiler, L"dxcompiler.dll"); + create = reinterpret_cast(GetProcAddress(compiler.handle,"DxcCreateInstance")); + if (!create) throw std::runtime_error("DXC entry missing"); +} + +ShaderDxilCompiler::ShaderDxilCompiler(const fs::path& directory) + : ShaderDxilCompiler(std::make_shared(directory)) {} + +ShaderDxilCompiler::ShaderDxilCompiler(std::shared_ptr sdk) : sdk_(std::move(sdk)) { + checked(sdk_->create(CLSID_DxcCompiler, IID_PPV_ARGS(&compiler_))); + checked(sdk_->create(CLSID_DxcUtils, IID_PPV_ARGS(&utils_))); +} + +ShaderDxilCompiler ShaderDxilCompiler::new_worker() const { + return ShaderDxilCompiler(sdk_); +} + +ShaderDxilCompiler ShaderDxilCompiler::runtime_worker(const fs::path& directory) { + static const auto sdk = [&] { + auto loaded = std::make_shared(directory); + // The loader releases these two runtime references at process shutdown. + // A shim static destructor runs under loader lock, after DXC may detach. + loaded->compiler.process_lifetime = true; + loaded->validator.process_lifetime = true; + return loaded; + }(); + return ShaderDxilCompiler(sdk); +} + +HRESULT ShaderDxilCompiler::reflect(const void* bytecode,size_t bytes,REFIID iid,void** result) { + DxcBuffer buffer{bytecode,bytes,0}; + return utils_->CreateReflection(&buffer,iid,result); +} + +CompiledShader ShaderDxilCompiler::compile(const std::string& source_text, const std::wstring& profile, + const fs::path& cache, ShaderSourceFormat format) { + const bool direct = format == ShaderSourceFormat::dxil_ir; + const bool native_ir = source_text.find("#pragma x2w_") != std::string::npos; + // Bump the native IR version when instruction semantics change. Keying + // before expansion lets a validated hit bypass instruction lowering. + const char* revision = direct ? "x2w-direct-dxil-1/validated/" : native_ir ? "x2w-dxil-native-ir-1/main/-Gis/-O3/" : "x2w-dxil-1/main/-Gis/-O3/"; + const std::string identity = revision + sdk_->identity + digest(profile.data(),profile.size()*sizeof(wchar_t)) + + digest(source_text.data(),source_text.size()); + const auto key = digest(identity.data(),identity.size()); + const auto path = cache / (key + ".bin"); + Bytes cached; + if (try_read_file(path, cached) && cached.size() > 128 && std::equal(key.begin(), key.end(), cached.begin())) { + const auto hash = digest(cached.data() + 128, cached.size() - 128); + if (std::equal(hash.begin(), hash.end(), cached.begin() + 64)) + return {Bytes(cached.begin() + 128, cached.end()), true}; + } + ComPtr blob; + if (direct) { + ComPtr input; + checked(utils_->CreateBlob(source_text.data(),static_cast(source_text.size()),DXC_CP_UTF8,&input)); + ComPtr assembler; + checked(sdk_->create(CLSID_DxcAssembler,IID_PPV_ARGS(&assembler))); + auto take_result = [](IDxcOperationResult *result) { + HRESULT hr; + checked(result->GetStatus(&hr)); + if (FAILED(hr)) { + ComPtr error; + result->GetErrorBuffer(&error); + throw std::runtime_error(error ? std::string(static_cast(error->GetBufferPointer()), + error->GetBufferSize()) : "DXIL assembly/validation failed"); + } + ComPtr bytes; + checked(result->GetResult(&bytes)); + return bytes; + }; + ComPtr assembled, validated; + checked(assembler->AssembleToContainer(input.Get(),&assembled)); + blob=take_result(assembled.Get()); + ComPtr validator; + const auto create_validator = reinterpret_cast( + GetProcAddress(sdk_->validator.handle,"DxcCreateInstance")); + if (!create_validator) throw std::runtime_error("SDK DXIL validator export unavailable"); + checked(create_validator(CLSID_DxcValidator,IID_PPV_ARGS(&validator))); + checked(validator->Validate(blob.Get(),DxcValidatorFlags_InPlaceEdit,&validated)); + blob=take_result(validated.Get()); + } else { + std::string expanded; + if (native_ir) { + expanded=expand_gfx1013_compute(source_text); + if (expanded!=source_text && profile.rfind(L"cs_",0)!=0) + throw std::runtime_error("native register lowering requires a compute profile"); + } + const auto& hlsl=native_ir ? expanded : source_text; + DxcBuffer source{hlsl.data(),hlsl.size(),DXC_CP_UTF8}; + const wchar_t* args[] = {L"-E",L"main",L"-T",profile.c_str(),L"-Gis",L"-O3"}; + ComPtr result; + checked(compiler_->Compile(&source,args,ARRAYSIZE(args),nullptr,IID_PPV_ARGS(&result))); + HRESULT status; + checked(result->GetStatus(&status)); + if (FAILED(status)) { + ComPtr errors; + checked(result->GetOutput(DXC_OUT_ERRORS,IID_PPV_ARGS(&errors),nullptr)); + throw std::runtime_error(errors && errors->GetStringLength() ? errors->GetStringPointer() : "DXC compile failed"); + } + checked(result->GetOutput(DXC_OUT_OBJECT,IID_PPV_ARGS(&blob),nullptr)); + } + const auto* start = static_cast(blob->GetBufferPointer()); + Bytes bytes(start,start+blob->GetBufferSize()); + auto hash = digest(bytes.data(),bytes.size()); + fs::create_directories(cache); + static std::atomic serial{}; + auto temp = path; + temp += "."+std::to_string(GetCurrentProcessId())+"."+std::to_string(serial++)+".tmp"; + try { + std::ofstream out(temp,std::ios::binary | std::ios::trunc); + out.exceptions(std::ios::badbit | std::ios::failbit); + out << key << hash; + out.write(reinterpret_cast(bytes.data()),bytes.size()); + out.close(); + if (!MoveFileExW(temp.c_str(),path.c_str(),MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { + // Another process may already have published and opened the same + // entry without FILE_SHARE_DELETE. Only accept an identical winner. + auto winner=read_file(path); + if(winner.size()!=128+bytes.size() || !std::equal(key.begin(),key.end(),winner.begin()) || + !std::equal(hash.begin(),hash.end(),winner.begin()+64) || + !std::equal(bytes.begin(),bytes.end(),winner.begin()+128)) + throw std::runtime_error("could not publish DXIL cache entry"); + fs::remove(temp); + } + } catch (...) { + std::error_code ignored; + fs::remove(temp,ignored); + throw; + } + return {std::move(bytes),false}; +} +} diff --git a/src/shader_dxil_compiler.h b/src/shader_dxil_compiler.h new file mode 100644 index 000000000..64f097d54 --- /dev/null +++ b/src/shader_dxil_compiler.h @@ -0,0 +1,45 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace x2w { + +std::string shader_digest(std::string_view bytes); +enum class ShaderSourceFormat { hlsl, dxil_ir }; + +struct CompiledShader { + std::vector dxil; + bool cache_hit = false; +}; + +// The caller supplies a matching SDK dxcompiler.dll and dxil.dll in the same directory. +// Source must be self-contained. The backend never resolves process-relative includes. +class ShaderDxilCompiler { +public: + explicit ShaderDxilCompiler(const std::filesystem::path& sdk_directory); + ShaderDxilCompiler(const ShaderDxilCompiler&) = delete; + ShaderDxilCompiler& operator=(const ShaderDxilCompiler&) = delete; + // Independent DXC interfaces, with the same loaded and fingerprinted SDK. + ShaderDxilCompiler new_worker() const; + // The startup shim uses one SDK directory for the lifetime of the process. + static ShaderDxilCompiler runtime_worker(const std::filesystem::path& sdk_directory); + CompiledShader compile(const std::string& hlsl, const std::wstring& profile, + const std::filesystem::path& cache, ShaderSourceFormat format = ShaderSourceFormat::hlsl); + HRESULT reflect(const void* bytecode, size_t bytes, REFIID iid, void** result); +private: + struct Sdk; + explicit ShaderDxilCompiler(std::shared_ptr sdk); + std::shared_ptr sdk_; + Microsoft::WRL::ComPtr compiler_; + Microsoft::WRL::ComPtr utils_; +}; +} diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 5060aecaa..3dfc27444 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -77,6 +77,23 @@ bool float_output_format(DXGI_FORMAT format) std::unordered_map& compute_translations() { static std::unordered_map m; return m; } LONG compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated, compute_dispatches_unmodelled; +// The root signature and pipeline of a translation whose entry values and views are filled in. Returns why it is +// unavailable, or null when it is ready. +const char* create_compute_pipeline(ComputeTranslation& tr, const void* code, std::size_t bytes) +{ + // Parameter 0 keeps one constant for a program without entry values: a constants parameter cannot be empty. + if (FAILED(x2w_startup::create_translated_root(device_of(the_device), static_cast(tr.uds.empty() ? 1 : tr.uds.size()), + static_cast(tr.srvs.size()), tr.samplers, &tr.root, static_cast(tr.uavs.size())))) + return "root signature creation failed"; + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = tr.root.Get(); + desc.CS = {code, bytes}; + if (FAILED(device_of(the_device)->CreateComputePipelineState(&desc, IID_PPV_ARGS(&tr.pipeline)))) + return "pipeline creation failed"; + tr.state = 1; + return nullptr; +} + // draw_lock held. Returns the reason the translation is unavailable, or null when it is ready or still absent. const char* load_compute_translation(ComputeTranslation& tr) { @@ -176,21 +193,77 @@ const char* load_compute_translation(ComputeTranslation& tr) } x2w_startup::ComPtr code; if (!cache_path(path, L"", tr.key, L".cs.cso") || FAILED(D3DReadFileToBlob(path, &code))) return "no compiled program"; - // Parameter 0 keeps one constant for a program without entry values: a constants parameter cannot be empty. - if (FAILED(x2w_startup::create_translated_root(device_of(the_device), static_cast(tr.uds.empty() ? 1 : tr.uds.size()), - static_cast(tr.srvs.size()), tr.samplers, &tr.root, static_cast(tr.uavs.size())))) - return "root signature creation failed"; - D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; - desc.pRootSignature = tr.root.Get(); - desc.CS = {code->GetBufferPointer(), code->GetBufferSize()}; - if (FAILED(device_of(the_device)->CreateComputePipelineState(&desc, IID_PPV_ARGS(&tr.pipeline)))) - return "pipeline creation failed"; - tr.state = 1; + if (const char* failure = create_compute_pipeline(tr, code->GetBufferPointer(), code->GetBufferSize())) return failure; log("x2w-draw compute pipeline %016llx translated: %zu entry values, %zu inputs, %zu outputs", tr.key, tr.uds.size(), tr.srvs.size(), tr.uavs.size()); return nullptr; } +// X2W_NATIVE_SHADERS=: the first Dispatch of a slot 67 request translates +// it in this process with the C++ compiler (src/gfx1013_compute_native.cpp), before a published .txt is read +// and with no offline translator running. The dispatch path below binds the result, so a program is accepted only +// with root constants, raw table buffers it loads per lane (buffer_load_dword) and raw table buffers it stores to. +// A refusal is logged and leaves the key to the published translations. draw_lock held. Returns whether tr is ready. +bool translate_compute_natively(ComputeTranslation& tr) +{ +#ifdef X2W_NATIVE_SHADERS + wchar_t sdk[MAX_PATH], path[MAX_PATH]; + const DWORD length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH); + if (!length || length >= MAX_PATH) return false; + if (!cache_path(path, L"req_", tr.key, L".c67")) return false; + try { + // The request as this runtime published it. The reader checks the six parts against the key in the name. + // Entry 0: a source-built program starts there, and the frontend reads a capture's v_nop prefix as code. + auto program = x2w::translate_compute(x2w::read_compute_request(path), 0, true); + for (const auto& block : program.constants) + for (unsigned word = 0; word < block.count; ++word) + tr.uds.push_back({static_cast(block.root_parameter), static_cast(word)}); + std::sort(program.bindings.begin(), program.bindings.end(), + [](const auto& a, const auto& b) { return a.shader_register < b.shader_register; }); + for (const auto& view : program.bindings) { + // The two kinds a fixture has run through this path: a raw buffer read per lane, and one written. + const bool output = view.kind == x2w::ComputeViewKind::raw_buffer_uav; + auto& slots = output ? tr.uavs : tr.srvs; + if ((!output && view.kind != x2w::ComputeViewKind::raw_vector_srv) || view.array_count != 1 || + view.root_parameter >= 16 || view.shader_register != slots.size()) + throw std::runtime_error("view kind " + std::to_string(static_cast(view.kind)) + + " is not bound for a natively translated program"); + slots.push_back({static_cast(view.root_parameter), static_cast(view.byte_offset)}); + } + if (!program.samplers.empty() || tr.uds.size() > 32 || tr.srvs.size() > 32 || tr.uavs.size() > 8) + throw std::runtime_error("a sampler, or more entry values, inputs or outputs than the dispatch path binds"); + // A direct module declares wave size 32 (src/dxil_module.h): without it the pipeline cannot be created. + D3D12_FEATURE_DATA_D3D12_OPTIONS1 waves{}; + if (FAILED(device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, &waves, sizeof(waves))) || + !waves.WaveOps || waves.WaveLaneCountMin > 32 || waves.WaveLaneCountMax < 32) + throw std::runtime_error("the adapter has no 32-lane waves"); + // Never released: a static destructor would release DXC after its module may have detached. + static x2w::ShaderDxilCompiler* const compiler = + new x2w::ShaderDxilCompiler(x2w::ShaderDxilCompiler::runtime_worker(sdk)); + const auto shader = compiler->compile(program.dxil_ir, L"cs_6_6", std::filesystem::path(path).parent_path() / L"native", + x2w::ShaderSourceFormat::dxil_ir); + if (const char* failure = create_compute_pipeline(tr, shader.dxil.data(), shader.dxil.size())) + throw std::runtime_error(failure); + log("x2w-draw compute pipeline %016llx translated natively: %zu entry values, %zu inputs, %zu outputs", tr.key, + tr.uds.size(), tr.srvs.size(), tr.uavs.size()); + return true; + } catch (const std::exception& error) { + tr.uds.clear(); + tr.srvs.clear(); + tr.uavs.clear(); + tr.root.Reset(); + tr.pipeline.Reset(); + static LONG logged; + if (first_calls(logged, 16)) + log("x2w-draw compute pipeline %016llx not translated natively: %s", tr.key, error.what()); + return false; + } +#else + (void)tr; + return false; +#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], @@ -292,8 +365,11 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& else if (!ensure_draw_heap(self->own().list_device)) reason = "no descriptor heap on this device"; else { if (!tr->state || tr->manifest_retry.due(GetTickCount64())) { - tr->unmodelled = load_compute_translation(*tr); - if (tr->unmodelled) log("x2w-draw compute pipeline %016llx not translated: %s", key, tr->unmodelled); + // 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); + if (tr->unmodelled) log("x2w-draw compute pipeline %016llx not translated: %s", key, tr->unmodelled); + } } if (tr->state != 1) { // A manifest the runtime cannot bind is the dispatch side's work; an absent one is the translator's. diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 9976d39e3..e48560cef 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -79,6 +79,10 @@ #include "state_block_blend.h" #include "title_heap_memory.h" #include "startup_stubs/xmem_section_buffer.h" +#ifdef X2W_NATIVE_SHADERS // d3d12_xs_shim only: the C++ shader compiler (startup_stubs/d3d12_compute_dispatch.inl) +#include "gfx1013_compute_native.h" +#include "shader_dxil_compiler.h" +#endif #include #include #include diff --git a/src/startup_stubs/native_buffer_stride.h b/src/startup_stubs/native_buffer_stride.h new file mode 100644 index 000000000..8d89e6db6 --- /dev/null +++ b/src/startup_stubs/native_buffer_stride.h @@ -0,0 +1,70 @@ +#pragma once + +#include "memory_srv_buffer.h" +#include +#include + +namespace x2w_startup { +inline UINT typed_dword_channels(const D3D12_SHADER_RESOURCE_VIEW_DESC &view) { + if (view.ViewDimension != D3D12_SRV_DIMENSION_BUFFER || view.Buffer.StructureByteStride || + view.Buffer.Flags || view.Shader4ComponentMapping != D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING) + return 0; + switch (view.Format) { + case DXGI_FORMAT_R32_UINT: case DXGI_FORMAT_R32_SINT: case DXGI_FORMAT_R32_FLOAT: return 1; + case DXGI_FORMAT_R32G32_UINT: case DXGI_FORMAT_R32G32_SINT: case DXGI_FORMAT_R32G32_FLOAT: return 2; + case DXGI_FORMAT_R32G32B32_UINT: case DXGI_FORMAT_R32G32B32_SINT: case DXGI_FORMAT_R32G32B32_FLOAT: return 3; + case DXGI_FORMAT_R32G32B32A32_UINT: case DXGI_FORMAT_R32G32B32A32_SINT: case DXGI_FORMAT_R32G32B32A32_FLOAT: return 4; + default: return 0; + } +} + +inline DXGI_FORMAT typed_dword_uint_format(UINT channels) { + constexpr DXGI_FORMAT formats[]{DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R32G32_UINT, + DXGI_FORMAT_R32G32B32_UINT, DXGI_FORMAT_R32G32B32A32_UINT}; + return channels <= 4 ? formats[channels] : DXGI_FORMAT_UNKNOWN; +} + +// Only a verified materialized token supplies the slot and address. Unregistered +// entries keep their empty record (slot zero), even if their heap bytes are zero. +inline bool native_null_typed_array_srv(UINT slot, UINT64 address, const void *bytes, size_t size, + UINT required_bytes, D3D12_SHADER_RESOURCE_VIEW_DESC &view) { + if (slot != 18 || address || !bytes || size < sizeof(view)) return false; + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + std::memcpy(&desc, bytes, sizeof(desc)); + const UINT channels = typed_dword_channels(desc); + if (!channels || channels * 4 < required_bytes) return false; + desc.Format = typed_dword_uint_format(channels); + view = desc; + return true; +} + +// The shader indexes raw views in bytes and structured views in elements. +inline bool native_view_stride(UINT slot, const void *bytes, std::size_t size, UINT &stride) { + bool raw = false; + DXGI_FORMAT format{}; + stride = 0; + if (slot == 18) { + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + if (size < sizeof(desc)) return false; + std::memcpy(&desc, bytes, sizeof(desc)); + if (desc.ViewDimension != D3D12_SRV_DIMENSION_BUFFER) return true; + stride = desc.Buffer.StructureByteStride; + raw = (desc.Buffer.Flags & D3D12_BUFFER_SRV_FLAG_RAW) != 0; + format = desc.Format; + } else if (slot == 19) { + D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; + if (size < sizeof(desc)) return false; + std::memcpy(&desc, bytes, sizeof(desc)); + if (desc.ViewDimension != D3D12_UAV_DIMENSION_BUFFER) return true; + stride = desc.Buffer.StructureByteStride; + raw = (desc.Buffer.Flags & D3D12_BUFFER_UAV_FLAG_RAW) != 0; + format = desc.Format; + } else { + return false; + } + if (!stride) + stride = raw ? 1u : x2w_startup::typed_buffer_format_bytes(format); + return stride > 0 && stride <= 0x3fff; +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/native_copy_ranges.h b/src/startup_stubs/native_copy_ranges.h new file mode 100644 index 000000000..49aa769a3 --- /dev/null +++ b/src/startup_stubs/native_copy_ranges.h @@ -0,0 +1,55 @@ +#pragma once + +#include +#include +#include + +namespace x2w_startup { +enum class CopyCoverage { none, partial, full }; + +// A union of disjoint half-open offsets in one placement. Callers validate +// the offsets against the buffer size before adding or looking up a range. +struct NativeCopyRanges { + struct Span { std::uint64_t begin, end; }; + std::vector spans; + + void add(std::uint64_t begin, std::uint64_t end) { + if (begin >= end) return; + auto first = std::lower_bound(spans.begin(), spans.end(), begin, + [](const Span& row, std::uint64_t start) { return row.end < start; }); + auto last = first; + while (last != spans.end() && last->begin <= end) { + begin = (std::min)(begin, last->begin); + end = (std::max)(end, last->end); + ++last; + } + spans.insert(spans.erase(first, last), {begin, end}); + } + + void cpu_write(std::uint64_t begin, std::uint64_t end) { + if (begin >= end) return; + for (auto it = spans.begin(); it != spans.end() && it->begin < end;) { + if (it->end <= begin) { ++it; continue; } + const Span old = *it; + if (old.begin < begin) { + it->end = begin; + ++it; + if (old.end > end) { spans.insert(it, {end, old.end}); return; } + } else if (old.end > end) { + it->begin = end; + return; + } else { + it = spans.erase(it); + } + } + } + + CopyCoverage coverage(std::uint64_t begin, std::uint64_t end) const { + if (begin >= end) return CopyCoverage::none; + auto row = std::lower_bound(spans.begin(), spans.end(), begin, + [](const Span& s, std::uint64_t start) { return s.end <= start; }); + if (row == spans.end() || row->begin >= end) return CopyCoverage::none; + return row->begin <= begin && end <= row->end ? CopyCoverage::full : CopyCoverage::partial; + } +}; +} diff --git a/src/startup_stubs/native_dispatch_states.h b/src/startup_stubs/native_dispatch_states.h new file mode 100644 index 000000000..8ad02d8e2 --- /dev/null +++ b/src/startup_stubs/native_dispatch_states.h @@ -0,0 +1,101 @@ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace x2w_startup { +struct NativeTextureWindow { + UINT mip = 0, mips = 1, slice = 0, slices = 1, plane = 0; +}; + +// Build from the resolved descriptors for one dispatch. A single-access +// resource needs one whole-resource state irrespective of its mip/array size. +class NativeDispatchStates { + struct Interval { UINT first, end; bool write; }; + struct Use { + bool read = false, write = false, upload = false; + UINT mips = 0, slices = 0; + std::vector intervals; + }; + std::map resources; + std::vector transitions, uavs; + + public: + template explicit NativeDispatchStates(const Views &views) { + bool mixed_access = false; + for (const auto &v : views) { + if (!v.resource) continue; + auto &use = resources[v.resource.Get()]; + if (v.write) use.write = true; + else use.read = true; + use.upload |= v.buffer.upload; + mixed_access |= use.read && use.write; + } + if (mixed_access) for (const auto &v : views) { + if (!v.resource) continue; + auto &use = resources.at(v.resource.Get()); + if (!use.read || !use.write) continue; + if (!use.mips) { + const auto desc = v.resource->GetDesc(); + use.mips = desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? 1 : desc.MipLevels; + use.slices = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? 1 : desc.DepthOrArraySize; + } + const auto &w = v.texture; + if (!w.mip && w.mips == use.mips) { + const UINT first = (w.slice + w.plane * use.slices) * use.mips; + use.intervals.push_back({first, first + w.slices * use.mips, v.write}); + continue; + } + for (UINT a = 0; a < w.slices; ++a) { + const UINT first = w.mip + (w.slice + a + w.plane * use.slices) * use.mips; + use.intervals.push_back({first, first + w.mips, v.write}); + } + } + for (auto &[resource, use] : resources) { + if (!use.write) continue; + if (use.upload) throw std::runtime_error("native UAV aliases an upload heap"); + D3D12_RESOURCE_BARRIER uav{}; + uav.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + uav.UAV.pResource = resource; + uavs.push_back(uav); + auto &ranges = use.intervals; + std::sort(ranges.begin(), ranges.end(), [](auto &a, auto &b) { return a.first < b.first; }); + for (size_t j = 0; j < ranges.size();) { + auto range = ranges[j++]; + while (j < ranges.size() && ranges[j].first <= range.end) { + if (ranges[j].write != range.write) { + if (ranges[j].first < range.end) + throw std::runtime_error("overlapping compute SRV and UAV subresource " + std::to_string(ranges[j].first)); + break; + } + range.end = (std::max)(range.end, ranges[j++].end); + } + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {resource, range.first, D3D12_RESOURCE_STATE_COMMON, + range.write ? D3D12_RESOURCE_STATE_UNORDERED_ACCESS : D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE}; + for (; b.Transition.Subresource < range.end; ++b.Transition.Subresource) + transitions.push_back(b); + } + } + } + bool mixed(ID3D12Resource *resource) const { + auto i = resources.find(resource); + return i != resources.end() && i->second.read && i->second.write; + } + template void whole_states(Apply apply) const { + for (const auto &[resource, use] : resources) + if (!use.upload) + apply(resource, use.write ? (use.read ? D3D12_RESOURCE_STATE_COMMON : D3D12_RESOURCE_STATE_UNORDERED_ACCESS) + : D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + } + const auto &split() const { return transitions; } + const auto &writes() const { return uavs; } + void reverse() { + for (auto &b : transitions) std::swap(b.Transition.StateBefore, b.Transition.StateAfter); + } +}; +} diff --git a/src/startup_stubs/native_global_srv.h b/src/startup_stubs/native_global_srv.h new file mode 100644 index 000000000..0ea0f62d9 --- /dev/null +++ b/src/startup_stubs/native_global_srv.h @@ -0,0 +1,148 @@ +#pragma once + +#include "native_buffer_stride.h" +#include +#include +#include +#include +#include +#include +#include + +// The view type of a global (descriptor heap) SRV slot that a dispatch can select from GPU data. +// +// A shader that picks its slot at run time can only be recorded and replayed if the type of every slot it may pick is +// known: the capture keeps {slot, type, stride} for each slot of the heap, and the dispatch is refused, before any +// shader runs, when the selected slot holds another type than the one the shader reads. No heap-indexed data read is +// translated here; this header only classifies, serializes and checks. +// +// A .views file describes the one dispatch it was captured from. It is not part of the .cdx/.root content key of the +// request it sits next to. +namespace x2w_startup { +enum class GlobalSrvType : unsigned { none, raw_buffer, structured_buffer, typed_buffer, texture }; + +inline const char *global_srv_type_name(GlobalSrvType type) { + switch (type) { + case GlobalSrvType::raw_buffer: return "raw_buffer"; + case GlobalSrvType::structured_buffer: return "structured_buffer"; + case GlobalSrvType::typed_buffer: return "typed_buffer"; + case GlobalSrvType::texture: return "texture"; + default: return "none"; + } +} + +inline GlobalSrvType global_srv_type_from_name(const std::string &name) { + for (auto type : {GlobalSrvType::raw_buffer, GlobalSrvType::structured_buffer, GlobalSrvType::typed_buffer, + GlobalSrvType::texture}) + if (name == global_srv_type_name(type)) return type; + return GlobalSrvType::none; +} + +struct GlobalSrvView { + unsigned slot = 0; + GlobalSrvType type = GlobalSrvType::none; + unsigned stride = 0; // Bytes per element for a buffer view (the value native_view_stride gives), 0 for a texture. + std::uint64_t bytes = 0; // Size of the buffer in bytes, 0 for a texture. Set by the caller from the resource description. +}; + +// Classifies the description a title passed for an SRV (slot 18 of the device interface). False: not a view this +// path can name (an unknown dimension, or a buffer view without a usable stride). +inline bool classify_global_srv_view(unsigned heap_slot, const void *bytes, std::size_t size, GlobalSrvView &view) { + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + if (!bytes || size < sizeof(desc)) return false; + std::memcpy(&desc, bytes, sizeof(desc)); + view = {}; + view.slot = heap_slot; + if (desc.ViewDimension == D3D12_SRV_DIMENSION_UNKNOWN) return false; + if (desc.ViewDimension != D3D12_SRV_DIMENSION_BUFFER) { + view.type = GlobalSrvType::texture; + return true; + } + if (!native_view_stride(18, bytes, size, view.stride)) return false; + view.type = desc.Buffer.StructureByteStride ? GlobalSrvType::structured_buffer + : (desc.Buffer.Flags & D3D12_BUFFER_SRV_FLAG_RAW) ? GlobalSrvType::raw_buffer + : GlobalSrvType::typed_buffer; + return true; +} + +// One request's view metadata, the text that travels with a captured request (req_.views). +struct GlobalSrvRequest { + unsigned selected = 0; + GlobalSrvType needed = GlobalSrvType::none; + std::vector views; + bool has_selected = false; +}; + +inline std::string encode_global_srv_request(const GlobalSrvRequest &request) { + std::ostringstream out; + out << "x2w-global-srv-views 2\nselect " << request.selected << "\nneed " << global_srv_type_name(request.needed) << '\n'; + for (const auto &view : request.views) + out << "slot " << view.slot << ' ' << global_srv_type_name(view.type) << ' ' << view.stride << ' ' << view.bytes << '\n'; + return out.str(); +} + +// False with a diagnostic in `error` for a text that cannot reconstruct the binding. +inline bool decode_global_srv_request(const std::string &text, GlobalSrvRequest &request, std::string &error) { + request = {}; + std::istringstream in(text); + std::string line; + if (!std::getline(in, line) || line != "x2w-global-srv-views 2") { + error = "global SRV view metadata has no 'x2w-global-srv-views 2' header"; + return false; + } + bool has_need = false; + while (std::getline(in, line)) { + std::istringstream fields(line); + std::string key; + fields >> key; + if (key.empty()) continue; + if (key == "select") { + if (!(fields >> request.selected)) { error = "global SRV view metadata: unreadable select line"; return false; } + request.has_selected = true; + } else if (key == "need") { + std::string name; + fields >> name; + request.needed = global_srv_type_from_name(name); + if (request.needed == GlobalSrvType::none) { + error = "global SRV view metadata: unknown needed view type '" + name + "'"; + return false; + } + has_need = true; + } else if (key == "slot") { + GlobalSrvView view; + std::string name; + if (!(fields >> view.slot >> name >> view.stride >> view.bytes)) { + error = "global SRV view metadata: unreadable slot line"; + return false; + } + view.type = global_srv_type_from_name(name); + if (view.type == GlobalSrvType::none) { + error = "global SRV slot " + std::to_string(view.slot) + " has unknown view type '" + name + "'"; + return false; + } + request.views.push_back(view); + } else { + error = "global SRV view metadata: unknown line '" + key + "'"; + return false; + } + } + if (!request.has_selected || !has_need) { + error = std::string("global SRV view metadata lacks the ") + (request.has_selected ? "needed view type" : "selected slot"); + return false; + } + return true; +} + +// Empty when the selected slot holds the type the shader reads. Otherwise the refusal text: it names the slot and the +// view types, and is produced before the shader runs. Used by the native recording and by the replay alike. +inline std::string refuse_global_srv_selection(const std::vector &views, unsigned selected, + GlobalSrvType needed) { + for (const auto &view : views) { + if (view.slot != selected) continue; + if (view.type == needed) return {}; + return "global SRV slot " + std::to_string(selected) + " has view type " + global_srv_type_name(view.type) + + ", the shader needs " + global_srv_type_name(needed); + } + return "global SRV slot " + std::to_string(selected) + " has no captured view type"; +} +} // namespace x2w_startup diff --git a/src/startup_stubs/native_recording.h b/src/startup_stubs/native_recording.h new file mode 100644 index 000000000..287cf5a18 --- /dev/null +++ b/src/startup_stubs/native_recording.h @@ -0,0 +1,52 @@ +#pragma once +#include +#include +#include +#include +#include +#include "native_copy_ranges.h" + +namespace x2w_startup { +struct NativeDescriptorTable { + ID3D12DescriptorHeap *heap{}; + D3D12_CPU_DESCRIPTOR_HANDLE cpu{}; + D3D12_GPU_DESCRIPTOR_HANDLE gpu{}; + UINT increment{}; +}; +// draw_lock protects recording and submission. Each reset starts a new +// allocation sequence. A closed recording and each of its submits own the +// same immutable tables, even when the command-list pointer is reused. +struct NativeRecording { + struct BufferCopy { + const void* owner; + std::uint64_t base, begin, end; + Microsoft::WRL::ComPtr resource; + }; + std::vector copies; + std::unordered_map> objects; + NativeDescriptorTable next; + UINT remaining = 0; + void retain(IUnknown *object) { objects.try_emplace(object, object); } + NativeDescriptorTable allocate(ID3D12Device *device, UINT count) { + if (!count) + return {}; + if (remaining < count) { + const UINT capacity = (std::max)(256u, count); + D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, capacity, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + Microsoft::WRL::ComPtr page; + if (FAILED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&page)))) + throw std::runtime_error("native descriptor page allocation failed"); + retain(page.Get()); + next = {page.Get(), page->GetCPUDescriptorHandleForHeapStart(), page->GetGPUDescriptorHandleForHeapStart(), + device->GetDescriptorHandleIncrementSize(desc.Type)}; + remaining = capacity; + } + auto table = next; + next.cpu.ptr += SIZE_T(count) * next.increment; + next.gpu.ptr += UINT64(count) * next.increment; + remaining -= count; + return table; + } +}; +} // namespace x2w_startup diff --git a/tests/checks/python-linux/native_f16_alu.txt b/tests/checks/python-linux/native_f16_alu.txt new file mode 100644 index 000000000..511eae460 --- /dev/null +++ b/tests/checks/python-linux/native_f16_alu.txt @@ -0,0 +1 @@ +tests/native_f16_alu_check.py model diff --git a/tests/cmake/native_align_bfm.cmake b/tests/cmake/native_align_bfm.cmake new file mode 100644 index 000000000..1cd0da59c --- /dev/null +++ b/tests/cmake/native_align_bfm.cmake @@ -0,0 +1,13 @@ +# Direct C++ compute: v_alignbit_b32, v_alignbyte_b32 and v_bfm_b32 (#2985). The controls compile and check the +# reference's mutants; the readback needs shader model 6.6 with wave32 and otherwise reports a skip (77). +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_align_bfm_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_align_bfm_check.py" controls + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_align_bfm_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_align_bfm_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_align_bfm_check.py" hardware + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_align_bfm_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_bytewin_store.cmake b/tests/cmake/native_bytewin_store.cmake new file mode 100644 index 000000000..e1239e016 --- /dev/null +++ b/tests/cmake/native_bytewin_store.cmake @@ -0,0 +1,11 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_bytewin_store_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_bytewin_store_check.py" controls + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_bytewin_store_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_bytewin_store_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_bytewin_store_check.py" hardware + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_bytewin_store_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_compile_dxil_refusals.cmake b/tests/cmake/native_compile_dxil_refusals.cmake new file mode 100644 index 000000000..8d41d0388 --- /dev/null +++ b/tests/cmake/native_compile_dxil_refusals.cmake @@ -0,0 +1,7 @@ +# Diagnostic .fail files and read-only --refusals census in compile_dxil (#2935). +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_compile_dxil_refusals COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_compile_dxil_refusals_check.py" + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_compile_dxil_refusals PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/native_compile_dxil_watch.cmake b/tests/cmake/native_compile_dxil_watch.cmake new file mode 100644 index 000000000..04f2c20e4 --- /dev/null +++ b/tests/cmake/native_compile_dxil_watch.cmake @@ -0,0 +1,7 @@ +# Continuous and one-shot --watch mode for compile_dxil (#2935). +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_compile_dxil_watch COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_compile_dxil_watch_check.py" + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_compile_dxil_watch PROPERTIES TIMEOUT 90) +endif() diff --git a/tests/cmake/native_cvt_pk16.cmake b/tests/cmake/native_cvt_pk16.cmake new file mode 100644 index 000000000..8a536d0bb --- /dev/null +++ b/tests/cmake/native_cvt_pk16.cmake @@ -0,0 +1,13 @@ +# Direct C++ compute: v_cvt_pk_u16_u32 and v_cvt_pk_i16_i32 (#2995). The controls compile and check the +# reference's mutants; the readback needs shader model 6.6 with wave32 and otherwise reports a skip (77). +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_cvt_pk16_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_cvt_pk16_check.py" controls + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_cvt_pk16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_cvt_pk16_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_cvt_pk16_check.py" hardware + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_cvt_pk16_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_cvt_pk_u8.cmake b/tests/cmake/native_cvt_pk_u8.cmake new file mode 100644 index 000000000..6b8b1fce2 --- /dev/null +++ b/tests/cmake/native_cvt_pk_u8.cmake @@ -0,0 +1,13 @@ +# Direct C++ compute: v_cvt_pk_u8_f32 (#2997). The controls compile and check the +# reference's mutants; the readback needs shader model 6.6 with wave32 and otherwise reports a skip (77). +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_cvt_pk_u8_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_cvt_pk_u8_check.py" controls + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_cvt_pk_u8_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_cvt_pk_u8_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_cvt_pk_u8_check.py" hardware + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_cvt_pk_u8_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_dpp_quad.cmake b/tests/cmake/native_dpp_quad.cmake new file mode 100644 index 000000000..e45b33e37 --- /dev/null +++ b/tests/cmake/native_dpp_quad.cmake @@ -0,0 +1,11 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_dpp_quad_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_dpp_quad_check.py" controls + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_dpp_quad_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_dpp_quad_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_dpp_quad_check.py" hardware + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_dpp_quad_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_dxil_llvm_ident.cmake b/tests/cmake/native_dxil_llvm_ident.cmake new file mode 100644 index 000000000..280f74fdc --- /dev/null +++ b/tests/cmake/native_dxil_llvm_ident.cmake @@ -0,0 +1,13 @@ +# Direct DXIL !llvm.ident metadata check and WARP/hardware draw verification (#2915). +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_dxil_llvm_ident_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_dxil_llvm_ident_check.py" container + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_dxil_llvm_ident_controls PROPERTIES TIMEOUT 60) + foreach(backend IN ITEMS warp hardware) + add_test(NAME native_dxil_llvm_ident_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_dxil_llvm_ident_check.py" draw + "$" "$" "${DXC_BIN_DIR}" ${backend}) + set_tests_properties(native_dxil_llvm_ident_${backend} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + endforeach() +endif() diff --git a/tests/cmake/native_f16_alu.cmake b/tests/cmake/native_f16_alu.cmake new file mode 100644 index 000000000..1e1e0944c --- /dev/null +++ b/tests/cmake/native_f16_alu.cmake @@ -0,0 +1,12 @@ +# v_add_f16, v_sub_f16, v_subrev_f16 and v_mul_f16 in the direct C++ compute path. +if(TARGET compile_dxil AND TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}") + add_executable(native_compute_ir_dump tests/native_compute_ir_dump.cpp) + target_include_directories(native_compute_ir_dump PRIVATE src) + target_link_libraries(native_compute_ir_dump PRIVATE x2w_shader_compiler d3d12 dxgi) + set_property(TARGET native_compute_ir_dump PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + add_test(NAME native_f16_alu_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_f16_alu_check.py" ir "$") + add_test(NAME native_f16_alu_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_f16_alu_check.py" gpu "$" "${DXC_BIN_DIR}") + set_tests_properties(native_f16_alu_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_gather_compare.cmake b/tests/cmake/native_gather_compare.cmake new file mode 100644 index 000000000..358d73691 --- /dev/null +++ b/tests/cmake/native_gather_compare.cmake @@ -0,0 +1,9 @@ +# Direct C++ image path: image_gather4_c_lz as textureGatherCmp (#2969). Module and refusal checks, then a graphics +# pipeline created on WARP through native_recording_check --graphics-sampler. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET compile_dxil AND TARGET native_recording_check AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_gather_compare_warp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_gather_compare_check.py" "$" + "${DXC_BIN_DIR}" "$") + set_tests_properties(native_gather_compare_warp PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) +endif() diff --git a/tests/cmake/native_global_load.cmake b/tests/cmake/native_global_load.cmake new file mode 100644 index 000000000..510f33660 --- /dev/null +++ b/tests/cmake/native_global_load.cmake @@ -0,0 +1,8 @@ +# Direct C++ compute: global_load_dword through a root SRV address (#2962). Refusals and the module's guards run +# everywhere; the dispatch readback needs shader model 6.6 with wave32 and otherwise reports a skip (77). +if(EXISTS "${INTAKE_PYTHON}" AND TARGET compile_dxil AND TARGET native_store_replay) + add_test(NAME native_global_load_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_global_load_check.py" "$" + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_global_load_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) +endif() diff --git a/tests/cmake/native_global_srv_heap_replay.cmake b/tests/cmake/native_global_srv_heap_replay.cmake new file mode 100644 index 000000000..b966866a6 --- /dev/null +++ b/tests/cmake/native_global_srv_heap_replay.cmake @@ -0,0 +1,15 @@ +# GPU-selected global SRV heap slot: record and offline request replay with captured view types (issue #2908). +# The fixture runs the native recording path (NativeRecording and NativeDispatchStates) and the compile_dxil request +# replay on the same accepted and refused selections. _warp skips (77): WARP has no 32-lane waves. +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll" AND EXISTS "${INTAKE_PYTHON}") + add_executable(native_global_srv_heap_replay tests/native_global_srv_heap_replay.cpp tests/desktop_gpu.cpp) + target_include_directories(native_global_srv_heap_replay PRIVATE src tests) + target_link_libraries(native_global_srv_heap_replay PRIVATE x2w_shader_compiler d3d12 dxgi d3dcompiler) + set_property(TARGET native_global_srv_heap_replay PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_global_srv_heap_replay_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_global_srv_heap_replay_check.py" + "$" "$" "${DXC_BIN_DIR}" ${adapter}) + set_tests_properties(native_global_srv_heap_replay_${adapter} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + endforeach() +endif() diff --git a/tests/cmake/native_graphics_vertex_vcc_join.cmake b/tests/cmake/native_graphics_vertex_vcc_join.cmake new file mode 100644 index 000000000..3ee4bfb29 --- /dev/null +++ b/tests/cmake/native_graphics_vertex_vcc_join.cmake @@ -0,0 +1,9 @@ +# A per-vertex VCC crosses a two-arm join in a translated vertex stage (#2906). +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + foreach(backend IN ITEMS warp hardware) + add_test(NAME native_graphics_vertex_vcc_join_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_graphics_vertex_vcc_join_check.py" "$" + "$" "${DXC_BIN_DIR}" ${backend}) + set_tests_properties(native_graphics_vertex_vcc_join_${backend} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + endforeach() +endif() diff --git a/tests/cmake/native_graphics_wqm.cmake b/tests/cmake/native_graphics_wqm.cmake new file mode 100644 index 000000000..aed792142 --- /dev/null +++ b/tests/cmake/native_graphics_wqm.cmake @@ -0,0 +1,11 @@ +# Cross-quad WQM/EXECZ in a native pixel draw (#2907). native_graphics_wqm_hardware stays in CMakeLists.txt. +# The WARP entry runs every case that one quad per wave can decide; the IR entry checks, without a GPU, that the +# vote's quad and wave operations are emitted before any branch. +if(TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_graphics_wqm_warp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_graphics_wqm_check.py" "$" + "$" "${DXC_BIN_DIR}" warp) + set_tests_properties(native_graphics_wqm_warp PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_test(NAME native_graphics_wqm_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_graphics_wqm_check.py" ir "$") +endif() diff --git a/tests/cmake/native_lane_access.cmake b/tests/cmake/native_lane_access.cmake new file mode 100644 index 000000000..4bd29c4d0 --- /dev/null +++ b/tests/cmake/native_lane_access.cmake @@ -0,0 +1,7 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_lane_access_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_lane_access_check.py" "$" + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_lane_access_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_lds_request.cmake b/tests/cmake/native_lds_request.cmake new file mode 100644 index 000000000..933e9be4c --- /dev/null +++ b/tests/cmake/native_lds_request.cmake @@ -0,0 +1,4 @@ +if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_lds_request COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_lds_request_check.py" "$" "${DXC_BIN_DIR}") +endif() diff --git a/tests/cmake/native_pack_b32_f16.cmake b/tests/cmake/native_pack_b32_f16.cmake new file mode 100644 index 000000000..0a1d5b0be --- /dev/null +++ b/tests/cmake/native_pack_b32_f16.cmake @@ -0,0 +1,12 @@ +# v_pack_b32_f16 in the direct C++ DXIL path: an IR check on pixel containers (no GPU) and a compute readback. +if(TARGET compile_dxil AND TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}") + add_executable(native_pixel_ir_dump tests/native_pixel_ir_dump.cpp) + target_include_directories(native_pixel_ir_dump PRIVATE src) + target_link_libraries(native_pixel_ir_dump PRIVATE x2w_shader_compiler d3d12 dxgi) + set_property(TARGET native_pixel_ir_dump PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + add_test(NAME native_pack_b32_f16_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_pack_b32_f16_check.py" ir "$") + add_test(NAME native_pack_b32_f16_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_pack_b32_f16_check.py" gpu "$" "${DXC_BIN_DIR}") + set_tests_properties(native_pack_b32_f16_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_rtv_variant.cmake b/tests/cmake/native_rtv_variant.cmake new file mode 100644 index 000000000..bdc28db6b --- /dev/null +++ b/tests/cmake/native_rtv_variant.cmake @@ -0,0 +1,15 @@ +# RTV variant requests (req_.rtv) resolved and cached by compile_dxil --requests (#2980). The controls need no +# device; the warp and hardware entries draw each variant through the stand-in and read the target back. +if(TARGET compile_dxil AND TARGET startup_stream_consumer AND EXISTS "${INTAKE_PYTHON}" + AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll" AND EXISTS "${DXC_BIN_DIR}/dxc.exe") + add_test(NAME native_rtv_variant_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_rtv_variant_check.py" controls + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_rtv_variant_controls PROPERTIES TIMEOUT 60) + foreach(backend IN ITEMS warp hardware) + add_test(NAME native_rtv_variant_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_rtv_variant_check.py" e2e + "$" "$" "${DXC_BIN_DIR}" ${backend}) + set_tests_properties(native_rtv_variant_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/native_sad.cmake b/tests/cmake/native_sad.cmake new file mode 100644 index 000000000..e190caa32 --- /dev/null +++ b/tests/cmake/native_sad.cmake @@ -0,0 +1,13 @@ +# Direct C++ compute: v_sad_u8, v_sad_hi_u8, v_sad_u16, v_sad_u32 and v_msad_u8 (#2987). The controls compile and check the +# reference's mutants; the readback needs shader model 6.6 with wave32 and otherwise reports a skip (77). +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_sad_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_sad_check.py" controls + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_sad_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_sad_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_sad_check.py" hardware + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_sad_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_salu64.cmake b/tests/cmake/native_salu64.cmake new file mode 100644 index 000000000..68deac535 --- /dev/null +++ b/tests/cmake/native_salu64.cmake @@ -0,0 +1,11 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_salu64_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_salu64_check.py" controls + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_salu64_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_salu64_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_salu64_check.py" hardware + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_salu64_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_sdwa_f16.cmake b/tests/cmake/native_sdwa_f16.cmake new file mode 100644 index 000000000..a1258520b --- /dev/null +++ b/tests/cmake/native_sdwa_f16.cmake @@ -0,0 +1,8 @@ +# SDWA binary16 arithmetic in the direct C++ compute path. +if(TARGET native_compute_ir_dump) + add_test(NAME native_sdwa_f16_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_sdwa_f16_check.py" ir "$") + add_test(NAME native_sdwa_f16_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_sdwa_f16_check.py" gpu "$" "${DXC_BIN_DIR}") + set_tests_properties(native_sdwa_f16_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_shift64.cmake b/tests/cmake/native_shift64.cmake new file mode 100644 index 000000000..4d1956cb9 --- /dev/null +++ b/tests/cmake/native_shift64.cmake @@ -0,0 +1,11 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_shift64_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_shift64_check.py" controls + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_shift64_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_shift64_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_shift64_check.py" hardware + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_shift64_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_signed_forms.cmake b/tests/cmake/native_signed_forms.cmake new file mode 100644 index 000000000..2866debfd --- /dev/null +++ b/tests/cmake/native_signed_forms.cmake @@ -0,0 +1,13 @@ +# Direct C++ compute: v_ashrrev_i64 and v_mad_i32_i24 (#2991). The controls compile and check the +# reference's mutants; the readback needs shader model 6.6 with wave32 and otherwise reports a skip (77). +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_signed_forms_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_signed_forms_check.py" controls + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_signed_forms_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_signed_forms_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_signed_forms_check.py" hardware + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_signed_forms_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_startup_request_cache.cmake b/tests/cmake/native_startup_request_cache.cmake new file mode 100644 index 000000000..1b88f24cf --- /dev/null +++ b/tests/cmake/native_startup_request_cache.cmake @@ -0,0 +1,15 @@ +# Startup request consumption and runtime cache publication for compile_dxil (#2933). +if(TARGET compile_dxil AND TARGET startup_stream_consumer AND TARGET offscreen_check + AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_startup_request_cache_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_startup_request_cache_check.py" controls + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_startup_request_cache_controls PROPERTIES TIMEOUT 60) + foreach(backend IN ITEMS warp hardware) + add_test(NAME native_startup_request_cache_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_startup_request_cache_check.py" e2e + "$" "$" + "$" "${DXC_BIN_DIR}" ${backend}) + set_tests_properties(native_startup_request_cache_${backend} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 90) + endforeach() +endif() diff --git a/tests/cmake/startup_compute_dispatch_native.cmake b/tests/cmake/startup_compute_dispatch_native.cmake new file mode 100644 index 000000000..cb7943b57 --- /dev/null +++ b/tests/cmake/startup_compute_dispatch_native.cmake @@ -0,0 +1,11 @@ +# A slot 67 request translated in-process by the C++ compiler (X2W_NATIVE_SHADERS) and dispatched through the +# stand-in. Without 32-lane waves the check verifies its refusals and exits 77. +if(TARGET x2w_shader_compiler AND TARGET startup_stream_consumer AND EXISTS "${INTAKE_PYTHON}" + AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_dispatch_native_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_native_check.py" + "$" "${DXC_BIN_DIR}" ${adapter}) + set_tests_properties(startup_compute_dispatch_native_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/native_adjacent_srv_check.py b/tests/native_adjacent_srv_check.py new file mode 100644 index 000000000..d2a8ae6dc --- /dev/null +++ b/tests/native_adjacent_srv_check.py @@ -0,0 +1,55 @@ +"""Check dynamic SRVs spanning adjacent ranges in a serialized guest root signature.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_scalar_lds_check import scalar, sop1, vmove + + +def main(gpu, sdk): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + # s4 and s5 are the two root tables. s6 holds group.x. The + # candidate span starts at slot 1, group 1 selects slot 2. + words = [sop1(3, 20, 4), sop1(3, 21, 128), sop1(3, 22, 5), sop1(3, 23, 128), + scalar(0xe, 11, 6, 129), scalar(0x1e, 11, 11, 133), + 0xf408040a, 0x16000020, 0xf408080b, 0xfa000000, + scalar(0x1e, 12, 6, 130), vmove(8, 12), sop1(3, 126, 129), vmove(3, 130), + 0xe0002000, 0x80040103, 0xe0701000, 0x80080108, 0xbf810000] + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1, 0, 0x80 | 6 << 1) + for name, second, reason in ( + ("append", "SRV(t18, space=2)", ""), + ("null", "SRV(t18, space=2)", ""), + ("reversed", "SRV(t18, space=2, offset=2)", ""), + ("hole", "SRV(t18, space=2, offset=3)", "exceeds its declared root range"), + ("uav", "UAV(u18, space=2, offset=2)", "overlaps a non-SRV root range")): + first = "SRV(t7, offset=1)" + ranges = second + "," + first if name == "reversed" else first + "," + second + src, root = work / "root.hlsl", work / "root.bin" + src.write_text(f'#define SIG "DescriptorTable({ranges}),DescriptorTable(UAV(u0))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, src], check=True) + marker = write_request(work, words, root.read_bytes(), sa) + dest = work / (name + ".bin") + mode = "--direct-null-srv" if name == "null" else "--direct" + result = subprocess.run([gpu, sdk, marker, work / "cache", "0", dest, mode], + capture_output=True, text=True) + if result.returncode == 77: + sys.exit(77) + if reason: + assert result.returncode and reason in result.stderr and not dest.exists(), result.stderr + continue + assert not result.returncode, (result.stdout, result.stderr) + expected = [0x69696969] * 2064 + expected[8:10] = [0x3f800000 + 256 * slot + 8 for slot in (1, 2)] + if name == "null": + expected[9] = 0 + actual = struct.unpack("<2064I", dest.read_bytes()) + assert list(actual) == expected, [(i, a, b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b][:10] + print("Both layouts selected distinct SRVs, a recorded null returned zero, and hole/UAV controls were refused.") + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/tests/native_align_bfm_check.py b/tests/native_align_bfm_check.py new file mode 100644 index 000000000..1dad65de7 --- /dev/null +++ b/tests/native_align_bfm_check.py @@ -0,0 +1,109 @@ +"""v_alignbit_b32, v_alignbyte_b32 and v_bfm_b32 in the direct compute path (#2985). + + native_align_bfm_check.py controls + native_align_bfm_check.py hardware + +The semantics are those of the gfx2hlsl.py VOP3 table: v_alignbit_b32 returns bits [k + 31 : k] of {S0, S1} with +k = S2[4:0], v_alignbyte_b32 the same with k = 8 * S2[1:0], and both return S1 for k = 0; v_bfm_b32 returns +((1 << S0[4:0]) - 1) << S1[4:0]. All words below were assembled with LLVM 15.0.7 (clang -cc1as, gfx1013). + +The dispatch has two groups of 32 lanes. Lane L of group g uses S0 = 0x89abcdef, S1 = 0x01234567 and +S2 = L + 32g, so every shift 0..31 and every byte count appears, and group 1 repeats them with bit 5 set, which +the five-bit field must ignore. v_bfm_b32 takes S0 = S2 and S1 = S2 ^ 0x15. Each lane stores the three results. +References with the zero shift not special-cased, with S0 and S1 exchanged, and with the field not masked must +each differ from the expected words. +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request + +# s_mov_b32 s20, s4 / s_mov_b32 s21, 0 / s_load_dwordx4 s[32:35], s[20:21], 0x20 / s_lshl_b32 s7, s5, 9 / +# s_lshl_b32 s8, s5, 5 / v_lshlrev_b32 v8, 4, v0 / v_add_nc_u32 v8, s7, v8 / v_add_nc_u32 v3, s8, v0 / +# v_mov_b32 v1, 0x89abcdef / v_mov_b32 v2, 0x1234567 / v_alignbit_b32 v4, v1, v2, v3 / +# v_alignbyte_b32 v5, v1, v2, v3 / v_xor_b32 v6, 0x15, v3 / v_bfm_b32 v7, v3, v6 / s_waitcnt lgkmcnt(0) / +# buffer_store_dword v4, v5, v7 at v8 + 0, 4, 8 through s[32:35] / s_endpgm +HEX = ('040394be 800395be 0a0808f4200000fa 0589078f 0585088f 84001034 0710104a 0800064a ff02027eefcdab89 ' + 'ff02047e67452301 04004ed501050e04 05004fd501050e04 95060c3a 070063d7030d0200 7fc08cbf ' + '001070e008040880 041070e008050880 081070e008070880 000081bf') +S0, S1 = 0x89ABCDEF, 0x01234567 +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 + + +def words(text): + out = [] + for h in text.split(): + out += [int.from_bytes(bytes.fromhex(h[i:i + 8]), 'little') for i in range(0, len(h), 8)] + return out + + +def align(high, low, k, zero_special=True): + """Bits [k + 31 : k] of {high, low}. Without the zero special case, a five-bit-masked 32 - k turns k = 0 into + low | high, the result of an unguarded lowering.""" + if k == 0 and not zero_special: + return low | high + return (((high << 32) | low) >> k) & 0xFFFFFFFF + + +def reference(zero_special=True, swapped=False, unmasked=False): + expected = [SENTINEL] * OUTPUT_WORDS + high, low = (S1, S0) if swapped else (S0, S1) + field = 63 if unmasked else 31 + for group in range(2): + for lane in range(32): + s2 = lane + 32 * group + bit = align(high, low, s2 & field, zero_special) + byte = align(high, low, 8 * (s2 & (7 if unmasked else 3)) % 64, zero_special) + bfm = (((1 << (s2 & field)) - 1) << ((s2 ^ 0x15) & field)) & 0xFFFFFFFF + base = GUARD_WORDS + (group * 32 + lane) * 4 + expected[base:base + 3] = [bit, byte, bfm] + return expected + + +def controls(cli, sdk, work, root): + marker = request(work, root, words(HEX)) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + expected = reference() + for label, mutant in (('zero shift not special-cased', reference(zero_special=False)), + ('S0 and S1 exchanged', reference(swapped=True)), + ('field not masked to five bits', reference(unmasked=True))): + assert mutant != expected, label + print('compiled; the zero-shift, exchanged-source and unmasked references each differ from the expected words') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, words(HEX)) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = list(struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes())) + expected = reference() + diff = [(i, hex(a), hex(b)) for i, (a, b) in enumerate(zip(actual, expected)) if a != b] + assert not diff, diff[:10] + print('v_alignbit_b32, v_alignbyte_b32 and v_bfm_b32: 192 words of two groups and the guards matched') + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_buffered_vertex_gpu.cpp b/tests/native_buffered_vertex_gpu.cpp new file mode 100644 index 000000000..f2b126a69 --- /dev/null +++ b/tests/native_buffered_vertex_gpu.cpp @@ -0,0 +1,250 @@ +#include "desktop_gpu.h" +#include "gfx1013_vertex_id.h" +#include "shader_dxil_compiler.h" +#include "xmem_test_device.h" +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; +using Position = std::array; +using Bytes = std::vector; +using Word = std::uint32_t; +namespace fs = std::filesystem; + +namespace { +template Bytes bytes_of(const std::vector &input) { + auto begin = reinterpret_cast(input.data()); + return {begin, begin + input.size() * sizeof(T)}; +} +struct Case { + std::string program, bindings; + std::array entry{}; + std::vector buffers; + Bytes indices; + std::vector expected; +}; +Case fixture(bool overwrite_descriptor = false) { + Case data; + // Different SGPRs, VB descriptor position, root-table number and byte offset + // from the buffered draw. Use a nonzero base vertex and a vertex byte offset. + std::vector words{0xbe980308, + 0xbe990380, // s24 = table0, s25 = 0 + 0xbe9a0400, + 0x939bff1b, + 0x00080000, // vertex table s[26:27], mask high + 0xf4080000u | (32u << 6) | 12u, + 0xfa000040, + 0xf4080000u | (40u << 6) | 13u, + 0xfa000000, + 0x4a000002, // v0 += s2 + 0xe03c2004, + 0x800a0600, // x/y/z at stride*id + 4 + 0xf4280000u | (32u << 6) | 16u, + 0xfa000010, // replace descriptor with 4 values + 0xd5030009, + 32u | (262u << 9), // x + constant.x + 0xd54b000a, + 242u | (263u << 9) | (33u << 18) | (1u << 31), // y - constant.y + 0x7e1602f2, // w = 1 + 0xf80008cf, + 0x0b080a09, + 0xf8000201, + 0x80808009, + 0xbf810000}; + if (overwrite_descriptor) { + // Overwrite word 2 of the vertex descriptor before the first vertex load. + const auto load = std::find(words.begin(), words.end(), Word{0xe03c2004}); + words.insert(load, 0xbeaa0380); + } + data.program.assign(reinterpret_cast(words.data()), words.size() * sizeof(Word)); + data.entry = {0, 1, 0, 16}; + data.buffers = {bytes_of(std::vector{99, 99, 99, 99, 7, 1, 2, 3, 7, 4, 5, 6, 7, 7, 8, 9}), + bytes_of(std::vector{0, 0, 0, 0, .5f, 1.5f, 2, 1})}; + data.indices = bytes_of(std::vector{1, 0, 2, 2, 0, 1}); + data.expected = {{4.5f, 3.5f, 6, 1}, {1.5f, .5f, 3, 1}, {7.5f, 6.5f, 9, 1}, + {7.5f, 6.5f, 9, 1}, {1.5f, .5f, 3, 1}, {4.5f, 3.5f, 6, 1}}; + data.bindings = "srv 0 buf vb 0\nsrv 1 buf table 0 64\n"; + return data; +} +Bytes read_file(const fs::path &path) { + std::ifstream file(path, std::ios::binary); + if (!file) throw std::runtime_error("missing replay input: " + path.filename().string()); + return {std::istreambuf_iterator(file), {}}; +} +Case load(const fs::path &dir) { + Case data; + auto program = read_file(dir / "program.bin"), bindings = read_file(dir / "bindings.txt"); + data.program.assign(program.begin(), program.end()); + data.bindings.assign(bindings.begin(), bindings.end()); + data.indices = read_file(dir / "indices.bin"); + auto entry = read_file(dir / "entry.bin"), expected = read_file(dir / "positions.bin"); + if (entry.size() != sizeof(data.entry) || expected.empty() || expected.size() % sizeof(Position) || + expected.size() / sizeof(Position) * 2 != data.indices.size()) + throw std::runtime_error("invalid replay dimensions"); + std::memcpy(data.entry.data(), entry.data(), entry.size()); + data.expected.resize(expected.size() / sizeof(Position)); + std::memcpy(data.expected.data(), expected.data(), expected.size()); + for (unsigned i = 0; i < 32; ++i) { + auto path = dir / ("t" + std::to_string(i) + ".bin"); + if (!fs::exists(path)) break; + data.buffers.push_back(read_file(path)); + } + return data; +} +ComPtr upload(ID3D12Device *device, const Bytes &bytes) { + auto obj = make_buffer(device, bytes.size(), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + void *mapped = nullptr; + check(obj->Map(0, nullptr, &mapped), "map upload"); + std::memcpy(mapped, bytes.data(), bytes.size()); + obj->Unmap(0, nullptr); + return obj; +} +void verify(ID3D12Device *dev, const Bytes &vs, const Case &data) { + if (data.buffers.empty() || data.buffers.size() > 32) throw std::runtime_error("invalid descriptor count"); + const UINT count = static_cast(data.buffers.size()); + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, count, 0, 0, 0}; + D3D12_ROOT_PARAMETER params[2]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants.Num32BitValues = 4; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[1].DescriptorTable = {1, &range}; + D3D12_ROOT_SIGNATURE_DESC root_desc{2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_STREAM_OUTPUT}; + ComPtr serialized; + check(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &serialized, nullptr), + "serialize SO root"); + ComPtr root; + check(dev->CreateRootSignature(0, serialized->GetBufferPointer(), serialized->GetBufferSize(), + IID_PPV_ARGS(&root)), + "SO root"); + D3D12_SO_DECLARATION_ENTRY output{0, "SV_Position", 0, 0, 4, 0}; + const UINT stride = sizeof(Position); + D3D12_GRAPHICS_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = root.Get(); + pso.VS = {vs.data(), vs.size()}; + pso.StreamOutput = {&output, 1, &stride, 1, D3D12_SO_NO_RASTERIZED_STREAM}; + pso.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pso.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pso.RasterizerState.DepthClipEnable = TRUE; + pso.SampleMask = UINT_MAX; + pso.SampleDesc.Count = 1; + pso.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + ComPtr pipeline; + const auto pso_start = std::chrono::steady_clock::now(); + check(dev->CreateGraphicsPipelineState(&pso, IID_PPV_ARGS(&pipeline)), "SO graphics pipeline"); + const auto pso_time = std::chrono::steady_clock::now() - pso_start; + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, count, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr heap; + check(dev->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)), "SRV heap"); + auto dest = heap->GetCPUDescriptorHandleForHeapStart(); + std::vector> buffers; + for (const auto &bytes : data.buffers) { + if (bytes.empty() || bytes.size() % 4) throw std::runtime_error("invalid raw SRV length"); + buffers.push_back(upload(dev, bytes)); + D3D12_SHADER_RESOURCE_VIEW_DESC view{}; + view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view.Format = DXGI_FORMAT_R32_TYPELESS; + view.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + view.Buffer.NumElements = static_cast(bytes.size() / 4); + view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + dev->CreateShaderResourceView(buffers.back().Get(), &view, dest); + dest.ptr += dev->GetDescriptorHandleIncrementSize(heap_desc.Type); + } + auto ib = upload(dev, data.indices), zero = upload(dev, Bytes(16)); + D3D12_INDEX_BUFFER_VIEW index{ib->GetGPUVirtualAddress(), static_cast(data.indices.size()), + DXGI_FORMAT_R16_UINT}; + const UINT64 payload = data.expected.size() * sizeof(Position); + auto out = make_buffer(dev, 16 + payload, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST); + auto readback = make_buffer(dev, 16 + payload, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + ComputeCommands commands(dev, pipeline.Get(), D3D12_COMMAND_LIST_TYPE_DIRECT); + auto *list = commands.list.Get(); + D3D12_QUERY_HEAP_DESC queries{D3D12_QUERY_HEAP_TYPE_TIMESTAMP, 2, 0}; + ComPtr timestamps; + check(dev->CreateQueryHeap(&queries, IID_PPV_ARGS(×tamps)), "draw timestamps"); + auto timing = make_buffer(dev, 2 * sizeof(UINT64), D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + UINT64 frequency = 0; + check(commands.queue->GetTimestampFrequency(&frequency), "timestamp frequency"); + list->CopyBufferRegion(out.Get(), 0, zero.Get(), 0, 16); + transition(list, out.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_STREAM_OUT); + D3D12_STREAM_OUTPUT_BUFFER_VIEW so{out->GetGPUVirtualAddress() + 16, payload, out->GetGPUVirtualAddress()}; + list->SOSetTargets(0, 1, &so); + list->SetGraphicsRootSignature(root.Get()); + ID3D12DescriptorHeap *heaps[]{heap.Get()}; + list->SetDescriptorHeaps(1, heaps); + list->SetGraphicsRoot32BitConstants(0, 4, data.entry.data(), 0); + list->SetGraphicsRootDescriptorTable(1, heap->GetGPUDescriptorHandleForHeapStart()); + list->IASetIndexBuffer(&index); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->EndQuery(timestamps.Get(), D3D12_QUERY_TYPE_TIMESTAMP, 0); + list->DrawIndexedInstanced(static_cast(data.indices.size() / 2), 1, 0, 0, 0); + list->EndQuery(timestamps.Get(), D3D12_QUERY_TYPE_TIMESTAMP, 1); + list->ResolveQueryData(timestamps.Get(), D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, timing.Get(), 0); + transition(list, out.Get(), D3D12_RESOURCE_STATE_STREAM_OUT, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyResource(readback.Get(), out.Get()); + commands.submit_and_wait(dev); + void *memory = nullptr; + D3D12_RANGE read{0, static_cast(16 + payload)}; + check(readback->Map(0, &read, &memory), "map SO result"); + UINT64 written = 0; + std::memcpy(&written, memory, sizeof(written)); + if (written != payload) throw std::runtime_error("wrong output vertex count"); + const auto *actual = reinterpret_cast(static_cast(memory) + 16); + double max_error = 0; + unsigned identical = 0; + for (size_t v = 0; v < data.expected.size(); ++v) + for (unsigned c = 0; c < 4; ++c) { + const float a = actual[v][c], e = data.expected[v][c]; + if (!std::isfinite(a) || !std::isfinite(e) || std::abs(a - e) > 1.e-5f * (std::max)(std::abs(e), 1.0f)) + throw std::runtime_error("position mismatch at vertex " + std::to_string(v) + " component " + + std::to_string(c) + " actual=" + std::to_string(a) + + " expected=" + std::to_string(e)); + identical += !std::memcmp(&a, &e, sizeof(a)); + max_error = (std::max)(max_error, std::abs(double(a) - e)); + } + D3D12_RANGE none{}; + readback->Unmap(0, &none); + D3D12_RANGE time_range{0, 2 * sizeof(UINT64)}; + check(timing->Map(0, &time_range, &memory), "read timestamps"); + const auto *ticks = static_cast(memory); + if (!frequency || ticks[1] < ticks[0]) throw std::runtime_error("invalid GPU timestamps"); + std::printf("pso_ms=%.6f draw_gpu_us=%.6f\n", std::chrono::duration(pso_time).count(), + 1e6 * double(ticks[1] - ticks[0]) / frequency); + timing->Unmap(0, &none); + std::printf("%zu indexed vertices, %u/%zu identical components, max absolute error %.9g\n", + data.expected.size(), identical, data.expected.size() * 4, max_error); +} +} // namespace +int wmain(int argc, wchar_t **argv) { + if (argc != 4 && argc != 5) return 2; + try { + bool unmatched = false; + const auto dev = create_device(std::wstring_view(argv[1]) == L"warp", unmatched); + if (!dev) return unmatched ? 1 : 77; + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_0}; + if (FAILED(dev->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &model, sizeof(model))) || + model.HighestShaderModel < D3D_SHADER_MODEL_6_0) + return 77; + auto data = argc == 5 ? load(argv[4]) : fixture(); + if (argc == 4) { + bool refused = false; + try { + x2w::translate_gfx1013_buffered_vertex(fixture(true).program); + } catch (const std::runtime_error &error) { + refused = std::strstr(error.what(), "overwritten buffer descriptor") != nullptr; + } + if (!refused) throw std::runtime_error("accepted overwritten vertex descriptor or wrong diagnostic"); + } + const auto program = x2w::translate_gfx1013_buffered_vertex(data.program); + if (program.bindings != data.bindings) throw std::runtime_error("vertex resource manifest mismatch"); + x2w::ShaderDxilCompiler compiler(argv[2]); + verify(dev.Get(), compiler.compile(program.hlsl, L"vs_6_0", argv[3]).dxil, data); + } catch (const std::exception &error) { + std::fprintf(stderr, "%s\n", error.what()); + return 1; + } +} diff --git a/tests/native_bytewin_store_check.py b/tests/native_bytewin_store_check.py new file mode 100644 index 000000000..099255a58 --- /dev/null +++ b/tests/native_bytewin_store_check.py @@ -0,0 +1,107 @@ +"""Read back direct compute byte-window stores and check descriptor refusals.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import scalar, sop1 + + +LANES = 64 +LANE_BYTES = 16 +PLANE_BYTES = LANES * LANE_BYTES +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 +SENTINEL = 0x69696969 +STORE_OPS = (0xE0701000, 0xE0741000, 0xE07C1000, 0xE0781000) + + +def compute_program(*, constant_stride=False, foreign_word=False, oob=0x30000000, ops=STORE_OPS): + # Root table 0 is in s4. Load slot 1 into s[8:11] through s[20:21]. + program = [sop1(3, 20, 4), sop1(3, 21, 128), 0xF4080000 | 8 << 6 | 10, 0xFA000020] + count_word = 10 + stride_word = 9 + if foreign_word: + # Give word 2 a valid byte_count proof, but from slot 2. + program += [0xF4080000 | 12 << 6 | 10, 0xFA000040] + count_word = 14 + stride_word = 13 + program += [ + scalar(0x27, 18, stride_word, 255), 0xE0010, # s_bfe_u32: extract the stride + scalar(0x09, 18, 18, 129), # s_max_u32: clamp the stride to 1 + scalar(0x0E, 9, 9, 255), 0xC000FFFF, # s_and_b32: clear the stride + ] + if constant_stride: + program += [sop1(3, 22, 132)] # Plain SGPR constant 4. + program += [ + scalar(0x26, 10, count_word, 22 if constant_stride else 18), # s_mul_i32 + scalar(0x10, 11, 11, 255), oob, # s_or_b32 + ] + + # v8 = 512 * group.x + 16 * lane.x. The replay view begins after its leading guard. + program += [scalar(0x1E, 7, 5, 137), vop2(0x1A, 8, 132, 0), vop2(0x25, 8, 7, 8)] + for component in range(4): + program.append(vop2(0x25, 2 + component, 129 + component, 8)) + # One 1024-byte plane per width. The last immediate is 3072, within 12 bits. + for plane, opcode in enumerate(ops): + program += [opcode | plane * PLANE_BYTES, 0x80020208] + return program + [0xBF810000] + + +def controls(cli, sdk, work, root): + # Manual mutants that must fail: dropping the clamped-stride proof must + # accept the constant; ignoring descriptor identity must accept the foreign word. + for name, program, errors in ( + ("constant stride", compute_program(constant_stride=True), + ("unbound numeric SGPR s10", "non-contiguous resource descriptor")), + ("foreign word 2", compute_program(foreign_word=True), ("non-contiguous resource descriptor",)), + ("wrong OOB bits", compute_program(oob=0x20000000), + ("unbound numeric SGPR s11", "non-contiguous resource descriptor")), + # Only stores accept the byte window; buffer_atomic_add through it stays refused. + ("atomic through byte window", compute_program(ops=(0xE0C81000,)), ("non-contiguous resource descriptor",))): + marker = request(work, root, program) + output = marker.with_suffix(".cso") + result = subprocess.run([cli, sdk, work / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True) + assert result.returncode and any(error in result.stderr for error in errors), (name, result.stderr) + assert not output.exists(), output + print(f"{name}: refused") + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, compute_program()) + output = work / "out.bin" + result = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + expected = [SENTINEL] * OUTPUT_WORDS + for plane, width in enumerate(range(1, 5)): + for lane in range(LANES): + start = GUARD_WORDS + (plane * PLANE_BYTES + lane * LANE_BYTES) // 4 + expected[start:start + width] = [LANE_BYTES * lane + j + 1 for j in range(width)] + for word, (got, want) in enumerate(zip(actual, expected)): + assert got == want, (word, hex(got), hex(want)) + print("All four store widths, unwritten words and guards matched") + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / "root.hlsl" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, shader], check=True) + return {"controls": controls, "hardware": hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_compile_dxil_refusals_check.py b/tests/native_compile_dxil_refusals_check.py new file mode 100644 index 000000000..97f0e6c9e --- /dev/null +++ b/tests/native_compile_dxil_refusals_check.py @@ -0,0 +1,297 @@ +"""Diagnostic .fail lifecycle and read-only --refusals summary checks for compile_dxil (#2935). + +usage: + native_compile_dxil_refusals_check.py +""" +import json +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +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 triage_run # noqa: E402 +from native_rtv_variant_check import FLOAT32, UINT16, UNORM8, pixel_stage, put_variant # noqa: E402 +from native_startup_request_cache_check import ( # noqa: E402 + COMPUTE_GROUP, + COMPUTE_RSRC2, + DECOY_MASKS, + TARGET_MASKS, + VS_WORDS, + compile_compute_root, + compile_graphics_table_root, + compute_program_words, + ps_words, + put_compute_request, + put_graphics_request, + stream_vertex_container, +) +from startup_compute_translate_check import state_a # noqa: E402 + + +def snapshot_tree(root: Path) -> dict[str, tuple[int, int]]: + snap: dict[str, tuple[int, int]] = {} + for p in sorted(root.rglob("*")): + st = p.stat() + snap[p.relative_to(root).as_posix()] = (st.st_size, st.st_mtime_ns) + return snap + + +def main(argv: list[str]) -> int: + if len(argv) != 2: + raise SystemExit(__doc__) + cli = Path(argv[0]) + sdk = Path(argv[1]) + + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + frontend = work / "frontend" + g_root = compile_graphics_table_root(sdk, work) + c_root = compile_compute_root(sdk, work) + c_code = compute_program_words() + c_sa = state_a(COMPUTE_GROUP, COMPUTE_RSRC2) + + # 1. Batch --requests writes .fail on refusal and removes stale .fail on subsequent success. + cache = work / "batch_cache" + cache.mkdir() + valid_gfx = put_graphics_request(cache, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + bad_vgpr2 = put_graphics_request(cache, VS_WORDS, ps_words(2), g_root, (0x0002, 0x8002)) + bad_decode_gfx = put_graphics_request( + cache, VS_WORDS, struct.pack("<2I", 0xFFFFFFFF, 0xBF810000), g_root, DECOY_MASKS + ) + # Pre-seed a stale .fail beside a valid request to verify --requests deletes it upon success. + stale_fail = cache / f"{valid_gfx:016x}.fail" + stale_fail.write_text("stale failure\n", encoding="utf-8") + + g_res = subprocess.run( + [cli, sdk, frontend, "--jobs", "2", "gfx1013-container-pair", "--requests", cache, cache], + capture_output=True, + text=True, + ) + assert g_res.returncode != 0 and "requests=3 compiled=1 refused=2" in g_res.stdout, ( + g_res.returncode, g_res.stdout, g_res.stderr + ) + assert (cache / f"{valid_gfx:016x}.txt").is_file() + assert not stale_fail.exists(), "stale .fail survived successful compilation" + for bad_key in (bad_vgpr2, bad_decode_gfx): + fail_file = cache / f"{bad_key:016x}.fail" + assert fail_file.is_file(), f"missing .fail for refused graphics request {bad_key:016x}" + fail_text = fail_file.read_text(encoding="utf-8") + assert fail_text.endswith("\n") and len(fail_text.splitlines()) == 1 and fail_text.strip(), repr(fail_text) + assert not (cache / f"{bad_key:016x}.txt").exists() + assert not (cache / f"{bad_key:016x}.vs.cso").exists() + assert not (cache / f"{bad_key:016x}.ps.cso").exists() + + valid_cs = put_compute_request(cache, c_code, c_root, c_sa) + bad_cs_decode = put_compute_request( + cache, c_code[:-4] + struct.pack("<2I", 0xFFFFFFFF, 0xBF810000), c_root, c_sa + ) + stale_cs_fail = cache / f"{valid_cs:016x}.fail" + stale_cs_fail.write_text("stale compute failure\n", encoding="utf-8") + + c_res = subprocess.run( + [cli, sdk, frontend, "--jobs", "2", "gfx1013-direct-cs@0", "--requests", cache, cache], + capture_output=True, + text=True, + ) + assert c_res.returncode != 0 and "requests=2 compiled=1 refused=1" in c_res.stdout, ( + c_res.returncode, c_res.stdout, c_res.stderr + ) + assert (cache / f"{valid_cs:016x}.txt").is_file() + assert not stale_cs_fail.exists(), "stale compute .fail survived successful compilation" + cs_fail = cache / f"{bad_cs_decode:016x}.fail" + assert cs_fail.is_file() + assert "unknown gfx1013 instruction format" in cs_fail.read_text(encoding="utf-8") + assert not (cache / f"{bad_cs_decode:016x}.txt").exists() + assert not (cache / f"{bad_cs_decode:016x}.cs.cso").exists() + + # Verify triage_run.py ingests and classifies the native .fail files cleanly. + log_dir = work / "logs" + log_dir.mkdir() + (log_dir / "stderr.txt").write_text("", encoding="utf-8") + triage_report = triage_run.triage_run(log_dir, shader_cache=cache) + assert "`X2W_SHADER_CACHE` `.fail` shaders: `3`" in triage_report, triage_report + assert "| 1 | `unsupported pixel entry VGPR` |" in triage_report, triage_report + assert "| 1 | `undecodable word` |" in triage_report, triage_report + assert "| 1 | `compute: undecodable word` |" in triage_report, triage_report + + # Mutate the valid graphics request into a key mismatch and re-run: old .txt must vanish and .fail appear. + (cache / f"req_{valid_gfx:016x}.b").write_bytes(ps_words(2)) + stale_run = subprocess.run( + [cli, sdk, frontend, "gfx1013-container-pair", "--requests", cache, cache], + capture_output=True, + text=True, + ) + assert stale_run.returncode != 0 + assert not (cache / f"{valid_gfx:016x}.txt").exists(), "refused re-run kept stale manifest" + assert "stale pixel input description" in (cache / f"{valid_gfx:016x}.fail").read_text(encoding="utf-8") + + # 2. Read-only --refusals summary across graphics (.a) and slot-67 compute (.c67) requests. + req_dir = work / "refusals_dir" + req_dir.mkdir() + g_ok = put_graphics_request(req_dir, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + # Two distinct VGPR-disabled failures (VGPR 2 and VGPR 4) should normalize and group together. + g_vgpr2 = put_graphics_request(req_dir, VS_WORDS, ps_words(2), g_root, (0x0002, 0x8002)) + g_vgpr4 = put_graphics_request(req_dir, VS_WORDS, ps_words(4), g_root, (0x0002, 0x8006)) + # Two undecodable graphics failures at different byte offsets (0 and 4) should group together. + g_dec0 = put_graphics_request(req_dir, VS_WORDS, struct.pack("<2I", 0xFFFFFFFF, 0xBF810000), g_root, DECOY_MASKS) + g_dec4 = put_graphics_request( + req_dir, VS_WORDS, struct.pack("<3I", 0xBF800000, 0xFFFFFFFF, 0xBF810000), g_root, DECOY_MASKS + ) + # Unsupported instruction with a distinct hex encoding (s_trap 0x1234 -> 0xbf921234). + g_trap = put_graphics_request( + req_dir, VS_WORDS, struct.pack("<3I", 0xBF921234, 0xF800180F, 0x04040404), g_root, TARGET_MASKS + ) + + c_ok = put_compute_request(req_dir, c_code, c_root, c_sa) + c_dec = put_compute_request( + req_dir, c_code[:-4] + struct.pack("<2I", 0xFFFFFFFF, 0xBF810000), c_root, c_sa + ) + c_key_bad = put_compute_request(req_dir, c_code, c_root, c_sa, override_key=c_ok ^ 1) + + before_snap = snapshot_tree(req_dir) + r1 = subprocess.run( + [cli, "--refusals", req_dir, "--json"], + capture_output=True, + text=True, + check=True, + ) + r2 = subprocess.run( + [cli, "--refusals", req_dir, "--jobs", "3", "--json"], + capture_output=True, + text=True, + check=True, + ) + r_text = subprocess.run( + [cli, "--refusals", req_dir, "--jobs", "2"], + capture_output=True, + text=True, + check=True, + ) + after_snap = snapshot_tree(req_dir) + assert before_snap == after_snap, "read-only --refusals modified the request directory" + + assert r1.stdout == r2.stdout, (r1.stdout, r2.stdout) + parsed = json.loads(r1.stdout) + assert parsed["graphics"]["examined"] == 6, parsed + assert parsed["graphics"]["no_refusal"] == 1, parsed + assert parsed["graphics"]["refused"] == 5, parsed + gfx_reasons = {row["reason"]: row["count"] for row in parsed["graphics"]["reasons"]} + assert gfx_reasons.get("unsupported pixel entry VGPR N") == 2, gfx_reasons + assert gfx_reasons.get("unknown gfx1013 instruction format at byte N") == 2, gfx_reasons + assert len(gfx_reasons) == 3 and sum(gfx_reasons.values()) == 5, gfx_reasons + + assert parsed["compute"]["examined"] == 3, parsed + assert parsed["compute"]["no_refusal"] == 1, parsed + assert parsed["compute"]["refused"] == 2, parsed + cs_reasons = {row["reason"]: row["count"] for row in parsed["compute"]["reasons"]} + assert cs_reasons == { + "compute request key mismatch": 1, + "unknown gfx1013 instruction format at byte N": 1, + }, cs_reasons + + # Negative control: hex words, PCs, and request keys must not appear in the census output. + for forbidden in ( + f"{g_ok:016x}", + f"{g_vgpr2:016x}", + f"{g_vgpr4:016x}", + f"{g_dec0:016x}", + f"{g_dec4:016x}", + f"{g_trap:016x}", + f"{c_dec:016x}", + f"{c_key_bad:016x}", + "bf921234", + "1234", + "+0x", + ): + assert forbidden not in r1.stdout.lower() and forbidden not in r_text.stdout.lower(), ( + forbidden, r1.stdout, r_text.stdout + ) + + for expected_line in ( + "Graphics requests", + "Requests examined: 6", + "No refusal recorded (not compiled): 1", + "Refused: 5", + "2\tunsupported pixel entry VGPR N", + "2\tunknown gfx1013 instruction format at byte N", + "Compute requests (device slot 67)", + "Compute requests examined: 3", + "No refusal recorded (not compiled): 1", + "Refused: 2", + "1\tcompute request key mismatch", + ): + assert expected_line in r_text.stdout, (expected_line, r_text.stdout) + + # Empty directory is valid and reports 0 examined. + empty_dir = work / "empty" + empty_dir.mkdir() + r_empty = subprocess.run([cli, "--refusals", empty_dir, "--json"], capture_output=True, text=True, check=True) + empty_json = json.loads(r_empty.stdout) + assert empty_json == { + "graphics": {"examined": 0, "no_refusal": 0, "refused": 0, "reasons": []}, + "compute": {"examined": 0, "no_refusal": 0, "refused": 0, "reasons": []}, + }, empty_json + + # RTV variant requests (.rtv): valid + refused variants, read-only guarantee, and same-key dedup. + rtv_dir = work / "rtv_refusals" + rtv_dir.mkdir() + rtv_base = put_graphics_request(rtv_dir, stream_vertex_container(), pixel_stage(), g_root) + rtv_u16, _ = put_variant(rtv_dir, rtv_base, (UINT16, UNORM8)) + rtv_f32, _ = put_variant(rtv_dir, rtv_base, (FLOAT32,)) + rtv_forged, _ = put_variant(rtv_dir, rtv_base, (UINT16,), name_key=0x1111222233334444) + rtv_missing, _ = put_variant(rtv_dir, 0x9999888877776666, (UINT16,)) + rtv_bad_fmt, _ = put_variant(rtv_dir, rtv_base, (7,)) + + rtv_before = snapshot_tree(rtv_dir) + r_rtv1 = subprocess.run([cli, "--refusals", rtv_dir, "--json"], capture_output=True, text=True, check=True) + r_rtv2 = subprocess.run( + [cli, "--refusals", rtv_dir, "--jobs", "2", "--json"], capture_output=True, text=True, check=True + ) + assert snapshot_tree(rtv_dir) == rtv_before, "--refusals modified RTV request directory" + assert r_rtv1.stdout == r_rtv2.stdout, (r_rtv1.stdout, r_rtv2.stdout) + rtv_json = json.loads(r_rtv1.stdout) + assert rtv_json["graphics"]["examined"] == 6, rtv_json + assert rtv_json["graphics"]["no_refusal"] == 3, rtv_json + assert rtv_json["graphics"]["refused"] == 3, rtv_json + for variant_key in (rtv_base, rtv_u16, rtv_f32, rtv_forged, rtv_missing, rtv_bad_fmt): + assert f"{variant_key:016x}" not in r_rtv1.stdout.lower(), (variant_key, r_rtv1.stdout) + + dedupe_dir = work / "rtv_dedupe" + dedupe_dir.mkdir() + dedupe_key = put_graphics_request(dedupe_dir, stream_vertex_container(), pixel_stage(), g_root) + put_variant(dedupe_dir, dedupe_key, (UINT16,), name_key=dedupe_key) + r_dedupe = subprocess.run([cli, "--refusals", dedupe_dir, "--json"], capture_output=True, text=True, check=True) + dedupe_json = json.loads(r_dedupe.stdout) + assert dedupe_json["graphics"] == { + "examined": 1, + "no_refusal": 0, + "refused": 1, + "reasons": [{"reason": "invalid RTV variant request", "count": 1}], + }, dedupe_json + + # 3. Negative controls for invalid --refusals CLI invocations. + bad_file = work / "not_a_dir.txt" + bad_file.write_text("x", encoding="utf-8") + for bad_args in ( + ["--refusals"], + ["--refusals", work / "missing_dir"], + ["--refusals", bad_file], + ["--refusals", req_dir, "--jobs", "0"], + ["--refusals", req_dir, "--jobs", "65"], + ["--refusals", req_dir, "--bogus"], + ): + res = subprocess.run([cli, *bad_args], capture_output=True, text=True) + assert res.returncode != 0 and res.stderr.strip(), (bad_args, res.returncode, res.stdout, res.stderr) + + print("native_compile_dxil_refusals checks: PASS (.fail lifecycle, triage_run classification, and read-only --refusals summary)") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/tests/native_compile_dxil_watch_check.py b/tests/native_compile_dxil_watch_check.py new file mode 100644 index 000000000..4f5b61a71 --- /dev/null +++ b/tests/native_compile_dxil_watch_check.py @@ -0,0 +1,283 @@ +"""Continuous and one-shot --watch mode checks for compile_dxil (#2935). + +usage: + native_compile_dxil_watch_check.py +""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import time + +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 +from native_rtv_variant_check import FLOAT32, UINT16, UNORM8, put_variant # noqa: E402 +from native_startup_request_cache_check import ( # noqa: E402 + COMPUTE_GROUP, + COMPUTE_RSRC2, + DECOY_MASKS, + TARGET_MASKS, + VS_WORDS, + compile_compute_root, + compile_graphics_table_root, + compute_program_words, + describe_psin, + ps_words, + put_compute_request, + put_graphics_request, +) +from startup_compute_translate_check import state_a # noqa: E402 + + +def touch(path: Path, data: bytes | None = None, mtime: float | None = None) -> None: + if data is not None: + path.write_bytes(data) + if mtime is not None: + os.utime(path, (mtime, mtime)) + + +def wait_for(predicate, timeout: float = 20.0) -> bool: + deadline = time.time() + timeout + while time.time() < deadline: + if predicate(): + return True + time.sleep(0.05) + return predicate() + + +def run_once(cli: Path, sdk: Path, frontend: Path, req_dir: Path, jobs: int = 1) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [cli, "--watch", sdk, frontend, req_dir, "--jobs", str(jobs), "--once"], + capture_output=True, + text=True, + timeout=60, + ) + + +def main(argv: list[str]) -> int: + if len(argv) != 2: + raise SystemExit(__doc__) + cli = Path(argv[0]) + sdk = Path(argv[1]) + + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + frontend = work / "frontend" + g_root = compile_graphics_table_root(sdk, work) + c_root = compile_compute_root(sdk, work) + c_code = compute_program_words() + c_sa = state_a(COMPUTE_GROUP, COMPUTE_RSRC2) + + # Part 1: --once pending, skip, resume, .psin/.psdep recheck, and parallel equivalence. + d1 = work / "once_serial" + d1.mkdir() + # Incomplete marker without .a / .c67 must be ignored. + (d1 / "req_00000000000000aa.b").write_bytes(ps_words(4)) + (d1 / "req_00000000000000aa.root").write_bytes(g_root) + (d1 / "req_00000000000000bb.data").write_bytes(b"\0" * 16) + + g_key = put_graphics_request(d1, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + g_bad_key = put_graphics_request(d1, VS_WORDS, ps_words(2), g_root, (0x0002, 0x8002)) + c_key = put_compute_request(d1, c_code, c_root, c_sa) + + r1 = run_once(cli, sdk, frontend, d1, jobs=1) + assert r1.returncode == 0, (r1.returncode, r1.stdout, r1.stderr) + assert f"{g_key:016x}: compiled graphics" in r1.stdout, r1.stdout + assert f"{c_key:016x}: compiled compute" in r1.stdout, r1.stdout + assert f"{g_bad_key:016x}: refused:" in r1.stdout, r1.stdout + assert "00000000000000aa" not in r1.stdout and "00000000000000bb" not in r1.stdout, r1.stdout + assert not (d1 / "00000000000000aa.fail").exists() + assert (d1 / f"{g_key:016x}.txt").is_file() + assert (d1 / f"{g_key:016x}.psdep").is_file() + assert (d1 / f"{c_key:016x}.txt").is_file() + assert (d1 / f"{g_bad_key:016x}.fail").is_file() + + # Re-running --once retries the .fail (first-pass semantics of --once) and skips complete entries. + txt_mtime = (d1 / f"{g_key:016x}.txt").stat().st_mtime_ns + cs_mtime = (d1 / f"{c_key:016x}.txt").stat().st_mtime_ns + r2 = run_once(cli, sdk, frontend, d1, jobs=1) + assert r2.returncode == 0, (r2.returncode, r2.stdout, r2.stderr) + assert f"{g_key:016x}:" not in r2.stdout and f"{c_key:016x}:" not in r2.stdout, r2.stdout + assert f"{g_bad_key:016x}: refused:" in r2.stdout, r2.stdout + assert (d1 / f"{g_key:016x}.txt").stat().st_mtime_ns == txt_mtime + assert (d1 / f"{c_key:016x}.txt").stat().st_mtime_ns == cs_mtime + + # Corrupting/truncating a stage .cso triggers resume and restores valid DXBC. + vs_cso = d1 / f"{g_key:016x}.vs.cso" + orig_vs = vs_cso.read_bytes() + vs_cso.write_bytes(orig_vs[:16]) + r3 = run_once(cli, sdk, frontend, d1, jobs=1) + assert r3.returncode == 0 and f"{g_key:016x}: compiled graphics" in r3.stdout, (r3.stdout, r3.stderr) + assert vs_cso.read_bytes() == orig_vs + + # Updating .psin mtime newer than .txt (with mismatched .b) rechecks, withdraws .txt, and writes .fail. + (d1 / f"req_{g_key:016x}.b").write_bytes(ps_words(2)) + future = time.time() + 2.0 + touch(d1 / f"req_{g_key:016x}.psin", mtime=future) + r4 = run_once(cli, sdk, frontend, d1, jobs=1) + assert r4.returncode == 0 and f"{g_key:016x}: refused:" in r4.stdout, (r4.stdout, r4.stderr) + assert not (d1 / f"{g_key:016x}.txt").exists() + assert (d1 / f"{g_key:016x}.fail").is_file() + + # Removing .psin when .psdep exists ('lost') forces recheck and withdraws .txt. + d_lost = work / "lost_psin" + d_lost.mkdir() + lost_key = put_graphics_request(d_lost, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + assert run_once(cli, sdk, frontend, d_lost, jobs=1).returncode == 0 + assert (d_lost / f"{lost_key:016x}.txt").is_file() and (d_lost / f"{lost_key:016x}.psdep").is_file() + (d_lost / f"req_{lost_key:016x}.psin").unlink() + r_lost = run_once(cli, sdk, frontend, d_lost, jobs=1) + assert r_lost.returncode == 0 and f"{lost_key:016x}: refused:" in r_lost.stdout, (r_lost.stdout, r_lost.stderr) + assert not (d_lost / f"{lost_key:016x}.txt").exists() + assert (d_lost / f"{lost_key:016x}.fail").is_file() + + # Parallel --once --jobs 2 matches serial --once --jobs 1. + d_serial = work / "cmp_serial" + d_parallel = work / "cmp_parallel" + for d in (d_serial, d_parallel): + d.mkdir() + put_graphics_request(d, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + put_graphics_request(d, VS_WORDS, ps_words(2), g_root, DECOY_MASKS) + put_graphics_request(d, VS_WORDS, ps_words(2), g_root, (0x0002, 0x8002)) + put_compute_request(d, c_code, c_root, c_sa) + put_compute_request(d, c_code, c_root, c_sa, override_key=c_key ^ 1) + rs = run_once(cli, sdk, frontend, d_serial, jobs=1) + rp = run_once(cli, sdk, frontend, d_parallel, jobs=2) + assert rs.returncode == 0 and rp.returncode == 0 + assert rs.stdout == rp.stdout, (rs.stdout, rp.stdout) + assert G.pending_keys(str(d_parallel), skip_failed=True) == [] + + # RTV variants in --once: compile base + variants, publish rtv1 manifest + .psdep, and recheck on base .psin update. + d_rtv = work / "once_rtv" + d_rtv.mkdir() + rtv_base = put_graphics_request(d_rtv, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + rtv_u16, rtv_u16_line = put_variant(d_rtv, rtv_base, (UINT16, UNORM8)) + rtv_f32, rtv_f32_line = put_variant(d_rtv, rtv_base, (FLOAT32,)) + rtv_bad, _ = put_variant(d_rtv, rtv_base, (7,)) + r_rtv = run_once(cli, sdk, frontend, d_rtv, jobs=2) + assert r_rtv.returncode == 0, (r_rtv.returncode, r_rtv.stdout, r_rtv.stderr) + for vkey, vline in ((rtv_u16, rtv_u16_line), (rtv_f32, rtv_f32_line)): + assert f"{vkey:016x}: compiled graphics" in r_rtv.stdout, r_rtv.stdout + vtxt = (d_rtv / f"{vkey:016x}.txt").read_text(encoding="ascii") + assert vtxt.splitlines()[-1] == vline, vtxt + assert (d_rtv / f"{vkey:016x}.psdep").is_file() + assert not (d_rtv / f"{vkey:016x}.fail").exists() + assert f"{rtv_bad:016x}: refused:" in r_rtv.stdout and (d_rtv / f"{rtv_bad:016x}.fail").is_file() + assert G.pending_keys(str(d_rtv), skip_failed=True) == [] + + # Updating the base request's .psin (with mismatched .b) rechecks both the base and its .rtv variants. + (d_rtv / f"req_{rtv_base:016x}.b").write_bytes(ps_words(2)) + touch(d_rtv / f"req_{rtv_base:016x}.psin", mtime=time.time() + 2.0) + r_rtv_recheck = run_once(cli, sdk, frontend, d_rtv, jobs=2) + assert r_rtv_recheck.returncode == 0, (r_rtv_recheck.returncode, r_rtv_recheck.stdout, r_rtv_recheck.stderr) + for key in (rtv_base, rtv_u16, rtv_f32): + assert f"{key:016x}: refused:" in r_rtv_recheck.stdout, r_rtv_recheck.stdout + assert not (d_rtv / f"{key:016x}.txt").exists() + assert (d_rtv / f"{key:016x}.fail").is_file() + + # Part 2: Live background --watch process retries pre-existing .fail once, skips unchanged .fail, + # translates newly written graphics/compute requests, and clears .fail when fixed. + wdir = work / "live_watch" + wdir.mkdir() + now = time.time() + stale_key = put_graphics_request(wdir, VS_WORDS, ps_words(2), g_root, (0x0002, 0x8002)) + touch(wdir / f"req_{stale_key:016x}.a", mtime=now - 20.0) + stale_fail = wdir / f"{stale_key:016x}.fail" + touch(stale_fail, b"stale reason\n", mtime=now - 10.0) + + watch = subprocess.Popen( + [cli, "--watch", sdk, frontend, wdir, "--jobs", "2", "--interval", "50"], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + try: + assert wait_for( + lambda: stale_fail.exists() and "unsupported pixel entry VGPR 2" in stale_fail.read_text(encoding="utf-8") + ), "watcher did not retry pre-existing .fail on first pass" + + # Write a new graphics request (initially tampered .b so it refuses, then fixed to the same key). + mut_key = G.pipeline_key(VS_WORDS, ps_words(4), g_root, ps_inputs=TARGET_MASKS) + stem = wdir / f"req_{mut_key:016x}" + stem.with_suffix(".b").write_bytes(ps_words(2)) + stem.with_suffix(".root").write_bytes(g_root) + stem.with_suffix(".psin").write_bytes(describe_psin(mut_key, TARGET_MASKS).encode("ascii")) + stem.with_suffix(".a").write_bytes(VS_WORDS) + + mut_fail = wdir / f"{mut_key:016x}.fail" + assert wait_for(lambda: mut_fail.exists()), "watcher did not emit .fail for newly written refused request" + first_fail_ns = mut_fail.stat().st_mtime_ns + stale_fail_ns = stale_fail.stat().st_mtime_ns + time.sleep(0.35) + assert mut_fail.stat().st_mtime_ns == first_fail_ns, "watcher rewrote unchanged .fail on subsequent pass" + assert stale_fail.stat().st_mtime_ns == stale_fail_ns, "watcher rewrote stale .fail on subsequent pass" + + # Fix the refused request with newer mtime: watcher must compile it and remove .fail. + future2 = time.time() + 2.0 + touch(stem.with_suffix(".b"), ps_words(4), mtime=future2) + touch(stem.with_suffix(".a"), VS_WORDS, mtime=future2) + mut_txt = wdir / f"{mut_key:016x}.txt" + assert wait_for(lambda: mut_txt.exists() and not mut_fail.exists()), ( + "watcher did not recover fixed request or remove .fail" + ) + assert (wdir / f"{mut_key:016x}.vs.cso").read_bytes().startswith(b"DXBC") + assert (wdir / f"{mut_key:016x}.ps.cso").read_bytes().startswith(b"DXBC") + + # Write a valid .rtv variant and an invalid .rtv variant while the watcher is running. + live_rtv, live_rtv_line = put_variant(wdir, mut_key, (UINT16, UNORM8)) + live_rtv_bad, _ = put_variant(wdir, mut_key, (7,)) + live_rtv_txt = wdir / f"{live_rtv:016x}.txt" + live_rtv_fail = wdir / f"{live_rtv_bad:016x}.fail" + assert wait_for(lambda: live_rtv_txt.exists() and live_rtv_fail.exists()), ( + "watcher did not process newly written .rtv variants" + ) + assert live_rtv_txt.read_text(encoding="ascii").splitlines()[-1] == live_rtv_line + assert (wdir / f"{live_rtv:016x}.vs.cso").read_bytes().startswith(b"DXBC") + assert (wdir / f"{live_rtv:016x}.ps.cso").read_bytes().startswith(b"DXBC") + + # Write a new compute request while the watcher is running. + live_cs = put_compute_request(wdir, c_code, c_root, c_sa) + live_cs_txt = wdir / f"{live_cs:016x}.txt" + assert wait_for(lambda: live_cs_txt.exists()), "watcher did not compile newly written compute request" + assert (wdir / f"{live_cs:016x}.cs.cso").read_bytes().startswith(b"DXBC") + assert not (wdir / f"{live_cs:016x}.fail").exists() + assert watch.poll() is None, "watcher exited unexpectedly" + finally: + watch.kill() + out, err = watch.communicate(timeout=20) + + assert not err.strip(), f"unexpected watcher stderr: {err!r}" + assert f"{stale_key:016x}: refused:" in out, out + assert f"{mut_key:016x}: refused:" in out and f"{mut_key:016x}: compiled graphics" in out, out + assert f"{live_cs:016x}: compiled compute" in out, out + + # Part 3: CLI negative controls. + bad_file = work / "not_a_dir" + bad_file.write_text("x", encoding="utf-8") + for bad_args in ( + ["--watch"], + ["--watch", sdk, frontend], + ["--watch", work / "missing_sdk", frontend, wdir, "--once"], + ["--watch", sdk, frontend, work / "missing_req", "--once"], + ["--watch", sdk, frontend, bad_file, "--once"], + ["--watch", sdk, frontend, wdir, "--interval", "5", "--once"], + ["--watch", sdk, frontend, wdir, "--interval", "60001", "--once"], + ["--watch", sdk, frontend, wdir, "--interval", "abc", "--once"], + ["--watch", sdk, frontend, wdir, "--jobs", "0", "--once"], + ["--watch", sdk, frontend, wdir, "--jobs", "65", "--once"], + ["--watch", sdk, frontend, wdir, "--bogus", "--once"], + ): + res = subprocess.run([cli, *bad_args], capture_output=True, text=True) + assert res.returncode != 0 and res.stderr.strip(), (bad_args, res.returncode, res.stdout, res.stderr) + + print("native_compile_dxil_watch checks: PASS (--once controls, resume/recheck, live --watch retry/skip/recovery, and CLI negative controls)") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/tests/native_compute_clear_check.py b/tests/native_compute_clear_check.py new file mode 100644 index 000000000..e703513b0 --- /dev/null +++ b/tests/native_compute_clear_check.py @@ -0,0 +1,64 @@ +"""Build a two-table compute request with source-generated instructions and an SDK root signature.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + + +def write_request(work, words, root, sa=None): + code = struct.pack(f"<{len(words)}I", *words) + data = b"synthetic" + if sa is 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(" +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; +using Clock = std::chrono::steady_clock; +namespace { +constexpr UINT width = 64, height = 32, pixels = width * height; +constexpr UINT raw_words = pixels * 2 + 16; +UINT raw_word(UINT i) { + // Every even word is another valid pair's byte address; odd words identify the pair. + return i % 2 ? 0x1234u + 11 * (i / 2) : 8 * ((i / 2 + 1) % pixels); +} +using Pixel = std::array; +Pixel pattern(UINT x, UINT y) { + return {float(1 + x + 128 * y), float(2000 + 2 * x + y), float(3 + x * y), float(10000 - x - 2 * y)}; +} +std::array sdwa_inputs(UINT x) { + return {0x93ac38e7u ^ (x * 0x0305070bu), 0x5ad2419bu ^ (x * 0x09010305u)}; +} +Pixel sdwa_expected(UINT x, const std::wstring &mode) { + auto [a, b] = sdwa_inputs(x); + UINT first, second; + if (mode == L"sdwa-class") { + first = b; + second = ((b >> 24) & 32u) ? a : b; + } else if (mode == L"sdwa-alias") { + first = (a >> 16) ^ a; + second = ((b >> 16) & 255u) ^ ((a >> 8) & 255u); + } else { + // Sign-extended source byte XOR a 32-bit operand. Then place the low byte + // of a separate XOR in byte 1, retaining or sign-filling unused bits. + first = UINT(int32_t(int8_t(a >> 16))) ^ b; + const UINT byte = ((a >> 16) ^ b) & 255u; + second = mode == L"sdwa-preserve" ? ((b & 0xffff00ffu) | (byte << 8)) + : UINT(int32_t(int8_t(byte))) << 8; + } + return {float(first & 65535), float(first >> 16), float(second & 65535), float(second >> 16)}; +} +} // namespace +int check_native_compute_grid(ID3D12Device *device, x2w::ShaderDxilCompiler &compiler, const wchar_t *marker, + const wchar_t *cache, const std::wstring &mode) { + const bool sdwa = mode == L"sdwa-alias" || mode == L"sdwa-preserve" || mode == L"sdwa-sext" || mode == L"sdwa-class"; + const bool typed = mode == L"typed" || sdwa; + const bool global_stride = mode == L"global-stride"; + const bool indexed = mode == L"indexed"; + const bool raw = global_stride || indexed || mode == L"raw-offset" || mode == L"raw-edge" || mode == L"raw-three" || + mode == L"raw-four" || mode == L"raw-math"; + const bool row = mode == L"row"; + if (!typed && !raw && !row && mode != L"copy" && mode != L"red" && mode != L"xyxx" && mode != L"negative") + return 2; + auto req = x2w::read_compute_request(marker); + UINT shape = 0; + std::memcpy(&shape, req.sa.data() + 12, sizeof(shape)); + const UINT gx = shape & 65535, gy = shape >> 16; + if (!gx || !gy || width % gx || height % gy) + return 2; + auto pipeline = x2w::create_native_compute_pipeline(device, compiler, marker, typed || raw ? 0 : 36, cache); + if (pipeline.srv_count != (row || indexed || global_stride ? 2u : 1u) || pipeline.uav_count != 1) + return 2; + auto kind = global_stride ? x2w::ComputeViewKind::buffer_srv : raw ? x2w::ComputeViewKind::raw_vector_srv : + typed ? x2w::ComputeViewKind::typed_buffer_srv : x2w::ComputeViewKind::texture_srv; + if ((row ? pipeline.bindings[1] : pipeline.bindings.front()).kind != kind) + return 2; + std::vector constants(pipeline.constant_words, 0); + if (typed || raw) { + if (constants.size() != 4 || pipeline.constants[0].root_parameter != 2 || + pipeline.bindings[0].byte_offset != 64 || pipeline.bindings[indexed || global_stride ? 2 : 1].byte_offset != 224) + return 2; + if (indexed && (pipeline.bindings[0].root_parameter != 0 || pipeline.bindings[0].array_count != 2 || + pipeline.bindings[1].root_parameter != 0 || pipeline.bindings[1].byte_offset != 96 || + pipeline.bindings[1].array_position != 1 || pipeline.bindings[2].root_parameter != 1)) + return 2; + if (global_stride && (pipeline.bindings[1].kind != x2w::ComputeViewKind::heap_stride_srv || + pipeline.bindings[1].root_parameter != x2w::compute_resource_heap)) + return 2; + constants[0] = 3; + constants[1] = 5; + } + constexpr unsigned copied_columns = 47, source_row = 13; + if (row) { + if (constants.size() != 2 || pipeline.bindings.front().kind != x2w::ComputeViewKind::buffer_srv || + pipeline.bindings[0].byte_offset != 0 || pipeline.bindings[1].byte_offset != 32 || + pipeline.bindings[2].byte_offset != 64) + return 2; + constants[0] = copied_columns; + constants[1] = 1; + } + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, pipeline.srv_count + 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr heap; + check(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap)), "grid heap"); + UINT step = device->GetDescriptorHandleIncrementSize(hd.Type); + auto cpu = heap->GetCPUDescriptorHandleForHeapStart(); + ComputeCommands cmd(device, pipeline.state.Get(), D3D12_COMMAND_LIST_TYPE_DIRECT); + D3D12_RESOURCE_DESC td{}; + td.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + td.Width = width; + td.Height = height; + td.DepthOrArraySize = td.MipLevels = td.SampleDesc.Count = 1; + td.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{}; + UINT64 bytes; + device->GetCopyableFootprints(&td, 0, 1, 0, &fp, nullptr, nullptr, &bytes); + auto upload = make_buffer(device, bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + void *mapped; + check(upload->Map(0, nullptr, &mapped), "grid upload"); + ComPtr input; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (raw) { + constexpr UINT first = 8; + for (UINT i = 0; i < first + raw_words + 1; ++i) + static_cast(mapped)[i] = i < first ? 0x654321u : raw_word(i - first); + if (global_stride) { + static_cast(mapped)[first + 3] = 4; + static_cast(mapped)[first + 11] = 9; + } + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Buffer.FirstElement = first; + srv.Buffer.NumElements = raw_words; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + input = upload; + } else if (typed) { + for (UINT i = 0; i < width; ++i) { + const auto values = sdwa ? sdwa_inputs(i) : std::array{33 * i + 7, 5 * i + 2}; + std::memcpy(static_cast(mapped) + 2 * i, values.data(), sizeof(values)); + } + srv.Format = DXGI_FORMAT_R32G32_UINT; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Buffer.NumElements = width; + input = upload; + } else { + for (UINT y = 0; y < height; ++y) + for (UINT x = 0; x < width; ++x) + std::memcpy(static_cast(mapped) + y * fp.Footprint.RowPitch + x * sizeof(Pixel), + pattern(x, y).data(), sizeof(Pixel)); + srv.Format = td.Format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Texture2D.MipLevels = 1; + input = resource(device, td, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST); + D3D12_TEXTURE_COPY_LOCATION src{upload.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}, + dst{input.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + src.PlacedFootprint = fp; + cmd.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + transition(cmd.list.Get(), input.Get(), D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + } + upload->Unmap(0, nullptr); + ComPtr parameters; + if (row) { + constexpr unsigned words = 130; + parameters = make_buffer(device, words * 4, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + check(parameters->Map(0, nullptr, &mapped), "row parameters"); + std::memset(mapped, 0, words * 4); + static_cast(mapped)[129] = source_row << 8; + parameters->Unmap(0, nullptr); + D3D12_SHADER_RESOURCE_VIEW_DESC raw{}; + raw.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + raw.Format = DXGI_FORMAT_R32_TYPELESS; + raw.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + raw.Buffer.NumElements = words; + raw.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(parameters.Get(), &raw, cpu); + cpu.ptr += step; + } + device->CreateShaderResourceView(input.Get(), &srv, cpu); + ComPtr second; + if (indexed || global_stride) { + second = make_buffer(device, bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + check(second->Map(0, nullptr, &mapped), "second indexed SRV"); + for (UINT i = 0; i < raw_words; ++i) + static_cast(mapped)[srv.Buffer.FirstElement + i] = 100000 + raw_word(i); + if (global_stride) { + auto *strides = static_cast(mapped) + srv.Buffer.FirstElement; + // Supply the metadata for a typed float3 SRV and an eleven-word structured UAV + // using the same decoder used for materialized guest slots at dispatch. + D3D12_SHADER_RESOURCE_VIEW_DESC typed_view{}; + typed_view.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + typed_view.Format = DXGI_FORMAT_R32G32B32_FLOAT; + D3D12_UNORDERED_ACCESS_VIEW_DESC structured{}; + structured.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + structured.Buffer.StructureByteStride = 44; + if (!x2w_startup::native_view_stride(18, &typed_view, sizeof(typed_view), strides[4]) || + !x2w_startup::native_view_stride(19, &structured, sizeof(structured), strides[9])) + return 2; + } + second->Unmap(0, nullptr); + cpu.ptr += step; + device->CreateShaderResourceView(second.Get(), &srv, cpu); + } + td.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + auto output = resource(device, td, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + if (row) { + transition(cmd.list.Get(), output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST); + D3D12_TEXTURE_COPY_LOCATION src{upload.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + D3D12_TEXTURE_COPY_LOCATION dst{output.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + src.PlacedFootprint = fp; + cmd.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + transition(cmd.list.Get(), output.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + } + cpu.ptr += step; + device->CreateUnorderedAccessView(output.Get(), nullptr, nullptr, cpu); + auto rb = make_buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + auto ticks = make_buffer(device, 16, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + D3D12_QUERY_HEAP_DESC qd{D3D12_QUERY_HEAP_TYPE_TIMESTAMP, 2}; + ComPtr query; + check(device->CreateQueryHeap(&qd, IID_PPV_ARGS(&query)), "grid timestamps"); + pipeline.bind(cmd.list.Get(), heap.Get(), heap->GetGPUDescriptorHandleForHeapStart(), step, constants.data()); + cmd.list->EndQuery(query.Get(), D3D12_QUERY_TYPE_TIMESTAMP, 0); + cmd.list->Dispatch(width / gx, row ? 1u : height / gy, 1); + cmd.list->EndQuery(query.Get(), D3D12_QUERY_TYPE_TIMESTAMP, 1); + cmd.list->ResolveQueryData(query.Get(), D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, ticks.Get(), 0); + transition(cmd.list.Get(), output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION src{output.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}, + dst{rb.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + dst.PlacedFootprint = fp; + cmd.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + check(cmd.list->Close(), "close"); + ID3D12CommandList *lists[]{cmd.list.Get()}; + auto start = Clock::now(); + cmd.queue->ExecuteCommandLists(1, lists); + double submit_us = std::chrono::duration(Clock::now() - start).count(); + ComPtr fence; + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "fence"); + check(cmd.queue->Signal(fence.Get(), 1), "signal"); + check(fence->SetEventOnCompletion(1, nullptr), "await grid"); + check(device->GetDeviceRemovedReason(), "grid completion"); + check(ticks->Map(0, nullptr, &mapped), "read times"); + UINT64 t[2], hz; + std::memcpy(t, mapped, 16); + ticks->Unmap(0, nullptr); + check(cmd.queue->GetTimestampFrequency(&hz), "frequency"); + check(rb->Map(0, nullptr, &mapped), "read pixels"); + unsigned differences = 0; + for (UINT y = 0; y < height; ++y) + for (UINT x = 0; x < width; ++x) { + Pixel expected = pattern(x, y); + if (raw) { + const UINT lane = y * width + x; + const UINT pair = mode == L"raw-edge" ? raw_words - 1 : 2 * lane; + expected = {float(raw_word(2 * lane + 13)), float(raw_word(pair)), + pair + 1 < raw_words ? float(raw_word(pair + 1)) : 0.f, float(lane)}; + if (mode == L"raw-three" || mode == L"raw-four") + expected = {float(raw_word(pair)), float(raw_word(pair + 1)), float(raw_word(pair + 2)), + mode == L"raw-four" ? float(raw_word(pair + 3)) : float(raw_word(pair + 13))}; + if (indexed && x >= gx) + for (unsigned component = 0; component < 3; ++component) + expected[component] += 100000; + if (mode == L"raw-math") { + constexpr float cosine[]{1.f, 0.f, -1.f, 0.f}; + expected[0] = cosine[lane % 4]; + const UINT bits = raw_word(pair), exponent = bits >> 10, fraction = bits & 1023; + expected[3] = exponent ? std::ldexp(float(1024 + fraction), int(exponent) - 25) + : std::ldexp(float(fraction), -24); + } + } + if (global_stride) expected.fill(x < gx ? 12.f : 44.f); + if (typed) + expected = {float(33 * x + 7), float(16*(y*3+5)+1+5*x+2), float(x+(x<32?3:9)), float(y/2+((y&3)==3))}; + if (sdwa) + expected = sdwa_expected(x, mode); + if (row && y == 0 && x < copied_columns) + expected = pattern(x, source_row); + if (mode == L"red") + expected.fill(expected[0]); + if (mode == L"xyxx") + expected[2] = expected[3] = expected[0]; + if (mode == L"negative") + expected[0] += 1; + auto *actual = + reinterpret_cast(static_cast(mapped) + y * fp.Footprint.RowPitch) + 4 * x; + for (UINT i = 0; i < 4; ++i) + differences += actual[i] != expected[i]; + } + rb->Unmap(0, nullptr); + std::printf("pixels=%u differing_components=%u cache_hit=%d frontend_ms=%.4f backend_ms=%.4f pso_ms=%.4f " + "cpu_submit_us=%.3f gpu_dispatch_us=%.3f\n", + pixels, differences, pipeline.cache_hit, pipeline.frontend_ms, pipeline.backend_ms, + pipeline.pipeline_ms, submit_us, double(t[1] - t[0]) * 1e6 / hz); + return differences ? 1 : 0; +} diff --git a/tests/native_compute_ir_dump.cpp b/tests/native_compute_ir_dump.cpp new file mode 100644 index 000000000..2c01a51f2 --- /dev/null +++ b/tests/native_compute_ir_dump.cpp @@ -0,0 +1,22 @@ +// Print the DXIL-text IR that the direct C++ frontend builds for a compute container. +// Used by native_f16_alu_check.py. Exit 1 and the diagnostic on stderr when the program is refused. +// usage: native_compute_ir_dump CONTAINER +#include "gfx1013_compute_native.h" +#include +#include +#include +#include + +int main(int argc, char **argv) { + if (argc != 2) + return 2; + std::ifstream file(argv[1], std::ios::binary); + const std::string bytes((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + try { + std::cout << x2w::translate_compute_container({bytes, {}}).dxil_ir; + } catch (const std::exception &error) { + std::cerr << error.what() << "\n"; + return 1; + } + return 0; +} diff --git a/tests/native_compute_raw_root_check.py b/tests/native_compute_raw_root_check.py new file mode 100644 index 000000000..ad2355bb9 --- /dev/null +++ b/tests/native_compute_raw_root_check.py @@ -0,0 +1,84 @@ +"""Exercise packed CBV/SRV address pairs in the raw compute entry ABI.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_direct_container_check import compute, words + + +def main(exe, sdk): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + + def signature(text): + src = work / "root.hlsl" + src.write_text(f'#define RS "{text}"') + binary = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "RS", + "-Fo", binary, src], check=True) + return binary.read_bytes() + + def compile_case(code, root, user=10, error=None): + sa = struct.pack("<7I", 0, 0, 0, 32 | (1 << 16), 1, 0, user << 1) + marker = write_request(work, code, root, sa) + result = subprocess.run([exe, sdk, work / "cache", "gfx1013-direct-cs@0", + marker, marker.with_suffix(".cso")], text=True, capture_output=True) + if error: + assert result.returncode and error in result.stderr, result.stderr + assert not marker.with_suffix(".cso").exists() + else: + assert result.returncode == 0, result.stderr + return result.stdout + + prefix = "RootConstants(num32BitConstants=2,b1)," + root = signature(prefix + "CBV(b0),SRV(t0)") + end = 0xbf810000 + # s[6:7] and s[8:9] belong to different root parameters. + # Copy the second address to s[2:3] before reading at byte 48. + read_cbv = [0xf40c0403, 0xfa000010] + copy_srv = 0xbe820408 + read_srv = [0xf40c0601, 0xfa000030] + code = [*read_cbv, copy_srv, *read_srv, end] + cold = compile_case(code, root) + assert "t0 root=1 bytes=0 min_size=48" in cold, cold + assert "t1 root=2 bytes=0 min_size=80" in cold, cold + assert "frontend_cache_hit=1" in compile_case(code, root) + compile_case([*read_cbv, copy_srv, 0xbe830380, *read_srv, end], root, + error="mismatched root address high half") + compile_case(code, root, user=9, error="root descriptor pair exceeds user SGPRs") + for wrong in ("UAV(u0)", "CBV(b0,visibility=SHADER_VISIBILITY_VERTEX)"): + compile_case(code, signature(prefix + wrong + ",SRV(t0)"), + error="compute root descriptor type or visibility") + + # The first table range occupies slot zero. Its appended range at slot + # one is either CBV or SRV, although both shaders perform the same SMEM load. + read_table = [0xbe850380, 0xf4080202, 0xfa000020, 0xf42000c4, 0xfa000000, end] + for declaration, expected in (("CBV(b1)", "declared-cbv"), ("SRV(t1)", "srv")): + table = signature("DescriptorTable(SRV(t0)," + declaration + ")") + assert "table_view=" + expected in compile_case(read_table, table, user=5) + + container_code = words(0xbe810380, 0xf4080200, 0xfa000020, 0xf42000c4, 0xfa000000, end) + for name, kind, width, sgpr, error in ( + ("cbv", 2, 4, 0, ""), ("srv", 0, 4, 0, ""), + ("uav", 3, 4, 0, "disagrees with reflected table record"), + ("image", 0, 8, 0, "disagrees with reflected table record"), + ("sgpr", 2, 4, 1, "no matching user SGPR")): + marker = work / (name + ".cdx") + record = (0x300 | kind, 8, 0, 0, width | sgpr << 8) + marker.write_bytes(compute(container_code, table=True, uses=[record])) + args = [exe, sdk, work / "cache", "gfx1013-container-cs", marker, marker.with_suffix(".cso")] + result = subprocess.run(args, capture_output=True, text=True) + if error: + assert result.returncode and error in result.stderr, result.stderr + else: + expected = "table_view=" + ("reflected-cbv" if kind == 2 else "srv") + assert result.returncode == 0 and expected in result.stdout, (result.stdout, result.stderr) + warm = subprocess.run(args, check=True, capture_output=True, text=True).stdout + assert "frontend_cache_hit=1" in warm and expected in warm, warm + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/tests/native_cvt_pk16_check.py b/tests/native_cvt_pk16_check.py new file mode 100644 index 000000000..c4f8e8eae --- /dev/null +++ b/tests/native_cvt_pk16_check.py @@ -0,0 +1,113 @@ +"""v_cvt_pk_u16_u32 and v_cvt_pk_i16_i32 in the direct compute path (#2995). + + native_cvt_pk16_check.py controls + native_cvt_pk16_check.py hardware + +Both saturate S0 and S1 to 16 bits and pack S0 into the low and S1 into the high half (gfx2hlsl.py's VOP3 table): +v_cvt_pk_u16_u32 takes min(S, 0xffff) of the unsigned values, v_cvt_pk_i16_i32 clamps the signed values to +[-32768, 32767]. A nonzero unused SRC2 field and op_sel are refused (gfx2hlsl.py refuses the SRC2 field). The VOP3 words were assembled with +LLVM 15.0.7 (clang -cc1as, gfx1013); the v_mov and store words follow the encodings of native_align_bfm_check.py. + +Each operand pair below is set by v_mov literals and converted by both instructions; every lane of two groups of +32 stores the sixteen results. The pairs cross both bounds of both forms. References that truncate instead of +saturating and that apply the unsigned bound to the signed form must each differ from the expected words. +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request + +PAIRS = [(0, 0xFFFF), (0x10000, 0xFFFFFFFF), (0xFFFF8000, 0xFFFF7FFF), (0x7FFF, 0x8000), + (0x12345, 0x7FFFFFFF), (0x80000000, 5), (0xFFFFFFFE, 0xFFFE), (1, 0x00010001)] +# s_mov_b32 s20, s4 / s_mov_b32 s21, 0 / s_load_dwordx4 s[32:35], s[20:21], 0x20 / s_lshl_b32 s7, s5, 11 / +# v_lshlrev_b32 v8, 6, v0 / v_add_nc_u32 v8, s7, v8: 64 bytes per lane, 2048 per group of 32 +PROLOGUE = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, 0x8F078B05, 0x34100086, 0x4A101007] +CVT_U16, CVT_I16 = (0xD76A0004, 0x00020501), (0xD76B0005, 0x00020501) # v4 / v5 from v1, v2 +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 + + +def program(src2=0): + code = PROLOGUE + [0xBF8CC07F] # s_waitcnt lgkmcnt(0) before the stores use s[32:35] + for index, (x, y) in enumerate(PAIRS): + code += [0x7E0202FF, x, 0x7E0402FF, y, + CVT_U16[0], CVT_U16[1] | src2 << 18, CVT_I16[0], CVT_I16[1] | src2 << 18] + for slot, vgpr in enumerate((4, 5)): + code += [0xE0701000 | (8 * index + 4 * slot), 0x80080008 | vgpr << 8] # buffer_store_dword v, v8, s[32:35] + return code + [0xBF810000] + + +def signed(x): + return x - (1 << 32) if x & 0x80000000 else x + + +def pack(x, y, truncate=False, unsigned_bound=False): + if truncate: + return (x & 0xFFFF) | ((y & 0xFFFF) << 16), (x & 0xFFFF) | ((y & 0xFFFF) << 16) + u = min(x, 0xFFFF) | (min(y, 0xFFFF) << 16) + clamp = (lambda v: min(v, 0x7FFF)) if unsigned_bound else (lambda v: max(-32768, min(32767, signed(v)))) + i = (clamp(x) & 0xFFFF) | ((clamp(y) & 0xFFFF) << 16) + return u, i + + +def reference(**mutation): + expected = [SENTINEL] * OUTPUT_WORDS + for lane in range(64): + base = GUARD_WORDS + lane * 16 + for index, (x, y) in enumerate(PAIRS): + expected[base + 2 * index:base + 2 * index + 2] = pack(x, y, **mutation) + return expected + + +def compile_program(cli, sdk, work, root, code): + marker = request(work, root, code) + return marker, subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, + marker.with_suffix('.cso')], capture_output=True, text=True) + + +def controls(cli, sdk, work, root): + marker, result = compile_program(cli, sdk, work, root, program()) + assert result.returncode == 0 and marker.with_suffix('.cso').is_file(), (result.stdout, result.stderr) + _, result = compile_program(cli, sdk, work, root, program(src2=3)) + assert result.returncode and 'with unused src2 field set' in result.stderr, (result.stdout, result.stderr) + code = program() + code[code.index(CVT_U16[0])] |= 1 << 11 # op_sel bit of src0 + _, result = compile_program(cli, sdk, work, root, code) + assert result.returncode and 'with op_sel' in result.stderr, (result.stdout, result.stderr) + expected = reference() + for label, mutant in (('truncated', reference(truncate=True)), ('unsigned bound', reference(unsigned_bound=True))): + assert mutant != expected, label + print('compiled; a nonzero src2 field and op_sel refused; the truncating and unsigned-bound references differ') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, program()) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = list(struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes())) + diff = [(i, hex(x), hex(y)) for i, (x, y) in enumerate(zip(actual, reference())) if x != y] + assert not diff, diff[:10] + print('v_cvt_pk_u16_u32 and v_cvt_pk_i16_i32: all 2064 words matched (1024 results, guards and sentinels)') + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_cvt_pk_u8_check.py b/tests/native_cvt_pk_u8_check.py new file mode 100644 index 000000000..987f072a6 --- /dev/null +++ b/tests/native_cvt_pk_u8_check.py @@ -0,0 +1,120 @@ +"""v_cvt_pk_u8_f32 in the direct compute path (#2997). + + native_cvt_pk_u8_check.py controls + native_cvt_pk_u8_check.py hardware + +D = (S2 & ~(0xff << 8 * S1[1:0])) | (flt32_to_uint8(S0) << 8 * S1[1:0]). The conversion is the one gfx2hlsl.py +measured on RDNA 2 hardware (see docs/experiments.md): round to nearest even, saturated to [0, 255], with NaN, both +zeros and every negative value giving 0 and +inf giving 255. The VOP3 word (opcode 0x15e) was assembled with LLVM +15.0.7 (clang -cc1as, gfx1013); the other words were checked with tools/disasm_rdna2.py --hex. + +Each case below sets S0 and S1 with v_mov literals over S2 = 0xa5a5a5a5 and stores the result; every lane of two +groups of 32 stores all of them. References that round half up, truncate, or let NaN or negative inputs through +must each differ from the expected words. +""" +from pathlib import Path +import math +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request + +REST = 0xA5A5A5A5 +F = lambda value: struct.unpack(' f32 -> reciprocal -> scaled integer is uniform at every + # step. Replacing the first conversion's input with VertexID is not. + uniform_vs = [0xf4000200, 0xfa000000, 0x7e020c08, 0x7e025501, + 0x100202ff, 0x41800000, 0x7e020f01, 0x7e120501, + 0x7e080c09, 0xf80008cf, 0x04040404, end] + check("vertex-uniform-readfirst-chain", "gfx1013-container-vs", + vertex(constants=(0,2,1), program=uniform_vs)) + varying_vs = uniform_vs.copy() + varying_vs[2] = 0x7e020d00 + check("vertex-varying-readfirst-chain", "gfx1013-container-vs", + vertex(constants=(0,2,1), program=varying_vs), "requires a wave-uniform reaching value") + # The first ALU overwrites its input VGPR and outputs a separate + # s[20:21] mask. CNDMASK still sees the original VCC. The next ALU + # consumes s[20:21], writes VCC and exposes that carry via v6. + vertex_carry = [0x7d0a0080, 0x7e020300, 0xd5281401, 195 | (257<<9) | (106<<18), + 0x7e0a02f4, 0x02000000 | (2<<17) | (5<<9) | 242, + 0xd5286a03, 128 | (193<<9) | (20<<18), 0x02000000 | (6<<17) | (5<<9) | 242, + 0x7e020b01, 0x7e060b03, 0xf80008cf, 0x06030201, end] + for op in range(3): + chain = vertex_carry.copy() + chain[2] += op<<16 + check("vertex-carry-chain-"+str(op), "gfx1013-container-vs", vertex(program=chain)) + replaced = vertex_carry[:6] + [0xbe950380] + vertex_carry[6:] + check("vertex-carry-high-overwrite", "gfx1013-container-vs", vertex(program=replaced), + "unproven vertex carry-in mask") + numeric = vertex_carry.copy() + numeric[5] = 0x7e040214 + check("vertex-carry-numeric-sgpr", "gfx1013-container-vs", vertex(program=numeric), + "unbound numeric SGPR s20") + # Match the decoder's DWORD input (+0.0), BYTE_3 class mask and + # s[40:41] destination. A second compare defines s[26:27]; both can + # still select a result while VCC retains the original vertex test. + class_select = [0x7d0a0080, 0x3446009e, 0x7d1046f9, 0x0386a880, + 0x7e0a02f4, 0xd5010004, 242 | (261<<9) | (40<<18), + 0x020c0af2, 0xd485001a, 130 | (256<<9), + 0xd5010007, 242 | (261<<9) | (26<<18), + 0xd5010008, 261 | (242<<9) | (40<<18), + 0xf80008cf, 0x08070604, end] + check("vertex-class-mask-select", "gfx1013-container-vs", vertex(program=class_select)) + pixel_class = [0x7e000281, *class_select[:-3]] + check("pixel-class-mask-select", "gfx1013-container-ps", patched_pixel(len(pixel_class),pixel_class, + export=(0xf800180f,0x08070604))) + changed_high = class_select[:5] + [0xbea90380] + class_select[5:] + check("vertex-class-mask-high-overwrite", "gfx1013-container-vs", vertex(program=changed_high), + "unproven graphics CNDMASK source") + bad_class = class_select.copy() + bad_class[3] |= 1<<16 + check("vertex-class-reserved-selection", "gfx1013-container-vs", vertex(program=bad_class), + "invalid or unsupported integer SDWA modifiers") + # s8 is a uniform root-buffer read. Bit 0 chooses identical high + # and low scalar words and the corresponding CNDMASK bit. + scalar_select = [0xf4000200,0xfa000000,0xbf0d8008,0x85a480c1, + 0x7e0a02f4,0xd5010004,242 | (261<<9) | (36<<18), + 0x7e0c0a24,0x7e0e0a25,0xf80008cf,0x04070604,end] + check("vertex-scalar-full-mask", "gfx1013-container-vs", + vertex(constants=(0,2,1), program=scalar_select)) + no_scalar_scc = scalar_select.copy() + no_scalar_scc[2] = 0x7d0a0080 # VOPC writes this lane's VCC, not SCC. + check("vertex-no-scalar-mask-proof", "gfx1013-container-vs", + vertex(constants=(0,2,1), program=no_scalar_scc), "requires a reaching scalar SCC comparison") + outside = [0xbf840006, *vertex_arms] # Jump into THEN before saving its mask. + check("vertex-mask-entry", "gfx1013-container-vs", vertex(program=outside), + "branch enters or crosses a masked vertex arm") + store = vertex_arms.copy() + store[6:8] = [0xe0701000,0x80020100] + check("vertex-mask-store", "gfx1013-container-vs", vertex(program=store), + "masked vertex arm has an unsupported exit or memory effect") + overwritten = vertex_arms.copy() + overwritten[7] = 0xbe880380 + check("vertex-mask-clobber", "gfx1013-container-vs", vertex(program=overwritten), + "masked vertex arm overwrites its saved EXEC") + escaping_scalar = vertex_arms.copy() + escaping_scalar[7] = 0xbe9a0381 # THEN writes s26; ELSE must not see a per-lane surrogate. + escaping_scalar[12] = 0x7e08021a + source = folder/"vertex-mask-scalar" + source.write_bytes(vertex(program=escaping_scalar)) + rejected = subprocess.run([exe, sdk, folder/"cache", "gfx1013-container-vs", source, source.with_suffix(".cso")], + capture_output=True, text=True) + assert rejected.returncode and ("unbound numeric SGPR s26" in rejected.stderr or + "undefined on an incoming path: 26" in rejected.stderr), rejected.stderr + check("split-mask-two-arms", "gfx1013-container-ps", patched_pixel(len(two_arms), two_arms, + input_address=1 << 8, input_signature=position_input)) + cmpx = [0xbefe0a7e, 0xbe8a047e, 0x7c2800f4, 0x7e0002f2, + 0x8afe7e0a, 0x7e0002f0, 0xbefe040a] + check("cmpx-partition", "gfx1013-container-ps", patched_pixel(len(cmpx), cmpx, + input_address=1 << 8, input_signature=position_input)) + unproven = cmpx.copy() + unproven[1] = 0xbf800000 + check("cmpx-wrong-parent", "gfx1013-container-ps", patched_pixel(len(unproven), unproven, + input_address=1 << 8, input_signature=position_input), "unproven enclosing whole-quad EXEC") + first = [0xd557000e, (240 << 18) | (128 << 9) | 242, 0x7e28050e, 0x7e000214] + check("readfirstlane-uniform-median", "gfx1013-container-ps", patched_pixel(len(first), first)) + varying = [0x7e280500, 0x7e000214] + check("readfirstlane-varying-position", "gfx1013-container-ps", patched_pixel(len(varying), varying, + input_address=1 << 8, input_signature=position_input), "wave-uniform reaching value") + partition = [0xbe8c047e, 0xbefe0a7e, 0xbe8a047e, 0x7c0400f2, + 0xd4010016, 0x000200f2, 0x8896166a, 0x87fe7e16, + 0xbf880001, 0x7e0002f4, 0x8afe7e0a, 0xbf880003, + 0xbe96240c, 0x7e0002f2, 0xbe9e2516, 0xbefe040a] + check("compare-union-exec-arms", "gfx1013-container-ps", patched_pixel(len(partition), partition, + input_address=1 << 8, input_signature=position_input)) + foreign_mask = partition.copy() + foreign_mask[12] = 0xbe962408 + check("unproven-inner-coverage", "gfx1013-container-ps", patched_pixel(len(foreign_mask), foreign_mask, + input_address=1 << 8, input_signature=position_input), "inner EXEC requires saved entry coverage") + unsafe = masked.copy() + unsafe[3] = 0xb0000002 # scalar state changes for the whole guest wave + check("masked-scalar", "gfx1013-container-ps", patched_pixel(len(unsafe), unsafe, + input_address=1 << 8, input_signature=position_input), "lane-local vector arithmetic") + full_mask = lanes + [0xbe80036a] + check("full-mask", "gfx1013-container-ps", patched_pixel(len(full_mask), full_mask), + "consumes a full wave mask") + # Two barycentric registers, three pull-model registers, one line + # stipple register, then position.y in V6 (position.x disabled). + position = [0x7e000306] + mask = (1 << 1) | (1 << 3) | (1 << 7) | (1 << 9) + check("pixel-position", "gfx1013-container-ps", patched_pixel(1, position, input_address=mask, + input_signature=((b"ISG1", signature(b"SV_Position", 1)),))) + # Export the numeric I,J,J,I registers. DXIL orders the three + # weights by vertex, so I/J must select components 1/2. + ij = patched_pixel(prefix=[0xbf800000], input_address=2, export=(0xf800180f,0x00010100)) + check("center-weights", "gfx1013-container-ps", ij) + ij_ir = subprocess.check_output([pathlib.Path(sdk)/"dxc.exe","-dumpbin",folder/"center-weights.cso"],text=True) + assert "SV_Barycentrics" in ij_ir and all( + f"@dx.op.loadInput.f32(i32 4, i32 0, i32 0, i8 {col}," in ij_ir for col in (1,2)), ij_ir + # Covered lanes replace I with 1/4. A subsequent horizontal quad + # shuffle must still see original I on the other side of an edge. + edge = [0xbe8c047e,0xbefe0a7e,0xbe8a047e,0xbefe040c,0x7e0002ff,0x3e800000, + 0xbefe040a,0x060000fa,0xff00b100] + check("masked-ij-quad-edge", "gfx1013-container-ps", patched_pixel(len(edge),edge,input_address=2)) + check("pull-weights", "gfx1013-container-ps", + patched_pixel(prefix=[0xbf800000], input_address=8, export=(0xf800180f,0x00010100)), + "unsupported pixel entry VGPR") + for semantic,system,component,channel in ( + (b"SV_Depth",65,3,0), (b"SV_DepthLessEqual",68,3,0), + (b"SV_DepthGreaterEqual",67,3,0), (b"SV_StencilRef",69,1,1), + (b"SV_Coverage",66,1,2)): + output=((b"OSG1",signature(semantic,system,component,0xffffffff,1)),) + data=patched_pixel(input_signature=output, export=(0xf8001880 | (1<> (2 * n)) & 3 for n in range(4)] + dpp8 = sum((lanes[n % 4] + (n & 4)) << (8 + 3 * n) for n in range(8)) + variants = [(0x060000fa, 0xff0c0000 | perm << 8), (0x060000e9, dpp8), (0x060000ea, dpp8)] + for n, (op, control) in enumerate(variants): + label = f"quad-fi-{perm}-{n}" + args = [0xbefe0a7e, op, control] + check(label, "gfx1013-container-ps", patched_pixel(len(args), args, input_address=2)) + ir = subprocess.check_output([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/(label+".cso")], text=True) + assert ("@dx.op.quadReadLaneAt.i32(" if not perm else "@dx.op.quadOp.i32(") in ir + check("quad-dpp8-cross"+str(perm), "gfx1013-container-ps", + patched_pixel(3, [0xbefe0a7e, 0x060000ea, dpp8 ^ (4 << 8)], input_address=2), + "repeating quad-local selections") + check("quad-fi-exact", "gfx1013-container-ps", + patched_pixel(2, [0x060000fa, 0xff0c0000], input_address=2), "requires a proven whole quad") + check("quad-half-row-mirror", "gfx1013-container-ps", + patched_pixel(3, [0xbefe0a7e, 0x060000fa, 0xff054100], input_address=2), + "half-row mirror requires a proven eight-lane pixel layout") + full = [0xbebe25c1,0x7e2202fa,0xff054100,0xbefe043e] + check("mirror-unknown-pixel-lanes","gfx1013-container-ps", + patched_pixel(len(full),full,input_address=2),"needs an unobserved source lane") + full[-1] += 2 + check("mirror-unmatched-exec","gfx1013-container-ps", + patched_pixel(len(full),full,input_address=2),"matching restore in the same block") + quad[0]=0xbf800000 + check("quad-no-wqm","gfx1013-container-ps",patched_pixel(len(quad),quad), + "without whole-quad entry") + quad[-1]^=1<<28 + check("quad-partial-mask","gfx1013-container-ps",patched_pixel(len(quad),quad), + "full-row, full-bank") + check("missing-position", "gfx1013-container-ps", patched_pixel(1, position, input_address=mask), + "position absent from pixel input signature") + for op in (32, 37): + prefix = [0xbe810380, 0xf40c0200, 0xfa000000, + 0xbe840380, 0xbe8503ff, 0x00fff000, 0xbe8603ff, 0x04000000, 0xbe870380, + 0x7e0002f0, 0x7e0202f2, 0x7e0402f4, 0xf0000108 | op << 18, 0x00220000] + check(f"sample{op}", "gfx1013-container-ps", patched_pixel(len(prefix), prefix, True)) + check(f"derivative{op}", cs, compute(words(*prefix, end), table=True), + "implicit derivatives require a pixel stage") + image_setup = prefix[:-2] + for op in (32, 34, 36, 37, 39): + coords = [0x7e060280, 0x7e080280, 0x7e0a0280] + sample = [*image_setup, *coords, 0xf0000e08 | (op << 18), 0x80220400] + name = f"packed-sample-{op}" + check(name, "gfx1013-container-ps", + patched_pixel(len(sample), sample, table=True, export=(0xf800180f, 0x05040504))) + ir = subprocess.check_output([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/(name+".cso")], text=True) + components = re.findall(r"extractvalue %dx.types.ResRet.f32 %\w+, (\d)", ir) + assert components == ["1", "2", "3"] and "shl i32" in ir, (name, components) + invalid = [*image_setup, 0xf09c0e18, 0x80220400] # Cube needs a separate view contract. + check("packed-sample-cube", "gfx1013-container-ps", patched_pixel(len(invalid),invalid,table=True), + "unsupported image dimension or D16") + # The derivative sample executes with its quad intact. Coverage masks + # the writeback to v0; a helper must keep the pre-sample coordinate. + window = [0xbe95037e, 0xbefe097e, 0xbe97037e, *image_setup, 0xbf820000, + 0xbefe0315, 0xf0800108, 0x00220000, 0xbefe0317, 0x060000fa, 0xff00b100, 0xbefe0315] + check("wave32-exact-sample", "gfx1013-container-ps", + patched_pixel(len(window), window, table=True, wave32=True)) + sample_ir = subprocess.check_output([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", + folder/"wave32-exact-sample.cso"], text=True) + assert all(op in sample_ir for op in ("@dx.op.sample.f32", "@dx.op.isHelperLane.i1", "select i1", + "@dx.op.quadOp.i32")) + clobbered = window.copy() + clobbered.insert(3, 0xbe950380) # Overwrite the exact coverage mask in s21. + check("wave32-clobbered-exec", "gfx1013-container-ps", + patched_pixel(len(clobbered), clobbered, table=True, wave32=True), + "unproven EXEC for a conditional sample") + for name, inst, intrinsic in (("raw", 0xe0701000, "rawBufferStore.i32"), + ("typed", 0xe0102000, "bufferStore.i32")): + store = [*image_setup, inst, 0x80020100] + check("pixel-buffer-" + name, "gfx1013-container-ps", patched_pixel(len(store), store, True)) + dump = subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/("pixel-buffer-" + name + ".cso")], + check=True, capture_output=True, text=True).stdout + assert "@dx.op." + intrinsic + "(" in dump, dump + for channels in (1, 2, 4): + # Two distinguishable binary16 values in each VGPR. + mask = (1 << channels) - 1 + store = 0xf0200008 | mask << 8 + code = [*image_setup, 0x7e0802ff, 0x40003c00, 0x7e0a02ff, 0xc000bc00, store, 0x80020400, end] + label = f"d16-store-{channels}" + check(label, cs, compute(words(*code), table=True)) + check("pixel-" + label, "gfx1013-container-ps", patched_pixel(len(code)-1, code[:-1], True)) + dump = subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/(label+".cso")], + check=True, capture_output=True, text=True).stdout + assert dump.count("call float @dx.op.legacyF16ToF32(") == channels and "@dx.op.textureStore.f32(" in dump, dump + vs_store = [*code[:-1], 0xf80008cf, 0, end] + check("vertex-uav", "gfx1013-container-vs", vertex(program=vs_store, table=True)) + code[-2] = 0x8002ff00 + check("d16-store-overflow", cs, compute(words(*code), table=True), "image data overflow") + code[-3], code[-2] = 0xf0200508, 0x80020400 + check("d16-store-holes", cs, compute(words(*code), table=True), "image opcode or descriptor modifiers") + for op, profile, dim, method in ((40, "gfx1013-container-ps", 1, "sampleCmp"), + (47, cs, 5, "sampleCmpLevelZero")): + code = comparison_program(op, dim) + label = f"comparison-{op}" + source = compute(words(*code, end), table=True) if profile == cs else patched_pixel(len(code), code, True) + check(label, profile, source) + dump = subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/(label+".cso")], + check=True, capture_output=True, text=True).stdout + assert f"@dx.op.{method}.f32(" in dump and "i32 32782" in dump, dump + cube_cmp = comparison_program(dim=3) + check("cube-array-compare", "gfx1013-container-ps", patched_pixel(len(cube_cmp), cube_cmp, True)) + code = comparison_program(sampler=0x1012) # point without coordinate truncation + check("comparison-invalid", cs, compute(words(*code, end), table=True), "unsupported comparison sampler fields") + for op in (32, 39): + code = [*image_setup, 0xf0000508 | op << 18, 0x40220002] + check(f"packed-{op}", "gfx1013-container-ps", patched_pixel(len(code), code, True)) + dump = subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/f"packed-{op}.cso"], + check=True, capture_output=True, text=True).stdout + assert dump.count("call float @dx.op.legacyF16ToF32(") == 2, dump + # Lower all four cube ALU operations, then use face coordinates in a sample. + cube = list(image_setup) + for op in range(0x144, 0x148): + cube.extend((0xd4000000 | op << 16 | (4 + op - 0x144), 256 | 257 << 9 | 258 << 18)) + cube.extend((0xf09c011a, 0x00220005, 0x00000406)) # S=V5, T=V6, face=V4 + check("cube", "gfx1013-container-ps", patched_pixel(len(cube), cube, True)) + dump = subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/"cube.cso"], + check=True, capture_output=True, text=True).stdout + assert "@dx.op.sampleLevel.f32(" in dump and "fcmp oge float" in dump and "fptosi float" in dump and "cubearray" in dump.lower(), dump + code = [*image_setup, 0xf0000118, 0x00020000] + check("cube-load", "gfx1013-container-ps", patched_pixel(len(code), code, True), "unsupported cube") + for label, op, dim, mask, flags, nsa, expected_ir in ( + ("gradient", 34, 1, 1, 0, [0x00020100, 1], "sampleGrad.f32"), + ("gradient-cube-array", 34, 3, 1, 0, [0x00020100, 0x0201], "sampleGrad.f32"), + ("gradient-array", 34, 5, 1, 0, [0x00020100, 0x0201], "sampleGrad.f32"), + ("lod-query", 96, 1, 3, 0x1000, [], "calculateLOD.f32"), + ("cube-array-lod", 96, 3, 3, 0, [], "calculateLOD.f32"), + ("cube-array-gather", 71, 3, 2, 0, [], "textureGather.f32"), + ("gather-green", 64, 1, 2, 0, [], "textureGather.f32"), + ("gather-blue-lz", 71, 1, 4, 0, [], "textureGather.f32"), + ("mip-size", 14, 1, 15, 0, [], "getDimensions")): + instruction = 0xf0000000 | op << 18 | dim << 3 | mask << 8 | flags | len(nsa) << 1 + code = [*image_setup, instruction, 0x00220000, *nsa] + if op == 64: + check(label+"-mips", "gfx1013-container-ps", patched_pixel(len(code), code, True), + "implicit gather requires a sampler fixed to mip zero") + code[image_setup.index(0x00fff000)] = 0 + check(label, "gfx1013-container-ps", patched_pixel(len(code), code, True)) + dump = subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/(label+".cso")], + check=True, capture_output=True, text=True).stdout + assert f"@dx.op.{expected_ir}(" in dump, dump + if op == 96 and dim == 1: + assert "i1 true)" in dump and "i1 false)" in dump and "fdiv float" in dump, dump + if op == 34: + wrong = [*image_setup, instruction - 2, 0x00220000, nsa[0]] + check(label+"-short", "gfx1013-container-ps", patched_pixel(len(wrong), wrong, True), + "incomplete image NSA address list") + pair=[exe,sdk,folder/"cache","gfx1013-container-pair", + folder/"vertex",folder/"linked.vs.cso",folder/"patched",folder/"linked.ps.cso"] + for expected in (0, 1): + result = subprocess.run(pair, check=True, capture_output=True, text=True) + assert f"graphics_pair frontend_cache_hit={expected}" in result.stdout + assert (folder/"linked.vs.cso").read_bytes()==(folder/"vertex.cso").read_bytes() + assert (folder/"linked.ps.cso").read_bytes()==(folder/"patched.cso").read_bytes() + pair[-2] = folder/"bary-two-pairs" + for warm in (0, 1): + result = subprocess.run(pair, check=True, capture_output=True, text=True) + assert f"graphics_pair frontend_cache_hit={warm}" in result.stdout + pair[-2]=folder/"smooth" + mismatch=subprocess.run(pair,capture_output=True,text=True) + assert mismatch.returncode and "stages disagree" in mismatch.stderr + # VS reads root 4, PS reads root 1. The linked b0 puts root 4 after + # four PS words although both stages load the guest value from s0. + check("root-vs", "gfx1013-container-vs", vertex(constants=(4, 1))) + check("root-ps", "gfx1013-container-ps", patched_pixel(prefix=[0x7e000200], constants=(1, 4))) + pair[-4], pair[-2] = folder/"root-vs", folder/"root-ps" + for warm in range(2): + result = subprocess.run(pair, check=True, capture_output=True, text=True) + assert f"frontend_cache_hit={warm}" in result.stdout + for output, col in (("linked.vs.cso", 1), ("linked.ps.cso", 0)): + dump = subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/output], + check=True, capture_output=True, text=True).stdout + assert any("@dx.op.cbufferLoadLegacy.i32(i32 59" in line and f", i32 {col})" in line + for line in dump.splitlines()), dump + (folder/"root-ps").write_bytes(patched_pixel(prefix=[0x7e000200], constants=(1, 32))) + overflow = subprocess.run(pair, capture_output=True, text=True) + assert overflow.returncode and "exceeds 32 words" in overflow.stderr, overflow.stderr + # Directory mode consumes the runtime's last-published .a marker and + # matches the FNV key over both containers, the root, and optional IA. + capture = folder / "requests" + capture.mkdir() + root = b"DXBC" + bytes(16) + words(1, 68, 1, 36) + b"RTS0" + words(24, 2, 0, 24, 0, 24, 0) + stem = publish(capture, vertex(), patched_pixel(), root) + batch = [exe, sdk, folder/"cache", "--jobs", "2", "gfx1013-container-pair", + "--requests", capture, folder/"warm"] + raw_vs = words(0x7e020b00, 0xf80008cf, 0x01010101, end) + raw_ps = words(0x7e0002f2, 0xf8001c0f, 0, end) + # A recorded logical table can contain scalar buffers outside the + # serialized desktop range. Both stage identities and each used + # record are checked, including when a warm cache already exists. + rs = folder/"short-root.hlsl" + rs.write_text('#define RS "DescriptorTable(CBV(b27,space=1))"\n') + short = folder/"short-root.bin" + subprocess.run([pathlib.Path(sdk)/"dxc.exe","-T","rootsig_1_1","-E","RS",rs,"-Fo",short],check=True) + interfaces = folder/"reviewed-cache"/"interfaces" + interfaces.mkdir(parents=True) + def install(raw, container): + (interfaces/(hashlib.sha256(raw).hexdigest()+".cdxil")).write_bytes(container) + ps_id = [0xd5800000,255,0x789,0xd5800000,255,0xabc] + ps = words(*ps_id) + raw_ps + install(ps, patched_pixel(7,[*ps_id,0x7e0002f2])) + for slot in (2,5): + vs_id = [0xd5800000,255,0x123,0xd5800000,255,slot] + op = [*vs_id,0xbe890380,0xf4080204,0xfa000000+32*slot, + 0xf42000c4,0xfa000000,0x7e000203,0xf80008cf,0,end] + raw = words(*op) + fixture_dir = folder/f"reflected-slot-{slot}" + publish(fixture_dir, ps, raw, short.read_bytes(), ps_inputs=(0x8080, 0x8080)) + job = [exe,sdk,interfaces.parent,"gfx1013-container-pair","--requests",fixture_dir,folder/"warm"] + for offset,error in ((8*slot,None),(8*slot+8,"raw load disagrees with reflected table record")): + install(raw, vertex(program=op, uses=[(0x302,offset,0,0,4 | 8<<8)])) + result = subprocess.run(job, capture_output=True,text=True) + if error: + assert result.returncode and error in result.stderr,result.stderr + else: + assert result.returncode == 0,result.stderr + install(raw, patched_pixel(len(vs_id),vs_id)) + install(ps, vertex(program=[*ps_id, *struct.unpack("<4I",raw_vs)])) + result = subprocess.run(job,capture_output=True,text=True) + assert result.returncode and "raw exports disagree with reflected stage" in result.stderr,result.stderr + for label, fragment, diagnostic in ( + ("raw-export", raw_ps, ""), + ("raw-branch", words(0xbf820000) + raw_ps, "verified stage interface or wave state")): + raw_dir = folder / label + raw_key = publish(raw_dir, fragment, raw_vs, root) + raw_job = batch.copy() + raw_job[-2] = raw_dir + result = subprocess.run(raw_job, capture_output=True, text=True) + if diagnostic: + assert result.returncode and diagnostic in result.stderr, result.stderr + else: + assert result.returncode == 0, result.stderr + for stage in ("ps", "vs"): + assert (folder/"warm"/f"{raw_key}.{stage}.cso").read_bytes().startswith(b"DXBC") + # One scalar entry precedes the packed screen coordinate. A different + # mask moves that entry and must change the request and compilation. + packed_ps = words(0x7e000cf9, 0x00040601, 0xf800180f, 0, end) + # Two independent comparisons kill fragment lanes before their color + # export. Empty waves branch to EXP_NULL beyond the first endpgm. + kill = [0xbe90047e, 0xbefe0410, 0x7e1002f2, 0x7e0a0280, + 0xd4010008, 0x21100, 0x7d040a80, 0x8888086a, 0x8afe087e, 0xbf880003, + 0xf800180f, 0, end, 0xf8001890, 0x80808080, end] + for name, clobber in (("terminal-discard", False), ("terminal-discard-clobber", True)): + sequence = kill.copy() + if clobber: + sequence.insert(6, 0xbe880380) + fixture = folder/name + key = publish(fixture, words(*sequence), raw_vs, root, ps_inputs=(2, 2)) + job = batch.copy() + job[-2] = fixture + result = subprocess.run(job, capture_output=True, text=True) + if clobber: + assert result.returncode and "discard mask has no reaching lane comparison" in result.stderr + else: + assert result.returncode == 0, result.stderr + ir = subprocess.check_output([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", + folder/"warm"/f"{key}.ps.cso"], text=True) + assert "call void @dx.op.discard(i32 82, i1 %" in ir + for name, entry, ps, vs, ok in ( + ("packed-input", (0x8080, 0x8080), packed_ps, raw_vs, True), + ("packed-absent", (0, 0), packed_ps, raw_vs, False), + ("center-position-zw", (0x0c02, 0x0c02), + words(0xf800180f, 0x03020302, end), raw_vs, True), + ("center-position-zw-packed", (0x8c02, 0x8c02), + words(0xf800180f, 0x04040302, end), raw_vs, True), + ("center-position-missing-w", (0x0402, 0x0402), + words(0xf800180f, 0x03020302, end), raw_vs, False), + ("whole-quad-second-param", (2, 2), + words(0xbe8c047e, 0xbefe0a7e, 0xc8100400, 0xc8110401, + 0xbefe040c, 0xf800180f, 0x04040404, end), + words(0xbe8c0400, 0x938dff0d, 0x80000, 0xf4080406, 0xfa000000, + 0x4a000002, 0xbf8cc07f, 0xe03c2000, 0x80040100, + 0xe0342010, 0x80040400, 0xe9c3200c, 0x80040800, + 0xf80008cf, 0x08030201, 0xf8000211, 0x04040404, end), True), + ("whole-quad-param", (0x8002, 0x8002), + words(0xbe8c047e, 0xbefe0a7e, 0xbe8a047e, 0xc8100000, 0xc8140100, + 0xc8110001, 0xc8150101, 0xbefe040c, 0xf800180f, 0x05040504, end), + words(0x7e020b00,0xf80008cf,0x01010101,0xf800020f,0x01010101,end), True)): + fixture = folder / name + key = publish(fixture, ps, vs, root, ps_inputs=entry) + job = batch.copy() + job[-2] = fixture + result = subprocess.run(job, capture_output=True, text=True) + assert (result.returncode == 0) == ok, (name, result.stderr) + if not ok: + assert "pixel entry VGPR" in result.stderr, result.stderr + elif name.startswith("center-position-"): + binary = folder/"warm"/f"{key}.ps.cso" + dump = subprocess.check_output([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", binary], text=True) + channels = re.findall(r"call float @dx\.op\.loadInput\.f32\(i32 4, i32 0, i32 0, i8 (\d+)", dump) + assert set(channels) == set("0123" if name.endswith("packed") else "23"), (name, channels) + # Mask a real PS root constant to select table byte offset 0 or 32. + # Reading through the resulting descriptor must require two SRV slots. + indexed = [0xbe810380, 0x8702a002, 0xf4080200, 2 << 25, + 0xf42000c4, 0xfa000000, 0x7e000203] + indexed_ps = patched_pixel(len(indexed), indexed, + root_inputs=((3,0,1,0,0), (0,0,1,0,0x102))) + # s4 supplies the byte offset and is also the first of eight destinations. + # The second raw load still consumes the address computed at entry. + load8 = [0x8704a002, 0xf40c0100, (4 << 25) + 16, 0x7e00020b] + descriptor_inputs = ((1,0,2,0,0), (0,0,1,0,0x102)) + check("root-index", "gfx1013-container-ps", + patched_pixel(len(load8), load8, root_inputs=descriptor_inputs)) + dump = subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/"root-index.cso"], + check=True, capture_output=True, text=True).stdout + first, second = re.findall(r"call .*?@dx\.op\.rawBufferLoad\.i32\(i32 139, [^,]+, i32 (%\w+),", dump) + assert f"{second} = add i32 {first}, 16" in dump, dump + unknown8 = [*load8[1:]] + unknown8[1] = (2 << 25) + 16 + check("root-index-range", "gfx1013-container-ps", + patched_pixel(len(unknown8), unknown8, root_inputs=descriptor_inputs), + "unbounded or unaligned root descriptor index") + for label, declaration, error in ( + ("cbv", "CBV(b0)", ""), + ("srv", "SRV(t0, visibility=SHADER_VISIBILITY_VERTEX)", ""), + ("uav", "UAV(u0)", "requires a root CBV or SRV"), + ("hidden", "SRV(t0, visibility=SHADER_VISIBILITY_PIXEL)", "visibility mismatch"), + ("array2", "DescriptorTable(SRV(t0,numDescriptors=2)),RootConstants(num32BitConstants=1,b0)", ""), + ("array1", "DescriptorTable(SRV(t0)),RootConstants(num32BitConstants=1,b0)", "exceeds its declared root range")): + rs = folder/"root.hlsl" + rs.write_text(f'#define RS "{declaration}"\n') + compiled_root = folder/"root.bin" + subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-T", "rootsig_1_1", "-E", "RS", + rs, "-Fo", compiled_root], check=True) + source = folder/("descriptor-" + label) + vs, ps = (vertex(), indexed_ps) if label.startswith("array") else (root_vs, patched_pixel()) + descriptor_stem = publish(source, vs, ps, compiled_root.read_bytes()) + job = batch.copy() + job[-2] = source + for warm in range(1 if error else 2): + result = subprocess.run(job, capture_output=True, text=True) + if error: + assert result.returncode and error in result.stderr, result.stderr + else: + assert result.returncode == 0 and f"frontend_cache_hit={warm}" in result.stdout, result.stderr + if label == "array2": + dump = subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/"warm"/f"{descriptor_stem}.ps.cso"], + check=True, capture_output=True, text=True).stdout + assert "i32 0, i32 1, i32 0, i8 0 }" in dump and "i1 true)" in dump, dump + for expected in (0, 1): + result = subprocess.run(batch, capture_output=True, text=True) + assert result.returncode == 0, result.stderr + assert f"graphics_pair frontend_cache_hit={expected}" in result.stdout + assert "requests=1 compiled=1 refused=0" in result.stdout + for stage, reference in (("vs", "vertex"), ("ps", "patched")): + assert (folder/"warm"/f"{stem}.{stage}.cso").read_bytes() == (folder/f"{reference}.cso").read_bytes() + rect=batch.copy() + rect[5]="gfx1013-container-rect" + for _ in range(2): + result=subprocess.run(rect,capture_output=True,text=True) + assert result.returncode==0, result.stderr + gs=folder/"warm"/f"{stem}.gs.cso" + dump=subprocess.run([pathlib.Path(sdk)/"dxc.exe","-dumpbin",gs],capture_output=True,text=True,check=True).stdout + assert dump.count("call void @dx.op.emitStream(")==6 and dump.count("call void @dx.op.cutStream(")==2 + (capture / f"req_{stem}.root").write_bytes(root + b"!") + result = subprocess.run(batch, capture_output=True, text=True) + assert result.returncode and "graphics request key mismatch" in result.stderr + for case, element, error in ( + ("stream", b"position 0 2 3 4294967295 0 0", ""), + ("instanced", b"POSITION 0 2 5 16 1 2", ""), + ("semantic", b"COLOR 0 2 0 0 0 0", "missing vertex input"), + ("component", b"POSITION 0 3 0 0 0 0", "vertex format disagrees")): + folder_input = folder/case + publish(folder_input, vertex(True), patched_pixel(), root, b"ia1 1\n"+element+b"\n") + batch[-2] = folder_input + for warm in range(1 if error else 2): + result = subprocess.run(batch, capture_output=True, text=True) + if error: + assert result.returncode and error in result.stderr, result.stderr + else: + assert result.returncode == 0, result.stderr + assert f"frontend_cache_hit={warm}" in result.stdout + check("patch-range", "gfx1013-container-ps", patched_pixel(3), "record outside") + check("pixel", "gfx1013-direct-constant-ps", words(0x7e0002f2, 0xf800180f, 0, end)) + + +if __name__ == "__main__": + main() diff --git a/tests/native_dpp_mirror_check.py b/tests/native_dpp_mirror_check.py new file mode 100644 index 000000000..9a3ac0c0e --- /dev/null +++ b/tests/native_dpp_mirror_check.py @@ -0,0 +1,149 @@ +"""GPU differential for source-built, direct-DXIL guest row mirrors.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_direct_container_check import patched_pixel, vertex +from native_scalar_lds_check import scalar, sop1, vmove + + +def vop2(op, dst, src0, src1): + return op << 25 | dst << 17 | src1 << 9 | src0 + + +def compute_program(control, active): + # v1 holds a unique value even after guest EXEC is narrowed. The DPP + # src0 aliases the destination. A distinct local src1 distinguishes + # suppress-write from adding zero when the mirror points outside EXEC. + return [sop1(3,20,4), sop1(3,21,128), 0xf4080000 | 32 << 6 | 10, 0xfa000020, + scalar(0x1e,7,5,135), vop2(0x1a,8,130,0), vop2(0x25,8,7,8), + vop2(0x25,1,145,0), vop2(0x25,2,148,0), sop1(3,126,255), active, + vop2(0x25,1,250,2), 0xff000001 | control, sop1(3,126,193), + 0xe0701000, 0x80080108, 0xbf810000] + + +def pixel_program(start, half, control): + # Explicitly populate a guest register array even when the rasterizer + # schedules fewer than eight pixels. Read back four individual guest lanes. + program = [sop1(0x25,62,193), vmove(17,128)] + for lane in range(16): + program += [0xd7610011, (129+lane) | ((128+start+lane) << 9)] + program += [vmove(17,250), 0xff040011 | control << 8] + for col in range(4): + program += [0xd7600000 | col, 273 | ((128+start+4*half+col) << 9)] + program += [sop1(4,126,62)] + program += [0x7e000c00 | col << 17 | col for col in range(4)] + return patched_pixel(len(program), program, export=(0xf800180f,0x03020100)) + + +def reduction_program(): + # Seed two guest wave64 halves differently, including unsigned values + # above INT_MAX. Inspect both the intermediate 32-lane extrema and + # the 64-lane extrema after the readlane/broadcast step. + program = [sop1(0x25,62,193), vmove(17,144)] + for lane, value in ((12,1),(19,27),(33,3),(60,39)): + program += [0xd7610011, (128+value) | ((128+lane) << 9)] + program += [0xd7610011, 193 | (155 << 9)] # lane 27 holds UINT_MAX + for output, op in enumerate((0x13,0x14)): + program += [vmove(18,273)] + for control in (0xb1,0x4e,0x141,0x140): + program += [vop2(op,18,250,18), 0xff040012 | (control << 8)] + program += [0xd7780013,274 | 128 << 9 | 128 << 18, vop2(op,18,274,19), + 0xd7600000 | output,274 | 191 << 9, + 0xd7600004,274 | 128 << 9,vop2(op,18,4,18), + 0xd7600002 | output,274 | 191 << 9] + # Keep the low byte of each result so the uint max is observable as 255. + program += [sop1(4,126,62)] + for col in range(4): + program += [vmove(col,col),vop2(0x1b,col,255,col),255,0x7e000c00 | col << 17 | (256+col)] + return patched_pixel(len(program),program,export=(0xf800180f,0x03020100)) + + +def vertex_program(last_id, branchless=False): + program = [vmove(1,243),vmove(2,243),vmove(3,128),vmove(4,242)] + # Start at (-1,-1). Separate masked arms move vertices 1 and 2 to + # (3,-1) and (-1,3). Each contains a scalar branch over the literal move. + for reg, vertex_id in ((1,1),(2,last_id)): + if branchless: + program += [sop1(4,8,126),0xbf8cc07f,0x7d240080 | vertex_id, + vmove(reg,255),0x40400000,0x8afe7e08,vmove(reg,243),sop1(4,126,8)] + else: + program += [0x7d040080 | vertex_id, 0xbe88246a, 0xbf880004, + 0xbf008080,0xbf840002,vmove(reg,255),0x40400000,0xbefe0408] + return vertex(program=program+[0xf80008cf,0x04030201,0xbf810000]) + + +def main(cli, replay, raster, sdk): + reverse = (7,6,5,4,3,2,1,0) + sentinel = 0x69696969 + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + shader = work/"fixture.hlsl" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"\n' + 'float4 vs(uint id:SV_VertexID):SV_Position {' + 'return float4(id==1?3:-1,id==2?3:-1,0,1);}') + dxc = Path(sdk)/"dxc.exe" + root, vs = work/"root", work/"vs.cso" + subprocess.run([dxc,"-T","rootsig_1_1","-E","SIG","-Fo",root,shader],check=True) + subprocess.run([dxc,"-T","vs_6_6","-E","vs","-Fo",vs,shader],check=True) + sa = struct.pack("<7I",0,0,0,32 | 1 << 16,1,0,0x8a) + sparse = 0x955ad3b6 + for mask, active, fi, zero in ((7,0xffffffff,1,0), (15,0xffffffff,1,0), + (7,sparse,1,0), (7,sparse,0,0), (7,sparse,0,1)): + ctrl = ((0x141 if mask == 7 else 0x140) << 8) | fi << 18 | zero << 19 + marker = write_request(work,compute_program(ctrl, active),root.read_bytes(),sa) + dest = work/"out.bin" + result = subprocess.run([replay,sdk,marker,work/"cache","0",dest,"--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + expected = [sentinel]*2064 + for lane in range(32): + peer = lane // (mask+1) * (mask+1) + mask - lane % (mask+1) + own, value = lane+20, lane+17 + if active & (1 << lane): + if fi or active & (1 << peer): value = own + peer + 17 + elif zero: value = own + for group in range(2): + expected[8+group*32+lane] = value + actual = struct.unpack("<2064I",dest.read_bytes()) + assert list(actual) == expected, (mask, fi, zero, actual[8:40], expected[8:40]) + print(f"CS xor={mask} EXEC={active:08x} FI={fi} BC={zero}: 64 results and guards matched") + for start, half, ctrl in ((0,0,0x141),(0,1,0x141),(32,0,0x141),(32,1,0x141),(0,0,0x140)): + src, ps = work/"pixel.fssm", work/"pixel.cso" + src.write_bytes(pixel_program(start,half,ctrl)) + subprocess.run([cli,sdk,work/"cache","gfx1013-container-ps",src,ps],check=True) + expected = [1 + x for x in reverse[4*half:4*half+4]] + reference = work/"pixels.bin" + reference.write_bytes(struct.pack("<4f",*expected)*8) + result = subprocess.run([raster,"hardware","--startup-pixel-words",vs,ps,"4","2",reference], + capture_output=True,text=True) + if result.returncode == 77: + return 77 + if ctrl == 0x140: + assert result.returncode == 1 and "8 of 8 pixels differ" in result.stderr, result.stderr + elif result.returncode: + raise AssertionError(result.stderr) + print(f"PS guest lanes {start+4*half}..{start+4*half+3}: " + + (f"matched {expected}" if ctrl == 0x141 else "wrong full-row control differed at all 8 pixels")) + src.write_bytes(reduction_program()) + subprocess.run([cli,sdk,work/"cache","gfx1013-container-ps",src,ps],check=True) + reference.write_bytes(struct.pack("<4f",3,39,1,255)*8) + subprocess.run([raster,"hardware","--startup-pixel-words",vs,ps,"4","2",reference],check=True) + print("PS unsigned min/max, two 32-lane halves and final wave64 reduction matched [3,39,1,255]") + for branchless,last_id in ((False,2),(False,1),(True,2),(True,1)): + src.write_bytes(vertex_program(last_id,branchless)) + subprocess.run([cli,sdk,work/"cache","gfx1013-container-vs",src,vs],check=True) + result = subprocess.run([raster,"hardware","--startup-pixel-words",vs,ps,"4","2",reference], + capture_output=True,text=True) + if last_id == 2: result.check_returncode() + else: assert result.returncode == 1 and "8 of 8 pixels differ" in result.stderr, result.stderr + print("Translated masked VS and reduction PS matched 8 pixels; collapsed triangle lost all 8") + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_dpp_quad_check.py b/tests/native_dpp_quad_check.py new file mode 100644 index 000000000..cd029641e --- /dev/null +++ b/tests/native_dpp_quad_check.py @@ -0,0 +1,132 @@ +"""Direct compute DPP16 quad_perm readback and compile-only refusals.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_dpp_mirror_check import vop2 +from native_scalar_lds_check import scalar, sop1, vmove + + +OR, ADD, SUBREV = 0x1C, 0x03, 0x05 +SWAP = (1, 0, 3, 2) +ALL = 0xFFFFFFFF +SPARSE = ALL ^ (1 << 1) +SENTINEL = 0x69696969 + + +def compute_program(op, pattern, active=ALL, fi=False, bound_zero=False): + control = 0xFF000001 | pattern << 8 | fi << 18 | bound_zero << 19 + # Reuse the mirror fixture's table load and addressing ABI. Two groups + # write 32 consecutive words each, after eight guard words. + program = [sop1(3, 20, 4), sop1(3, 21, 128), + 0xF4080000 | 32 << 6 | 10, 0xFA000020, + scalar(0x1e, 7, 5, 135), vop2(0x1a, 8, 130, 0), vop2(0x25, 8, 7, 8), + vop2(0x25, 1, 145, 0)] + if op == OR: + program += [vmove(2, 192)] # inline integer 64 + else: + program += [vop2(0x25, 2, 148, 0), + 0x7E000000 | 1 << 17 | 6 << 9 | 257, # v_cvt_f32_u32 v1, v1 + 0x7E000000 | 2 << 17 | 6 << 9 | 258] # v_cvt_f32_u32 v2, v2 + # Seed both registers under full EXEC, alias src0 with dst, and restore + # EXEC before storing so suppressed writes are visible in the readback. + return program + [sop1(3, 126, 255), active, + vop2(op, 1, 250, 2), control, sop1(3, 126, 193), + 0xE0701000, 0x80080108, 0xBF810000] + + +def reference(op, selection, active, fi, bound_zero): + initial = list(range(17, 49)) + enabled = [(active >> lane) & 1 for lane in range(32)] + result = initial.copy() + for base in range(0, 32, 4): + for offset, source in enumerate(selection): + lane, peer = base + offset, base + source + if not enabled[lane]: + continue + if fi or enabled[peer]: + src0 = initial[peer] + elif bound_zero: + src0 = 0 + else: + continue + if op == OR: + result[lane] = src0 | 64 + elif op == ADD: + result[lane] = src0 + (lane + 20) + else: + result[lane] = (lane + 20) - src0 + if op != OR: + return struct.unpack("<32I", struct.pack("<32f", *result)) + return tuple(result) + + +def request(work, root, program, threads=32): + sa = struct.pack("<7I", 0, 0, 0, threads | 1 << 16, 1, 0, 0x8A) + return write_request(work, program, root, sa) + + +def controls(cli, sdk, work, root): + for pattern, threads, error in ( + (0xB1, 32, None), + (0x101, 32, "unsupported DPP lane selection"), # row_shl:1 + (0xB1, 30, "DPP quad_perm needs a thread count divisible by four")): + marker = request(work, root, compute_program(OR, pattern), threads) + output = marker.with_suffix(".cso") + result = subprocess.run([cli, sdk, work / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True) + if error is None: + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + else: + assert result.returncode and error in result.stderr, (result.stdout, result.stderr) + assert not output.exists(), output + print(error) + return 0 + + +def hardware(replay, sdk, work, root): + # Manual mutants that must fail: read the permutation in reversed lane + # order (rotation), or ignore BOUND_CTRL (sparse EXEC add with BC=1). + cases = ( + ("or swap", OR, SWAP, ALL, False, False), + ("add swap", ADD, SWAP, ALL, False, False), + ("subrev broadcast", SUBREV, (0, 0, 0, 0), ALL, False, False), + ("or identity", OR, (0, 1, 2, 3), ALL, False, False), + ("or rotation", OR, (1, 2, 3, 0), ALL, False, False), + ("add disabled source, zero", ADD, SWAP, SPARSE, False, True), + ("add disabled source, preserve", ADD, SWAP, SPARSE, False, False), + ("add disabled source, fetch", ADD, SWAP, SPARSE, True, False), + ) + for name, op, selection, active, fi, bound_zero in cases: + pattern = sum(source << (2 * lane) for lane, source in enumerate(selection)) + marker = request(work, root, compute_program(op, pattern, active, fi, bound_zero)) + output = work / "out.bin" + result = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + lanes = reference(op, selection, active, fi, bound_zero) + expected = (SENTINEL,) * 8 + lanes * 2 + (SENTINEL,) * (2064 - 72) + actual = struct.unpack("<2064I", output.read_bytes()) + mismatch = next((i for i, pair in enumerate(zip(actual, expected)) if pair[0] != pair[1]), None) + assert mismatch is None, (name, mismatch, actual[mismatch], expected[mismatch]) + print(f"{name}: 64 results and guards matched") + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / "root.hlsl" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, shader], check=True) + return {"controls": controls, "hardware": hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_dxil_llvm_ident_check.py b/tests/native_dxil_llvm_ident_check.py new file mode 100644 index 000000000..89e453e5a --- /dev/null +++ b/tests/native_dxil_llvm_ident_check.py @@ -0,0 +1,273 @@ +"""Verify direct DXIL !llvm.ident emission and D3D12 draw execution (#2915).""" +import ctypes +from ctypes import POINTER, Structure, byref, c_char_p, c_int32, c_size_t, c_uint32, c_void_p +from pathlib import Path +import re +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import uuid + +from native_direct_container_check import ( + compute, + interpolated_pixel, + patched_pixel, + publish, + signature, + signature_rows, + vertex, + words, +) + + +class _GUID(Structure): + _fields_ = [ + ("Data1", c_uint32), + ("Data2", ctypes.c_uint16), + ("Data3", ctypes.c_uint16), + ("Data4", ctypes.c_ubyte * 8), + ] + + @classmethod + def parse(cls, text: str) -> "_GUID": + return cls.from_buffer_copy(uuid.UUID(text).bytes_le) + + +_CLSID_DXC_UTILS = _GUID.parse("6245d6af-66e0-48fd-80b4-4d271796748c") +_IID_IDXC_UTILS = _GUID.parse("4605c4cb-2019-492a-ada4-65f20bb7d67f") +_CLSID_DXC_ASSEMBLER = _GUID.parse("d728db68-f903-4f80-94cd-dccf76ec7151") +_IID_IDXC_ASSEMBLER = _GUID.parse("091f7a26-1c1f-4948-904b-e6e3a8a771d5") +_CLSID_DXC_VALIDATOR = _GUID.parse("8ca3e215-f728-4cf3-8cdd-88af917587a1") +_IID_IDXC_VALIDATOR = _GUID.parse("a6e82bd2-1fd7-4826-9811-2857e797f49a") + + +def _vfn(obj, index: int, restype, *argtypes): + vtbl = ctypes.cast(ctypes.cast(obj, POINTER(c_void_p))[0], POINTER(c_void_p)) + return ctypes.WINFUNCTYPE(restype, c_void_p, *argtypes)(vtbl[index]) + + +def _blob_bytes(blob: c_void_p) -> bytes: + ptr = _vfn(blob, 3, c_void_p)(blob) + size = _vfn(blob, 4, c_size_t)(blob) + return ctypes.string_at(ptr, size) + + +def _take_result(op_result: c_void_p) -> tuple[bytes, c_void_p]: + status = c_int32() + assert _vfn(op_result, 3, c_int32, POINTER(c_int32))(op_result, byref(status)) == 0 + if status.value < 0: + err = c_void_p() + _vfn(op_result, 5, c_int32, POINTER(c_void_p))(op_result, byref(err)) + detail = _blob_bytes(err).decode("utf-8", "replace") if err.value else f"{status.value:#x}" + raise RuntimeError(f"DXIL assembly/validation failed: {detail}") + blob = c_void_p() + assert _vfn(op_result, 4, c_int32, POINTER(c_void_p))(op_result, byref(blob)) == 0 + return _blob_bytes(blob), blob + + +def assemble_and_validate(sdk: Path, ir_text: str) -> bytes: + dxc_dll = ctypes.WinDLL(str(sdk / "dxcompiler.dll")) + dxil_dll = ctypes.WinDLL(str(sdk / "dxil.dll")) + for dll in (dxc_dll, dxil_dll): + dll.DxcCreateInstance.argtypes = [POINTER(_GUID), POINTER(_GUID), POINTER(c_void_p)] + dll.DxcCreateInstance.restype = c_int32 + + utils, assembler, validator = c_void_p(), c_void_p(), c_void_p() + assert dxc_dll.DxcCreateInstance(byref(_CLSID_DXC_UTILS), byref(_IID_IDXC_UTILS), byref(utils)) == 0 + assert dxc_dll.DxcCreateInstance(byref(_CLSID_DXC_ASSEMBLER), byref(_IID_IDXC_ASSEMBLER), byref(assembler)) == 0 + assert dxil_dll.DxcCreateInstance(byref(_CLSID_DXC_VALIDATOR), byref(_IID_IDXC_VALIDATOR), byref(validator)) == 0 + + encoded = ir_text.encode("utf-8") + source_blob = c_void_p() + assert _vfn(utils, 6, c_int32, c_char_p, c_uint32, c_uint32, POINTER(c_void_p))( + utils, encoded, len(encoded), 65001, byref(source_blob) + ) == 0 + assembled = c_void_p() + assert _vfn(assembler, 3, c_int32, c_void_p, POINTER(c_void_p))(assembler, source_blob, byref(assembled)) == 0 + _, container_blob = _take_result(assembled) + validated = c_void_p() + assert _vfn(validator, 3, c_int32, c_void_p, c_uint32, POINTER(c_void_p))( + validator, container_blob, 1, byref(validated) + ) == 0 + cso_bytes, _ = _take_result(validated) + return cso_bytes + + +def has_llvm_ident(disassembly: str, expected: str = "x2w") -> bool: + match = re.search(r"^!llvm\.ident\s*=\s*!\{!(\d+)\}\s*$", disassembly, re.MULTILINE) + if not match: + return False + node_id = match.group(1) + node = re.search(rf"^!{node_id}\s*=\s*!\{{!\"([^\"]*)\"\}}\s*$", disassembly, re.MULTILINE) + return bool(node and node.group(1) == expected) + + +def fullscreen_triangle_vs() -> bytes: + # Fullscreen triangle (-1, -1), (4, -1), (-1, 4) from SV_VertexID in v0. + program = [ + 0x7E0C02F6, # v_mov_b32_e32 v6, 4.0 + 0x7D040081, # v_cmp_eq_i32_e32 vcc, 1, v0 + 0x02020CF3, # v_cndmask_b32_e32 v1, -1.0, v6, vcc + 0x7D040082, # v_cmp_eq_i32_e32 vcc, 2, v0 + 0x02040CF3, # v_cndmask_b32_e32 v2, -1.0, v6, vcc + 0x7E060280, # v_mov_b32_e32 v3, 0 + 0x7E0E02F2, # v_mov_b32_e32 v7, 1.0 + 0xF80008CF, 0x07030201, # exp pos0 v1, v2, v3, v7 done + 0xBF810000, # s_endpgm + ] + return vertex(program=program) + + +def check_containers(cli: Path, sdk: Path) -> None: + dxc = sdk / "dxc.exe" + with TemporaryDirectory() as tmp: + work = Path(tmp) + cache = work / "cache" + + def compile_and_dump(name: str, profile: str, payload: bytes) -> tuple[Path, str]: + src = work / f"{name}.in" + cso = work / f"{name}.cso" + src.write_bytes(payload) + run = subprocess.run([cli, sdk, cache, profile, src, cso], capture_output=True, text=True) + assert run.returncode == 0, (name, profile, run.stdout, run.stderr) + dump = subprocess.check_output([dxc, "-dumpbin", cso], text=True) + assert has_llvm_ident(dump), f"{name} ({profile}) missing !llvm.ident:\n{dump}" + return cso, dump + + cs_code = words(0x7E000280, 0xBF810000) + compile_and_dump("compute", "gfx1013-container-cs", compute(cs_code)) + compile_and_dump("vertex", "gfx1013-container-vs", fullscreen_triangle_vs()) + _, ps_dump = compile_and_dump( + "pixel", + "gfx1013-container-ps", + patched_pixel(1, [0x7E0002F2], input_signature=((b"OSG1", signature(b"SV_Target", 64)),)), + ) + const_words = struct.pack("<8I", 0x7E0002F2, 0x7E0202F0, 0x7E0402FF, 0x3E800000, 0x7E0602F4, 0xF800180F, 0x03020100, 0xBF810000) + _, const_ps_dump = compile_and_dump("direct_const_ps", "gfx1013-direct-constant-ps", const_words) + + # Rectangle geometry expansion emits VS, GS and PS through DxilModule. + inputs_dir, rect_out = work / "rect_in", work / "rect_out" + vs_rect = vertex( + program=[0x7E020B00, 0xF80000CF, 0x01010101, 0xF8000A0F, 0x01010101, 0xBF810000], + varying=True, + extra=((b"OSG1", signature_rows([(b"TEXCOORD", 0, 3, 0, 15), (b"SV_Position", 1, 3, 1, 15)])),), + ) + root = b"DXBC" + bytes(16) + words(1, 68, 1, 36) + b"RTS0" + words(24, 2, 0, 24, 0, 24, 0) + stem = publish(inputs_dir, vs_rect, interpolated_pixel(), root) + subprocess.run([cli, sdk, cache, "gfx1013-container-rect", "--requests", inputs_dir, rect_out], check=True) + for stage in ("vs", "gs", "ps"): + stage_dump = subprocess.check_output([dxc, "-dumpbin", rect_out / f"{stem}.{stage}.cso"], text=True) + assert has_llvm_ident(stage_dump), f"rect.{stage} missing !llvm.ident" + + # Negative control: SDK validation accepts a module without !llvm.ident, + # and has_llvm_ident rejects the stripped container across both direct emitters. + for label, dump in (("container_ps", ps_dump), ("direct_const_ps", const_ps_dump)): + ir_text = "\n".join( + line for line in dump.splitlines() if not line.startswith(";") and not line.startswith("!llvm.ident") + ) + "\n" + stripped_cso = work / f"{label}_stripped.cso" + stripped_cso.write_bytes(assemble_and_validate(sdk, ir_text)) + stripped_dump = subprocess.check_output([dxc, "-dumpbin", stripped_cso], text=True) + assert not has_llvm_ident(stripped_dump), f"{label} negative control kept !llvm.ident" + + print("direct DXIL !llvm.ident container and negative controls passed (cs, vs, gs, ps, direct-constant-ps)") + + +def check_draws(cli: Path, raster: Path, sdk: Path, backend: str) -> None: + with TemporaryDirectory() as tmp: + work = Path(tmp) + cache = work / "cache" + vs_in, vs_cso = work / "vs.in", work / "vs.cso" + vs_in.write_bytes(fullscreen_triangle_vs()) + subprocess.run([cli, sdk, cache, "gfx1013-container-vs", vs_in, vs_cso], check=True) + + # Case 1: gfx1013-direct-constant-ps -> (1.0, 0.5, 0.25, 2.0) + const_in, const_cso = work / "const_ps.in", work / "const_ps.cso" + const_words = [0x7E0002F2, 0x7E0202F0, 0x7E0402FF, 0x3E800000, 0x7E0602F4, 0xF800180F, 0x03020100, 0xBF810000] + const_in.write_bytes(struct.pack("<8I", *const_words)) + subprocess.run([cli, sdk, cache, "gfx1013-direct-constant-ps", const_in, const_cso], check=True) + + expected = work / "expected.bin" + expected.write_bytes(struct.pack("<4f", 1.0, 0.5, 0.25, 2.0) * 16) + run = subprocess.run( + [raster, backend, "--startup-pixel-words", vs_cso, const_cso, "8", "2", expected], + capture_output=True, + text=True, + ) + if run.returncode == 77: + sys.exit(77) + assert run.returncode == 0, (run.stdout, run.stderr) + if "debug_layer=enabled" in run.stdout: + assert "debug_errors=0 debug_warnings=0" in run.stdout, run.stdout + + # Negative control 1: change alpha 2.0 -> 4.0 in gfx1013-direct-constant-ps; readback must fail. + bad_words = list(const_words) + bad_words[4] = 0x7E0602F6 # v3 = 4.0f + bad_in, bad_cso = work / "bad_const_ps.in", work / "bad_const_ps.cso" + bad_in.write_bytes(struct.pack("<8I", *bad_words)) + subprocess.run([cli, sdk, cache, "gfx1013-direct-constant-ps", bad_in, bad_cso], check=True) + bad_run = subprocess.run( + [raster, backend, "--startup-pixel-words", vs_cso, bad_cso, "8", "2", expected], + capture_output=True, + text=True, + ) + assert bad_run.returncode != 0, "mutated gfx1013-direct-constant-ps unexpectedly matched" + + # Case 2: gfx1013-container-ps exporting distinct constants -> (0.5, 2.0, 1.0, 4.0) + ps_in, ps_cso = work / "container_ps.in", work / "container_ps.cso" + ps_seq = [0x7E0002F0, 0x7E0202F4, 0x7E0402F2, 0x7E0602F6] + ps_in.write_bytes( + patched_pixel( + len(ps_seq), + ps_seq, + export=(0xF800180F, 0x03020100), + input_signature=((b"OSG1", signature(b"SV_Target", 64)),), + ) + ) + subprocess.run([cli, sdk, cache, "gfx1013-container-ps", ps_in, ps_cso], check=True) + expected.write_bytes(struct.pack("<4f", 0.5, 2.0, 1.0, 4.0) * 16) + run2 = subprocess.run( + [raster, backend, "--startup-pixel-words", vs_cso, ps_cso, "8", "2", expected], + capture_output=True, + text=True, + ) + assert run2.returncode == 0, (run2.stdout, run2.stderr) + if "debug_layer=enabled" in run2.stdout: + assert "debug_errors=0 debug_warnings=0" in run2.stdout, run2.stdout + + # Negative control 2: swap exported channels in gfx1013-container-ps; readback must fail. + bad_ps_in, bad_ps_cso = work / "bad_container_ps.in", work / "bad_container_ps.cso" + bad_ps_in.write_bytes( + patched_pixel( + len(ps_seq), + ps_seq, + export=(0xF800180F, 0x03020001), + input_signature=((b"OSG1", signature(b"SV_Target", 64)),), + ) + ) + subprocess.run([cli, sdk, cache, "gfx1013-container-ps", bad_ps_in, bad_ps_cso], check=True) + bad_run2 = subprocess.run( + [raster, backend, "--startup-pixel-words", vs_cso, bad_ps_cso, "8", "2", expected], + capture_output=True, + text=True, + ) + assert bad_run2.returncode != 0, "mutated gfx1013-container-ps unexpectedly matched" + + print(run2.stdout.strip()) + + +def main() -> None: + mode = sys.argv[1] + if mode == "container": + _, _, cli, sdk = sys.argv + check_containers(Path(cli), Path(sdk)) + elif mode == "draw": + _, _, cli, raster, sdk, backend = sys.argv + check_draws(Path(cli), Path(raster), Path(sdk), backend) + else: + raise ValueError(f"unknown mode: {mode}") + + +if __name__ == "__main__": + main() diff --git a/tests/native_f16_alu_check.py b/tests/native_f16_alu_check.py new file mode 100644 index 000000000..ae8388bb5 --- /dev/null +++ b/tests/native_f16_alu_check.py @@ -0,0 +1,588 @@ +"""v_add_f16, v_sub_f16, v_subrev_f16 and v_mul_f16 in the direct C++ compute path. + +Each source contributes its low 16 bits. abs clears bit 15 of that half, then neg toggles it. +The operation runs in f32 and rounds to binary16 the way v_cvt_f16_f32 does. The result is the low +16 bits and the destination's high half keeps its value (LLVM GCNSubtarget::zeroesHigh16BitsOfDest: +"On gfx10, all 16-bit instructions preserve the high bits"). Every destination holds HI_A in its high +half before the operation, so each stored word is HI_A | result. The reference is half_op in f16_packed_model.py (sub is an add of +the negated second source, subrev swaps the sources). NaN payloads are compared by class. + + native_f16_alu_check.py model + no dumper and no GPU: the case table, the f32 rounding cross-check, and the two mutants + native_f16_alu_check.py ir DUMPER + build one compute container, dump its DXIL text, evaluate it, and require the named refusals + native_f16_alu_check.py gpu STORE_REPLAY SDK + compute readback of the same words (exit 77 when the adapter cannot run a wave32 shader) +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +import f16_packed_model as M +from native_compute_clear_check import write_request +from native_direct_container_check import pack, words +from native_scalar_lds_check import scalar, sop1, vmove + +GROUPS = 2 +WORDS = 2064 +BASE = 8 +STRIDE = 128 +SHIFT = 9 +assert 4 * STRIDE == 1 << SHIFT + +OPS = ('add', 'sub', 'subrev', 'mul') +OP_CODE = {'add': 0x32, 'sub': 0x33, 'subrev': 0x34, 'mul': 0x35} +# Binary16 rounding of the nine inline float encodings, in encoding order. +INLINE_F16 = { + 240: 0x3800, 241: 0xb800, 242: 0x3c00, 243: 0xbc00, 244: 0x4000, + 245: 0xc000, 246: 0x4400, 247: 0xc400, 248: 0x3118, +} +PAIRS = [ + (0x3c00, 0x4000), (0x0000, 0x8000), (0x8000, 0x8000), (0x0001, 0x0000), + (0x0001, 0x0001), (0x7c00, 0x3c00), (0x7c00, 0xfc00), (0x7e00, 0x3c00), + (0x7bff, 0x7bff), (0x3c00, 0x1000), (0x3c01, 0x1000), (0x7c01, 0x0001), +] +HI_A = 0xABCD0000 +HI_B = 0x789A0000 + + +def binary16(op, a, b): + """Low 16 bits of one RDNA 2 operation. sub negates the second source; subrev swaps.""" + a &= 0xffff + b &= 0xffff + if op == 'sub': + return M.half_op('add', a, b ^ 0x8000) + if op == 'subrev': + return M.half_op('add', b, a ^ 0x8000) + return M.half_op(op, a, b) + + +def modified(bits, abs_mask, neg, index): + if abs_mask & (1 << index): + bits &= 0x7fff + if neg & (1 << index): + bits ^= 0x8000 + return bits & 0xffff + + +def same_half(got, want): + """Bit equality of two stored words: the high half must be the kept HI_A, the low halves equal. Any NaN + matches any NaN.""" + if got >> 16 != HI_A >> 16 or want >> 16 not in (0, HI_A >> 16): + return False + left, right = got & 0xffff, want & 0xffff + if M.is_nan(left) or M.is_nan(right): + return M.is_nan(left) and M.is_nan(right) + return left == right + + +def _u32(value): + return value & 0xffffffff + + +def packed_half_rne(bits): + """The integer round used by packed_half_rne in the direct compute lowering.""" + bits = _u32(bits) + sign = (bits >> 16) & 32768 + mag = bits & 0x7fffffff + exp = mag >> 23 + frac = mag & 0x7fffff + + def round_shift(value, shift, half): + odd = _u32(value >> shift) & 1 + bias = _u32(_u32(half - 1) + odd) + return _u32(_u32(value + bias) >> shift) + + normal = round_shift(_u32(mag - 939524096), 13, 4096) + sub_range = 102 <= exp <= 112 + shift = _u32(126 - exp) if sub_range else 14 + half = _u32(1 << _u32(shift - 1)) + sub = round_shift(frac | 8388608, shift, half) + if exp <= 112: + result = sub if sub_range else 0 + else: + result = normal + if exp > 142: + result = 31744 + if mag > 2139095040: + result = (frac >> 13) | 32256 + return (result | sign) & 65535 + + +def f32_half(op, a, b): + """f32 operation of two exact f16 values, then the integer binary16 round.""" + left, right = M.h2f(a), M.h2f(b) + value = {'add': left + right, 'sub': left - right, 'subrev': right - left, 'mul': left * right}[op] + bits = struct.unpack(' right, 'uge': left >= right, 'ult': left < right, 'ule': left <= right, + 'sgt': sl > sr, 'sge': sl >= sr, 'slt': sl < sr, 'sle': sl <= sr, + }[pred] + + +def _f32(bits): + return struct.unpack('> (right & 31) + elif op == 'ashr': + result = _signed(left) >> (right & 31) + elif op in ('urem', 'udiv'): + result = 0 if right == 0 else (left % right if op == 'urem' else left // right) + else: + result = {'add': left + right, 'sub': left - right, 'mul': left * right, + 'and': left & right, 'or': left | right, 'xor': left ^ right}[op] + values[name] = ('i32', result & 0xffffffff) + return + logic = re.fullmatch(r'(and|or|xor) i1 (\S+), (\S+)', rhs) + if logic: + left, right = _i1(logic.group(2), values), _i1(logic.group(3), values) + result = {'and': left & right, 'or': left | right, 'xor': left ^ right}[logic.group(1)] + values[name] = ('i1', result) + return + extended = re.fullmatch(r'zext i1 (\S+) to i32', rhs) + if extended: + values[name] = ('i32', _i1(extended.group(1), values)) + return + if rhs.startswith('bitcast i32 '): + token = rhs.removeprefix('bitcast i32 ').removesuffix(' to float') + values[name] = ('float', _i32(token, values)) + return + if rhs.startswith('bitcast float '): + token = rhs.removeprefix('bitcast float ').removesuffix(' to i32') + kind, bits = values[token] + if kind != 'float': + raise AssertionError(rhs) + values[name] = ('i32', bits) + return + floated = re.fullmatch(r'(fadd|fsub|fmul) float (\S+), (\S+)', rhs) + if floated: + def bits_of(token): + if token.startswith('%'): + kind, bits = values[token] + if kind != 'float': + raise AssertionError(rhs) + return bits + return struct.unpack(' len(want) + print('native_f16_alu model: %d results match f32-then-round; ' + 'a sub/subrev swap and a zeroed upper half are rejected' % len(items)) + + +def run_ir(dumper): + items = all_cases() + check_model(items) + code, want = program(items) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = dump(dumper, work, code, 'alu') + assert run.returncode == 0, run.stderr + text = run.stdout + assert 'legacyF16ToF32' in text and 'legacyF32ToF16' not in text, 'rounding opcode' + assert 'fadd float' in text and 'fsub float' in text and 'fmul float' in text + assert '939524096' in text, 'integer nearest-even rounding' + stores = sorted(interpret(text)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, hex(got), hex(expected)) for i, ((_, got), expected) in enumerate(zip(stores, want)) + if not same_half(got, expected)] + assert not bad, bad[:8] + for refused, why in refusal_programs(): + run = dump(dumper, work, refused, 'refused') + assert run.returncode != 0 and why in run.stderr, (why, run.returncode, run.stderr) + print('native_f16_alu IR: %d results match the model; %d refusals carry the named diagnostic' % + (len(want), len(refusal_programs()))) + + +def group_offsets(count): + offsets = [[BASE + group * STRIDE + i for i in range(count)] for group in range(GROUPS)] + flat = [index for group in offsets for index in group] + assert len(set(flat)) == len(flat) + assert 0 <= min(flat) and max(flat) < WORDS + return offsets + + +def run_gpu(gpu, sdk): + items = all_cases() + code, want = program(items) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src, root = work / 'root.hlsl', work / 'root.bin' + src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([str(Path(sdk) / 'dxc.exe'), '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, src], check=True) + sa = struct.pack('<7I', 0, 0, 0, 32 | (1 << 16), 1, 0, 0x80 | (5 << 1)) + marker = write_request(work, code, root.read_bytes(), sa) + dest = work / 'f16-alu-readback.bin' + run = subprocess.run([gpu, sdk, str(marker), str(work / 'cache'), '0', str(dest), '--direct']) + if run.returncode == 77: + sys.exit(77) + run.check_returncode() + offsets = group_offsets(len(want)) + expected = [0x69696969] * WORDS + results = {} + for group in range(GROUPS): + for slot, value in zip(offsets[group], want): + expected[slot] = value + results[slot] = value + actual = struct.unpack('<2064I', dest.read_bytes()) + bad = [] + for index, (got, model) in enumerate(zip(actual, expected)): + # NaN payloads are not portable. Finite values and infinities match bit for bit, + # and every result keeps HI_A in its upper half. Words outside the stores stay at the fill. + ok = same_half(got, results[index]) if index in results else got == model + if not ok: + bad.append((index, hex(got), hex(model))) + assert not bad[:10], bad[:10] + print('native_f16_alu GPU: %d words matched the model, high half kept' % (GROUPS * len(want))) + + +if __name__ == '__main__': + if len(sys.argv) == 2 and sys.argv[1] == 'model': + run_model() + elif len(sys.argv) == 3 and sys.argv[1] == 'ir': + run_ir(sys.argv[2]) + elif len(sys.argv) == 4 and sys.argv[1] == 'gpu': + run_gpu(sys.argv[2], sys.argv[3]) + else: + sys.exit(__doc__) diff --git a/tests/native_gather_compare_check.py b/tests/native_gather_compare_check.py new file mode 100644 index 000000000..e60de81db --- /dev/null +++ b/tests/native_gather_compare_check.py @@ -0,0 +1,94 @@ +"""image_gather4_c_lz in the direct C++ image path (#2969). + + native_gather_compare_check.py + +image_gather4_c_lz compares the red component of the four texels of a gather footprint at the view's first mip +against a reference, the first address dword, and returns the four results. The direct frontend lowers +it to DXIL textureGatherCmp (opcode 74) with channel 0, the comparison sampler under the existing comparison field +checks and the base-level sampler fix of image_gather4_lz, on 2D and 2D-array images with dmask 0x1. The programs +reuse comparison_program() of native_direct_container_check.py (clamp X/Y, point with TRUNC_COORD, LESS). + +Checks: a compute container compiles and its module calls textureGatherCmp with channel 0, u and v from v1 and v2 +and the reference v0 as compare value (the same program with image_sample_c_lz compiles as a control); refusals by +message for dmask 0x2, a cube and a 3D image, d16, image_gather4_c (implicit LOD), _c_l and _c_b; and, +through native_recording_check --graphics-sampler, WARP creates the graphics pipeline of the program of +native_graphics_comparison_pso_warp with the comparison sample replaced by this gather. +""" +import pathlib +import re +import subprocess +import sys +import tempfile + +from native_direct_container_check import comparison_program, compute, patched_pixel, vertex, words + +REFUSED = 'direct image opcode or descriptor modifiers' + + +def main(compiler, sdk, probe): + sdk = pathlib.Path(sdk) + with tempfile.TemporaryDirectory() as tmp: + folder = pathlib.Path(tmp) + + def compile_cs(label, code): + marker = folder / (label + '.cdx') + marker.write_bytes(compute(words(*code, 0x7e0a0300, 0xbf810000), table=True)) + run = subprocess.run([compiler, sdk, folder / 'cache', 'gfx1013-container-cs', marker, + marker.with_suffix('.cso')], capture_output=True, text=True) + return marker.with_suffix('.cso'), run + + cso, run = compile_cs('gather', comparison_program(op=79)) + assert run.returncode == 0, run.stderr + dump = subprocess.run([sdk / 'dxc.exe', '-dumpbin', cso], capture_output=True, text=True, check=True).stdout + calls = [line for line in dump.splitlines() if '@dx.op.textureGatherCmp.f32(i32 74' in line] + assert len(calls) == 1, dump + # The module keeps VGPRs in allocas %r256 (v0) and up. Each float argument must be a bitcast of a load of the + # matching register: u = v1, v = v2, two undef components, then zero offsets, channel 0 and the reference v0. + casts = dict(re.findall(r'(%[\w.]+) = bitcast i32 (%[\w.]+) to float', dump)) + loads = dict(re.findall(r'(%[\w.]+) = load i32, i32\* %r(\d+),', dump)) + args = re.search(r'textureGatherCmp\.f32\(i32 74, ([^)]*)\)', calls[0]).group(1).split(', ') + floats = [a.split(' ', 1)[1] for a in args if a.startswith('float ')] + sources = ['v%d' % (int(loads[casts[f]]) - 256) if f in casts else f for f in floats] + assert sources == ['v1', 'v2', 'undef', 'undef', 'v0'], (sources, calls[0]) + assert args[-4:-1] == ['i32 0', 'i32 0', 'i32 0'], args + assert 'textureGather.f32' not in dump and 'sampleCmp' not in dump, dump + _, run = compile_cs('sample_c_lz', comparison_program(op=47)) + assert run.returncode == 0, run.stderr + print('module: one textureGatherCmp with channel 0') + + base = comparison_program(op=79) + image = base[-2] + cases = [('dmask 0x2', image & ~0xf00 | 0x200, base[-1], REFUSED), + ('cube', image & ~0x38 | 3 << 3, base[-1], REFUSED), + ('3D', image & ~0x38 | 2 << 3, base[-1], REFUSED), + ('d16', image, base[-1] | 0x80000000, 'unsupported image dimension or D16')] # refused at decode + cases += [(name, image & ~(0x7f << 18) | op << 18, base[-1], REFUSED) + for name, op in (('image_gather4_c', 72), ('image_gather4_c_l', 76), ('image_gather4_c_b', 77))] + for label, word, second, message in cases: + _, run = compile_cs(label.replace(' ', '_'), [*base[:-2], word, second]) + assert run.returncode and message in run.stderr, (label, run.stdout, run.stderr) + _, run = compile_cs('array', [*base[:-2], image & ~0x38 | 5 << 3, base[-1]]) + assert run.returncode == 0, run.stderr + print('refused: dmask 0x2, cube, 3D, d16, image_gather4_c, _c_l and _c_b; a 2D array compiles') + + # The program of native_graphics_comparison_pso_warp, with image_sample_c_lz (47) replaced by the gather. + code = [*comparison_program(op=79), 0xf09c0108, 0x00220500, 0x06000b04] + vs, ps, root = (folder / name for name in ('vertex', 'pixel', 'root.bin')) + vs_code = [0xbe810380, 0xf40c0200, 0xfa000040, 0x7e020280, 0x7e040280, + 0xf0200108, 0x80020201, 0x7e020b00, 0xf80008cf, 0x01010101, 0xbf810000] + vs.write_bytes(vertex(program=vs_code, table=True)) + code += [0xf40c0200, 0xfa000020, 0xf0200108, 0x80020400] + ps.write_bytes(patched_pixel(len(code), code, True)) + source = folder / 'root.hlsl' + source.write_text('#define RS "DescriptorTable(SRV(t0), UAV(u0, numDescriptors=2))"\n') + subprocess.run([sdk / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'RS', source, '-Fo', root], check=True) + run = subprocess.run([probe, '--graphics-sampler', sdk, vs, ps, root, folder / 'cache'], + capture_output=True, text=True) + print(run.stdout.strip()) + if run.returncode == 77: + sys.exit(77) + assert run.returncode == 0, (run.returncode, run.stdout, run.stderr) + + +if __name__ == '__main__': + main(*sys.argv[1:]) diff --git a/tests/native_global_load_check.py b/tests/native_global_load_check.py new file mode 100644 index 000000000..4335ac84e --- /dev/null +++ b/tests/native_global_load_check.py @@ -0,0 +1,138 @@ +"""global_load_dword through a root SRV address in the direct C++ compute path (#2962). + + native_global_load_check.py + +The saddr form reads ADDR = SADDR + zext(VADDR) + sext(OFFSET[11:0]) (RDNA 2 ISA, FLAT/GLOBAL addressing). The +direct frontend accepts SADDR only as the unadvanced root address of a root SRV, the binding its scalar root loads +already use, guards the 32-bit byte offset against wrapping, and drops the low two address bits like +buffer_load_dword in this path. All words below were assembled with LLVM 15 (clang -cc1as, gfx1013). + +The dispatch (two groups of 32 lanes) reads the root SRV that native_store_replay fills with 0x51aa0000 + dword +index. An s_load_dword at byte 252 sizes the view to 64 dwords. Each lane L stores five words: + A v1 = 4L -> word L + B v1, offset:16 -> word L + 4 + C v1, offset:-8 -> word L - 2, or 0 for L < 2 (the byte offset would be negative) + D v2 = 0xfffffff0 | 4(L & 3), +16 -> 0: zext(v2) + 16 is at least 2^32 (unguarded it would wrap in bounds) + E v3 = 4L + 1 -> word L (low address bits dropped) +References with the offset dropped or the wrap guard dropped must each differ from the readback. The lower guard +of C is not observable here: a wrapped negative offset lies near 2^32, outside any view below 4 GiB, and reads 0 +either way. Refusals are checked by message, and the module's loads and guards are counted before the +GPU run, which needs shader model 6.6 with wave32 (native_store_replay returns 77 otherwise). +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request + + +def words(hexes): + out = [] + for h in hexes.split(): + out += [int.from_bytes(bytes.fromhex(h[i:i + 8]), 'little') for i in range(0, len(h), 8)] + return out + + +ROOT = 'SRV(t0),DescriptorTable(UAV(u0,numDescriptors=8))' +SA = struct.pack('<7I', 0, 0, 0, 32 | 1 << 16, 1, 0, 0x80 | 7 << 1) +# s_mov_b32 s20, s6 / s_mov_b32 s21, 0 / s_load_dwordx4 s[40:43], s[20:21], 0x20 / s_load_dword s30, s[4:5], 0xfc / +# s_lshl_b32 s12, s7, 10 / v_lshlrev_b32 v8, 5, v0 / v_add_nc_u32 v8, s12, v8 / v_lshlrev_b32 v1, 2, v0 / +# v_and_b32 v2, 3, v0 / v_lshlrev_b32 v2, 2, v2 / v_or_b32 v2, -16, v2 / v_add_nc_u32 v3, 1, v1 +PROLOGUE = words('060394be 800395be 0a0a08f4200000fa 820700f4fc0000fa 078a0c8f 85001034 0c10104a 82000234 ' + '83000436 82040434 d0040438 8102064a') +LOADS = { + 'A': '008030dc01000414', # global_load_dword v20, v1, s[4:5] + 'B': '108030dc01000415', # global_load_dword v21, v1, s[4:5] offset:16 + 'C': 'f88f30dc01000416', # global_load_dword v22, v1, s[4:5] offset:-8 + 'D': '108030dc02000417', # global_load_dword v23, v2, s[4:5] offset:16 + 'E': '008030dc03000418', # global_load_dword v24, v3, s[4:5] +} +# s_waitcnt vmcnt(0) lgkmcnt(0), five buffer_store_dword v20..v24, v8, s[40:43], 0 offen offset:0..16, s_endpgm +EPILOGUE = words('70008cbf 001070e008140a80 041070e008150a80 081070e008160a80 0c1070e008170a80 ' + '101070e008180a80 000081bf') +REFUSALS = [ + ('008030dc01007d14', 'global_load_dword with a scalar address pair'), # v[1:2], off + ('008030dc01001414', 'global load base is not a root buffer address'), # s[20:21], a table pointer + ('028030dc01000414', 'global load at an unaligned immediate offset'), # offset:2 + ('008034dc01000414', 'global_load_dword with a scalar address pair'), # global_load_dwordx2 + ('008070dc01140400', 'global_load_dword with a scalar address pair'), # global_store_dword + ('800385be 008030dc01000414', 'global load base is an advanced or mismatched root address'), # s_mov_b32 s5, 0 + ('04900480 008030dc01000414', 'unbound numeric SGPR s4'), # s_add_u32 s4, s4, 16 on the root address + ('00a030dc01000414', 'global_load_dword with a scalar address pair'), # the lds bit + ('000030dc01007d14', 'global_load_dword with a scalar address pair'), # flat_load_dword (segment 0) + ('004030dc01007d14', 'global_load_dword with a scalar address pair'), # scratch_load_dword (segment 1) + ('0080c8dc01140400', 'global_load_dword with a scalar address pair'), # global_atomic_add +] +POLICY = '009033dc01000414' # global_load_dword v20, v1, s[4:5] glc slc dlc: accepted + + +def reference(drop_offset=False, drop_wrap_guard=False): + expected = [0x69696969] * 2064 + for group in range(2): + for lane in range(32): + base = 8 + (group * 32 + lane) * 8 + + def word(byte): + return 0x51aa0000 + byte // 4 if 0 <= byte < 256 else 0 + b = word(4 * lane + (0 if drop_offset else 16)) + c_byte = 4 * lane - 8 + c = word(c_byte) if c_byte >= 0 else 0 + d_byte = 0xfffffff0 | 4 * (lane & 3) + d = word((d_byte + 16) & 0xffffffff) if drop_wrap_guard else 0 + expected[base:base + 5] = [word(4 * lane), b, c, d, word(4 * lane)] + return expected + + +def main(compiler, replay, sdk): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + source, root = work / 'root.hlsl', work / 'root.bin' + source.write_text('#define SIG "%s"' % ROOT) + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, source], check=True) + + def compile_words(code): + marker = write_request(work, code, root.read_bytes(), SA) + return marker, subprocess.run([compiler, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, + marker.with_suffix('.cso')], capture_output=True, text=True) + + for code, message in REFUSALS: + _, run = compile_words(PROLOGUE + words(code) + EPILOGUE) + assert run.returncode and message in run.stderr, (code, message, run.stdout, run.stderr) + _, run = compile_words(PROLOGUE + words(POLICY) + EPILOGUE) + assert run.returncode == 0, run.stderr + print('refused: off, a table pointer, offset:2, dwordx2, store, a replaced high half, an advanced pointer, ' + 'lds, flat and scratch segments, an atomic; glc slc dlc accepted') + + code = PROLOGUE + words(' '.join(LOADS.values())) + EPILOGUE + marker, run = compile_words(code) + assert run.returncode == 0, run.stderr + assert 't0 root=0 bytes=0 min_size=256' in run.stdout, run.stdout + # The module, before the GPU run: five global loads plus the scalar root load, the two upper-bound guards + # (B and D) and the lower-bound guard (C), each a select on a raw buffer load. + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', marker.with_suffix('.cso')], + capture_output=True, text=True, check=True).stdout + counts = [dump.count(t) for t in ('rawBufferLoad.i32(i32 139', 'icmp ule i32', 'icmp uge i32')] + assert counts == [6, 2, 1], counts + print('module: 6 raw buffer loads, 2 upper-bound and 1 lower-bound guards') + dest = work / 'readback.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', dest, '--direct'], + capture_output=True, text=True) + if result.returncode == 77: + print(result.stdout + result.stderr) + sys.exit(77) + assert result.returncode == 0, (result.stdout, result.stderr) + actual = list(struct.unpack('<2064I', dest.read_bytes())) + expected = reference() + diff = [(i, hex(a), hex(b)) for i, (a, b) in enumerate(zip(actual, expected)) if a != b] + assert not diff, diff[:10] + for label, mutant in (('offset dropped', reference(drop_offset=True)), + ('wrap guard dropped', reference(drop_wrap_guard=True))): + assert mutant != expected and actual != mutant, label + print('global_load_dword: 320 words of two groups matched (offsets 0, 16, -8, the 2^32 guard and an ' + 'unaligned address); the offset-dropped and wrap-guard-dropped references differ') + + +if __name__ == '__main__': + main(*sys.argv[1:]) diff --git a/tests/native_global_srv_heap_replay.cpp b/tests/native_global_srv_heap_replay.cpp new file mode 100644 index 000000000..c0d823b1a --- /dev/null +++ b/tests/native_global_srv_heap_replay.cpp @@ -0,0 +1,451 @@ +// Native compute fixture whose shader picks a global (descriptor heap) SRV slot from a GPU input. +// +// root OUT.root writes the root signature the request container carries. +// record SDK CACHE REQ.cdx ADAPTER SELECTOR EXPECT [--no-guard] +// Native recording path: reads the GPU selector back before the dispatch, captures {select, view types} +// into REQ.views, refuses a slot of another view type before the shader runs, otherwise records the +// dispatch with x2w_startup::NativeRecording and NativeDispatchStates and compares the fenced output. +// replay SDK CACHE REQ.cdx COMPILED.cso VIEWS ADAPTER EXPECT REFERENCE_SLOT +// Offline request replay: decodes VIEWS, refuses before the dispatch or runs the compiled.cso shader on a +// heap rebuilt from the captured slot types and compares with the reference slot data. +// EXPECT is "ok" or "refused". Exit 0: outcome as expected. 1: output mismatch for an expected-ok case. 3: the +// outcome differs from the expectation. 4: setup error. 77: capability skip. +#include "desktop_gpu.h" +#include "native_compute_pipeline.h" +#include "startup_stubs/native_dispatch_states.h" +#include "startup_stubs/native_global_srv.h" +#include "startup_stubs/native_recording.h" +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; +using x2w_startup::GlobalSrvType; +using x2w_startup::GlobalSrvView; +namespace fs = std::filesystem; + +namespace { +constexpr unsigned slot_count = 4, slot_words = 64, selector_page_slot = 4, output_page_slot = 5; +constexpr unsigned output_words = 72; +constexpr std::uint32_t sentinel = 0x69696969u; + +// Backing data of a raw buffer slot, deterministic from the slot index. +std::uint32_t slot_word(unsigned slot, unsigned index) { return 0xA0000000u + slot * 0x10000000u + index; } + +struct Rig { + ComPtr device; + ComPtr queue; + ComPtr allocator; + ComPtr list; + ComPtr fence; + HANDLE event = nullptr; + UINT64 fence_value = 0; + x2w_startup::NativeRecording recording; + x2w_startup::NativeDescriptorTable page; + ComPtr selector, output; + std::vector> slots{slot_count}; // keeps the backing resources of the heap alive + std::vector> upload_keep; + + ~Rig() { + if (event) CloseHandle(event); + } + + // Returns 77 when the adapter cannot run the fixture; 0 when the rig is ready. + int open(const std::wstring &adapter) { + ComPtr factory; + ComPtr chosen; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 77; + if (adapter == L"warp") { + if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&chosen)))) return 77; + } else { + for (UINT i = 0; i < 8; ++i) { + ComPtr candidate; + if (factory->EnumAdapters1(i, &candidate) == DXGI_ERROR_NOT_FOUND) break; + DXGI_ADAPTER_DESC1 desc{}; + candidate->GetDesc1(&desc); + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) { + chosen = candidate; + std::printf("adapter=%ls\n", desc.Description); + break; + } + } + if (!chosen) { std::puts("no hardware adapter"); return 77; } + } + if (FAILED(D3D12CreateDevice(chosen.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) { + std::puts("no device"); + return 77; + } + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_6}; + D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; + if (FAILED(check_feature(device.Get(), D3D12_FEATURE_SHADER_MODEL, &model, sizeof model)) || + model.HighestShaderModel < D3D_SHADER_MODEL_6_6 || + FAILED(check_feature(device.Get(), D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof options)) || + options.ResourceBindingTier < D3D12_RESOURCE_BINDING_TIER_3) { + std::printf("adapter lacks shader model 6.6 or resource binding tier 3 (tier %d)\n", + int(options.ResourceBindingTier)); + return 77; + } + // The native module declares WaveSize=32 (the guest wave), so an adapter without 32-lane waves cannot run it. + D3D12_FEATURE_DATA_D3D12_OPTIONS1 waves{}; + if (FAILED(check_feature(device.Get(), D3D12_FEATURE_D3D12_OPTIONS1, &waves, sizeof waves)) || !waves.WaveOps || + waves.WaveLaneCountMin > 32 || waves.WaveLaneCountMax < 32) { + std::printf("adapter has no 32-lane waves (%u..%u)\n", waves.WaveLaneCountMin, waves.WaveLaneCountMax); + return 77; + } + D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + check(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)), "queue"); + check(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), "allocator"); + check(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(&list)), + "list"); + check(list->Close(), "close"); + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "fence"); + event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!event) throw std::runtime_error("event"); + // The descriptor page of one native recording: slots 0..3 are selectable, 4 is t0, 5 is u0. + page = recording.allocate(device.Get(), 6); + return 0; + } + + D3D12_CPU_DESCRIPTOR_HANDLE cpu(unsigned index) const { + auto handle = page.cpu; + handle.ptr += SIZE_T(index) * page.increment; + return handle; + } + D3D12_GPU_DESCRIPTOR_HANDLE first_gpu() const { + auto handle = page.gpu; + handle.ptr += UINT64(selector_page_slot) * page.increment; + return handle; + } + + void wait() { + check(queue->Signal(fence.Get(), ++fence_value), "signal"); + check(fence->SetEventOnCompletion(fence_value, event), "fence event"); + if (WaitForSingleObject(event, 30000) != WAIT_OBJECT_0) throw std::runtime_error("fence wait timed out"); + } + // Records `body` on the one list and waits for its fence. + template void run(Body body) { + check(allocator->Reset(), "allocator reset"); + check(list->Reset(allocator.Get(), nullptr), "list reset"); + body(list.Get()); + check(list->Close(), "list close"); + ID3D12CommandList *lists[]{list.Get()}; + queue->ExecuteCommandLists(1, lists); + wait(); + } + // A command list with no commands: what a refused request submits instead of the dispatch. + void run_empty() { + run([](ID3D12GraphicsCommandList *) {}); + } + void fill(ID3D12Resource *destination, const std::vector &words) { + const UINT64 bytes = words.size() * 4; + auto upload = make_buffer(device.Get(), bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + void *mapped = nullptr; + D3D12_RANGE none{}; + check(upload->Map(0, &none, &mapped), "upload map"); + std::memcpy(mapped, words.data(), bytes); + upload->Unmap(0, nullptr); + run([&](ID3D12GraphicsCommandList *l) { l->CopyBufferRegion(destination, 0, upload.Get(), 0, bytes); }); + } + std::vector read(ID3D12Resource *source, unsigned words) { + auto readback = make_buffer(device.Get(), UINT64(words) * 4, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + run([&](ID3D12GraphicsCommandList *l) { l->CopyBufferRegion(readback.Get(), 0, source, 0, UINT64(words) * 4); }); + std::vector out(words); + void *mapped = nullptr; + D3D12_RANGE range{0, UINT64(words) * 4}; + check(readback->Map(0, &range, &mapped), "readback map"); + std::memcpy(out.data(), mapped, out.size() * 4); + D3D12_RANGE written{}; + readback->Unmap(0, &written); + return out; + } + + // t0 (the selector, a raw buffer) and u0 (72 words of output) in their page slots. + void create_io() { + selector = make_buffer(device.Get(), 4, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON); + output = make_buffer(device.Get(), output_words * 4, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Buffer.NumElements = 1; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(selector.Get(), &srv, cpu(selector_page_slot)); + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{}; + uav.Format = DXGI_FORMAT_R32_TYPELESS; + uav.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + uav.Buffer.NumElements = output_words; + uav.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device->CreateUnorderedAccessView(output.Get(), nullptr, &uav, cpu(output_page_slot)); + } + void fill_sentinel() { fill(output.Get(), std::vector(output_words, sentinel)); } + bool sentinels_intact() { + for (auto word : read(output.Get(), output_words)) + if (word != sentinel) return false; + return true; + } + + // Creates the backing resource and the SRV of one selectable slot. Returns the captured view: the class is + // classified from the exact description passed to CreateShaderResourceView, the size from the resource. + GlobalSrvView add_slot(unsigned slot, GlobalSrvType type, std::uint64_t bytes) { + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (type == GlobalSrvType::texture) { + D3D12_RESOURCE_DESC texture{}; + texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + texture.Width = texture.Height = 8; + texture.DepthOrArraySize = texture.MipLevels = 1; + texture.Format = DXGI_FORMAT_R32_UINT; + texture.SampleDesc.Count = 1; + slots[slot] = resource(device.Get(), texture, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON); + desc.Format = DXGI_FORMAT_R32_UINT; + desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + desc.Texture2D.MipLevels = 1; + } else if (type == GlobalSrvType::raw_buffer || type == GlobalSrvType::typed_buffer) { + if (!bytes || bytes % 4 || bytes > (1u << 20)) + throw std::runtime_error("slot " + std::to_string(slot) + " has an unusable buffer size"); + slots[slot] = make_buffer(device.Get(), bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON); + std::vector data(bytes / 4); + for (unsigned i = 0; i < data.size(); ++i) data[i] = slot_word(slot, i); + fill(slots[slot].Get(), data); + desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + desc.Buffer.NumElements = static_cast(bytes / 4); + if (type == GlobalSrvType::raw_buffer) { + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + } else { + desc.Format = DXGI_FORMAT_R32_UINT; + } + } else { + throw std::runtime_error(std::string("view type ") + x2w_startup::global_srv_type_name(type) + + " cannot be rebuilt by this fixture"); + } + device->CreateShaderResourceView(slots[slot].Get(), &desc, cpu(slot)); + GlobalSrvView view; + if (!x2w_startup::classify_global_srv_view(slot, &desc, sizeof desc, view)) + throw std::runtime_error("slot view could not be classified"); + if (view.type != type) throw std::runtime_error("slot view classified as another type"); + view.bytes = type == GlobalSrvType::texture ? 0 : slots[slot]->GetDesc().Width; + return view; + } + + unsigned read_selector(unsigned value) { + fill(selector.Get(), {value}); + return read(selector.Get(), 1)[0]; + } + + // Barriers from the views of the dispatch (NativeDispatchStates), the dispatch, the barriers back, the fence. + // `state` is the pipeline-state object to run (null: the one bind() set). + void dispatch(const x2w::NativeComputePipeline &pipeline, ID3D12PipelineState *state, ID3D12Resource *selected) { + struct View { + ComPtr resource; + bool write = false; + x2w_startup::NativeTextureWindow texture{}; + struct { bool upload = false; } buffer; + }; + std::vector views; + views.push_back({selector, false, {}, {}}); + views.push_back({output, true, {}, {}}); + views.push_back({selected, false, {}, {}}); + x2w_startup::NativeDispatchStates states(views); + std::vector before, after; + states.whole_states([&](ID3D12Resource *resource, D3D12_RESOURCE_STATES target) { + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON, target}; + before.push_back(b); + std::swap(b.Transition.StateBefore, b.Transition.StateAfter); + after.push_back(b); + }); + run([&](ID3D12GraphicsCommandList *l) { + l->ResourceBarrier(UINT(before.size()), before.data()); + pipeline.bind(l, page.heap, first_gpu(), page.increment); + if (state) l->SetPipelineState(state); + l->Dispatch(1, 1, 1); + l->ResourceBarrier(UINT(after.size()), after.data()); + }); + } +}; + +std::vector reference_output(unsigned slot) { + std::vector words(output_words, sentinel); + for (unsigned i = 0; i < slot_words; ++i) words[i] = slot_word(slot, i); + return words; +} + +// 0: the 72 words equal the reference; 1 prints the first mismatch. +int compare_output(Rig &rig, unsigned reference_slot) { + const auto expected = reference_output(reference_slot); + const auto actual = rig.read(rig.output.Get(), output_words); + for (unsigned i = 0; i < output_words; ++i) + if (actual[i] != expected[i]) { + std::printf("mismatch word %u: got 0x%08x expected 0x%08x (reference slot %u)\n", i, actual[i], expected[i], + reference_slot); + return 1; + } + std::printf("output matches slot %u data (%u words) and the %u sentinel words are intact\n", reference_slot, + slot_words, output_words - slot_words); + return 0; +} + +// The refused path of both modes: no dispatch is recorded, and the output must be untouched. +int refused_path(Rig &rig, bool expect_ok) { + rig.run_empty(); + const bool intact = rig.sentinels_intact(); + std::printf("no dispatch submitted; u0 sentinels %s\n", intact ? "intact" : "CHANGED"); + return (!expect_ok && intact) ? 0 : 3; +} + +int write_root(const fs::path &destination) { + D3D12_DESCRIPTOR_RANGE ranges[2]{}; + ranges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + ranges[0].NumDescriptors = 1; + ranges[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; + ranges[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV; + ranges[1].NumDescriptors = 1; + ranges[1].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; + D3D12_ROOT_PARAMETER parameter{}; + parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameter.DescriptorTable = {2, ranges}; + D3D12_ROOT_SIGNATURE_DESC desc{1, ¶meter, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr blob, error; + if (FAILED(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, &error))) + throw std::runtime_error("root signature serialization failed"); + std::ofstream file(destination, std::ios::binary); + file.write(static_cast(blob->GetBufferPointer()), static_cast(blob->GetBufferSize())); + file.close(); + if (!file) throw std::runtime_error("could not write the root signature"); + return 0; +} + +// The pipeline must read t0 and u0 through the tables and the selected slot through the heap. +void check_pipeline_shape(const x2w::NativeComputePipeline &pipeline) { + if (!pipeline.heap_indexed || pipeline.srv_count != 1 || pipeline.uav_count != 1 || pipeline.constant_words) + throw std::runtime_error("native pipeline has an unexpected binding layout"); +} + +int record(int argc, wchar_t **argv) { + if (argc != 8 && argc != 9) return 2; + const std::wstring expect = argv[7]; + const bool guard = !(argc == 9 && std::wstring_view(argv[8]) == L"--no-guard"); + if ((argc == 9 && guard) || (expect != L"ok" && expect != L"refused")) return 2; + const unsigned selector = static_cast(std::stoul(argv[6])); + const fs::path cdx = argv[4]; + Rig rig; + if (int skip = rig.open(argv[5])) return skip; + try { + x2w::ShaderDxilCompiler compiler(argv[2]); + auto pipeline = x2w::create_native_compute_pipeline(rig.device.Get(), compiler, cdx, 0, argv[3], true, + x2w::HeapViewContract::raw_buffer); + check_pipeline_shape(pipeline); + rig.create_io(); + x2w_startup::GlobalSrvRequest request; + request.needed = GlobalSrvType::raw_buffer; + request.views.push_back(rig.add_slot(0, GlobalSrvType::raw_buffer, slot_words * 4)); + request.views.push_back(rig.add_slot(1, GlobalSrvType::raw_buffer, slot_words * 4)); + request.views.push_back(rig.add_slot(2, GlobalSrvType::texture, 0)); + request.views.push_back(rig.add_slot(3, GlobalSrvType::typed_buffer, slot_words * 4)); + rig.fill_sentinel(); + // The selector is GPU data: it is read back (one CPU/GPU sync) before the dispatch is recorded. + request.selected = rig.read_selector(selector); + request.has_selected = true; + auto views_path = cdx; + views_path.replace_extension(L".views"); + std::ofstream(views_path, std::ios::binary) << x2w_startup::encode_global_srv_request(request); + std::printf("captured select=%u need=raw_buffer views=%s\n", request.selected, views_path.string().c_str()); + const auto diagnostic = x2w_startup::refuse_global_srv_selection(request.views, request.selected, request.needed); + if (!diagnostic.empty() && guard) { + std::printf("refused select=%u: %s\n", request.selected, diagnostic.c_str()); + return refused_path(rig, expect == L"ok"); + } + if (request.selected >= slot_count || request.views[request.selected].type != GlobalSrvType::raw_buffer) + throw std::runtime_error("--no-guard only dispatches a raw buffer slot"); + rig.dispatch(pipeline, nullptr, rig.slots[request.selected].Get()); + if (expect == L"refused") { + // Discrimination control: without the guard the shader ran, so the output must have changed. + const bool intact = rig.sentinels_intact(); + std::printf("dispatch ran (%s); %s\n", guard ? "no refusal" : "guard disabled", + intact ? "sentinels intact" : "sentinels changed"); + return 3; + } + return compare_output(rig, request.selected); + } catch (const std::exception &error) { + std::printf("setup error: %s\n", error.what()); + return 4; + } +} + +int replay(int argc, wchar_t **argv) { + if (argc != 10) return 2; + const std::wstring expect = argv[8]; + if (expect != L"ok" && expect != L"refused") return 2; + const fs::path cdx = argv[4], cso = argv[5], views_path = argv[6]; + const unsigned reference_slot = static_cast(std::stoul(argv[9])); + Rig rig; + if (int skip = rig.open(argv[7])) return skip; + try { + rig.create_io(); + rig.fill_sentinel(); + std::string text, error; + x2w_startup::GlobalSrvRequest request; + std::ifstream file(views_path, std::ios::binary); + if (!file) { + error = "global SRV view metadata file missing: " + views_path.string(); + } else { + text.assign(std::istreambuf_iterator(file), {}); + x2w_startup::decode_global_srv_request(text, request, error); + } + if (error.empty()) + error = x2w_startup::refuse_global_srv_selection(request.views, request.selected, request.needed); + if (error.empty() && request.needed != GlobalSrvType::raw_buffer) + error = std::string("GPU-selected heap slot view type ") + x2w_startup::global_srv_type_name(request.needed) + + " is not raw_buffer; only raw buffer heap reads are translated"; + if (!error.empty()) { + std::printf("refused: %s\n", error.c_str()); + return refused_path(rig, expect == L"ok"); + } + x2w::ShaderDxilCompiler compiler(argv[2]); + auto pipeline = x2w::create_native_compute_pipeline(rig.device.Get(), compiler, cdx, 0, argv[3], true, + x2w::HeapViewContract::raw_buffer); + check_pipeline_shape(pipeline); + std::ifstream shader(cso, std::ios::binary); + if (!shader) throw std::runtime_error("missing compiled shader " + cso.string()); + const std::string dxil((std::istreambuf_iterator(shader)), {}); + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = pipeline.root.Get(); + pso.CS = {dxil.data(), dxil.size()}; + ComPtr compiled; + check(rig.device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&compiled)), "compiled shader pipeline"); + for (const auto &view : request.views) { + if (view.slot >= slot_count) throw std::runtime_error("captured slot outside the fixture heap page"); + rig.add_slot(view.slot, view.type, view.bytes); + } + rig.read_selector(request.selected); + rig.dispatch(pipeline, compiled.Get(), rig.slots[request.selected].Get()); + const int result = compare_output(rig, reference_slot); + if (expect == L"refused") return 3; // ran when a refusal was expected + return result; + } catch (const std::exception &error) { + std::printf("setup error: %s\n", error.what()); + return 4; + } +} +} // namespace + +int wmain(int argc, wchar_t **argv) { + try { + if (argc >= 2 && std::wstring_view(argv[1]) == L"root" && argc == 3) return write_root(argv[2]); + if (argc >= 2 && std::wstring_view(argv[1]) == L"record") return record(argc, argv); + if (argc >= 2 && std::wstring_view(argv[1]) == L"replay") return replay(argc, argv); + } catch (const std::exception &error) { + std::printf("setup error: %s\n", error.what()); + return 4; + } + std::fputs("usage: native_global_srv_heap_replay root OUT.root | record SDK CACHE REQ.cdx ADAPTER SELECTOR ok|refused " + "[--no-guard] | replay SDK CACHE REQ.cdx COMPILED.cso VIEWS ADAPTER ok|refused REFERENCE_SLOT\n", stderr); + return 2; +} diff --git a/tests/native_global_srv_heap_replay_check.py b/tests/native_global_srv_heap_replay_check.py new file mode 100644 index 000000000..d679b3cfb --- /dev/null +++ b/tests/native_global_srv_heap_replay_check.py @@ -0,0 +1,344 @@ +"""GPU-selected global SRV heap slot: native recording and offline request replay (issue #2908). + +usage: native_global_srv_heap_replay_check.py FIXTURE COMPILE_DXIL SDK ADAPTER + +A source-built compute container picks a descriptor heap slot from a GPU buffer (t0), reads 64 words through +ResourceDescriptorHeap[slot] and stores them to u0. Slots 0 and 1 are raw buffers with different data, slot 2 is a +texture, slot 3 a typed buffer. The fixture's `record` mode captures the GPU selector and the slot view types into a +req_.views file and refuses the incompatible slots before the dispatch; `compile_dxil` and the fixture's `replay` +mode consume the same file offline. Exit 77 when the fixture reports a capability skip. +""" +import pathlib +import shutil +import struct +import subprocess +import sys +import tempfile +import zlib + +fixture, compile_dxil, sdk, adapter = sys.argv[1:5] +RAW = "global SRV slot {n} has view type {t}, the shader needs raw_buffer" +HEAP_REFUSAL = "direct resource-heap load requires the selected GPU slot and its view type" + + +def words(*values): + return struct.pack(f"<{len(values)}I", *values) + + +def pack(body, extra=()): + raw = b"FSSM" + struct.pack(" exit {result.returncode}") + if result.returncode == 77 and str(command[0]) == fixture: + print("fixture capability skip (77)") + sys.exit(77) + return result.returncode, out, err + + +def require(condition, message): + if not condition: + print("FAIL: " + message) + sys.exit(1) + print("ok: " + message) + + +with tempfile.TemporaryDirectory(prefix="x2w_global_srv_") as scratch: + base = pathlib.Path(scratch) + cache = base / "cache" + cache.mkdir() + + # Fixture root signature, container, key (B6). + root_path = base / "fixture.root" + code, out, err = run([fixture, "root", root_path]) + require(code == 0 and root_path.stat().st_size > 0, "fixture wrote the root signature") + root = root_path.read_bytes() + cdx = compute_two_inputs(PROGRAM) + stem = "req_%016x" % key_of(root, cdx) + + def request_dir(name): + directory = base / name + directory.mkdir() + (directory / (stem + ".cdx")).write_bytes(cdx) + (directory / (stem + ".root")).write_bytes(root) + return directory + + def compile_directory(directory): + out_dir = base / (directory.name + "_out") + result = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + # compile_dxil --requests publishes .cs.cso (the req_ prefix stripped) for a compute request. + return result, out_dir / (stem[len("req_"):] + ".cs.cso") + + selections = [request_dir(f"sel{n}") for n in range(4)] + nometa = request_dir("nometa") + + # 1. Missing metadata, offline: a heap shader without .views is refused before any output exists. + (code, out, err), cso = compile_directory(nometa) + require(code == 1 and HEAP_REFUSAL in err, "compile_dxil without .views refuses the heap read with the slot/type text") + require(not cso.exists(), "no .cso is published for the request without .views") + + # 2. Native recording path: accepted and refused selections. + for n in (0, 1): + views = selections[n] / (stem + ".views") + code, out, err = run([fixture, "record", sdk, cache, selections[n] / (stem + ".cdx"), adapter, n, "ok"]) + require(code == 0, f"record select {n}: fenced output equals the slot {n} data and u0 sentinels are intact") + require("output matches slot %d data" % n in out, f"record select {n} compared 64 words with the CPU reference") + text = views.read_text() + require(text.startswith("x2w-global-srv-views 2\nselect %d\nneed raw_buffer\n" % n), + f"record select {n} captured the GPU selector and the view type") + for line in ("slot 0 raw_buffer 1 256", "slot 1 raw_buffer 1 256", "slot 2 texture 0 0", "slot 3 typed_buffer 4 256"): + require(line + "\n" in text, f"captured view line '{line}'") + for n, type_name in ((2, "texture"), (3, "typed_buffer")): + code, out, err = run([fixture, "record", sdk, cache, selections[n] / (stem + ".cdx"), adapter, n, "refused"]) + require(code == 0, f"record select {n}: refused with unchanged u0 sentinels") + require(RAW.format(n=n, t=type_name) in out, f"record select {n}: slot/type diagnostic before the dispatch") + require("no dispatch submitted" in out and "sentinels intact" in out, f"record select {n}: nothing was dispatched") + + # 3. Discrimination control: without the guard a valid slot runs and changes u0, which the check must see. + code, out, err = run([fixture, "record", sdk, cache, selections[0] / (stem + ".cdx"), adapter, 0, "refused", "--no-guard"]) + require(code == 3 and "sentinels changed" in out, "record --no-guard expecting a refusal sees the changed sentinels (exit 3)") + + # 4. Offline replay compilation of the captured requests. + outputs = {} + for n in range(4): + (code, out, err), cso = compile_directory(selections[n]) + outputs[n] = cso + if n < 2: + require(code == 0 and "requests=1 compiled=1 refused=0" in out, f"compile_dxil select {n}: compiled") + require("global_srv select=%d need=raw_buffer" % n in out, f"compile_dxil select {n}: reports the captured selection") + require(cso.exists(), f"compile_dxil select {n}: published a .cso") + else: + type_name = "texture" if n == 2 else "typed_buffer" + require(code == 1 and "refused=1" in out, f"compile_dxil select {n}: refused") + require(RAW.format(n=n, t=type_name) in err, f"compile_dxil select {n}: slot/type diagnostic") + require(not cso.exists(), f"compile_dxil select {n}: no .cso") + + # 5. Fixture replay of the compiled shader and of the refusals. + def replay(directory, cso, views, expect, reference): + return run([fixture, "replay", sdk, cache, directory / (stem + ".cdx"), cso, views, adapter, expect, reference]) + + for n in (0, 1): + code, out, err = replay(selections[n], outputs[n], selections[n] / (stem + ".views"), "ok", n) + require(code == 0 and "output matches slot %d data" % n in out, f"replay select {n}: compiled shader output equals slot {n} data") + for n, type_name in ((2, "texture"), (3, "typed_buffer")): + code, out, err = replay(selections[0], outputs[0], selections[n] / (stem + ".views"), "refused", 0) + require(code == 0 and RAW.format(n=n, t=type_name) in out and "sentinels intact" in out, + f"replay select {n}: refused with the slot/type diagnostic, u0 sentinels intact") + + # 6. Mutation control: the slot 1 data is not the slot 0 reference. + code, out, err = replay(selections[0], outputs[0], selections[0] / (stem + ".views"), "ok", 1) + require(code == 1 and "mismatch word 0" in out, "replay select 0 compared with slot 1 data reports a mismatch (exit 1)") + + # 7. Negative controls on both paths: metadata that cannot reconstruct the binding. + good = (selections[0] / (stem + ".views")).read_text() + lines = good.splitlines() + + def variant(name, text, expected): + directory = request_dir("neg_" + name) + views = directory / (stem + ".views") + views.write_text(text, newline="\n") + (code, out, err), cso = compile_directory(directory) + require(code == 1 and expected in err, f"compile_dxil '{name}': refused with '{expected}'") + require(not cso.exists() and not any(cso.parent.glob("*.cso")), f"compile_dxil '{name}': no .cso") + code, out, err = replay(selections[0], outputs[0], views, "refused", 0) + require(code == 0 and expected in out and "sentinels intact" in out, + f"replay '{name}': refused with the same diagnostic, u0 sentinels intact") + + def without(prefix): + kept = [line for line in lines if not line.startswith(prefix)] + require(len(kept) == len(lines) - 1, f"control input drops exactly one '{prefix}' line") + return "\n".join(kept) + "\n" + + variant("mismatched_type", good.replace("slot 0 raw_buffer 1 256", "slot 0 texture 0 0"), RAW.format(n=0, t="texture")) + require("slot 0 texture 0 0" in (base / "neg_mismatched_type" / (stem + ".views")).read_text(), "mismatch input rewrote slot 0") + variant("no_need", without("need "), "global SRV view metadata lacks the needed view type") + variant("no_select", without("select "), "global SRV view metadata lacks the selected slot") + variant("no_slot_line", without("slot 0 "), "global SRV slot 0 has no captured view type") + variant("select_7", good.replace("select 0", "select 7"), "global SRV slot 7 has no captured view type") + + # 8. Shader shapes whose heap read could address another slot than the captured selection, use the slot's stride + # as a number, or rewrite the heap descriptor in a way the raw slot view cannot stand for: refused by + # compile_dxil even with valid metadata, no .cso. + words_list = list(struct.unpack(f"<{len(PROGRAM) // 4}I", PROGRAM)) + lshl = words_list.index(0x8f118510) + heap_load = words_list.index(0xf4080501) + after_wait = heap_load + 3 # the s_waitcnt after the heap descriptor load + # The byte-address rewrite of the heap descriptor s[20:23] into s[24:27] (LLVM 15 encodings, as above). + rewrite = [ + 0x939cff15, 0x000e0010, # s_bfe_u32 s28, s21, 0xe0010 (stride) + 0x849c811c, # s_max_u32 s28, s28, 1 + 0x931a1c16, # s_mul_i32 s26, s22, s28 (byte count) + 0x8719ff15, 0xc000ffff, # s_and_b32 s25, s21, 0xc000ffff (stride cleared) + 0x871bff17, 0xcfffffff, # s_and_b32 s27, s23, 0xcfffffff + 0x881bff1b, 0x30000000, # s_or_b32 s27, s27, 0x30000000 (raw out-of-bounds mode) + 0xbe980314, # s_mov_b32 s24, s20 + ] + load = words_list.index(0xe0301000) # buffer_load_dword v2, v1, s[20:23], 0 offen + store = words_list.index(0xe0701000) # buffer_store_dword v2, v1, s[12:15], 0 offen + + def window(rewritten=rewrite, prefix=(), store_word=0x80030201): + """PROGRAM with the rewrite after the heap load and the load through s[24:27].""" + program = list(words_list) + program[load + 1] = 0x80060201 # buffer_load_dword v2, v1, s[24:27], 0 offen + program[store + 1] = store_word + return program[:after_wait] + list(prefix) + list(rewritten) + program[after_wait:] + + WINDOW = window() + second_load = window([0xbe980320 if w == 0xbe980314 else w for w in rewrite]) + second_load[after_wait - 1:after_wait - 1] = [0xf4080801, 0x22000000] # before the s_waitcnt + # The branch word sits at after_wait + 1; its target is next pc + 4 * simm16, here the s_lshl_b32 at word lshl. + loop_around_load = window(prefix=(0xbf071010, 0xbf850000 | ((lshl - (after_wait + 2)) & 0xFFFF))) + shapes = { + # s_mov_b32 s17, 64 instead of the GPU-derived s_lshl_b32 s17, s16, 5 + "constant_index": (words_list[:lshl] + [0xbe9103c0] + words_list[lshl + 1:], + "heap descriptor index is a constant; the captured selection must come from GPU data"), + # s_load_dwordx4 s[20:23], s[2:3], s17 offset:0x20 + "immediate_offset": (words_list[:heap_load] + [0xf4080501, 0x22000020] + words_list[heap_load + 2:], + "heap descriptor load with an immediate offset addresses another slot than the captured selection"), + # s_bfe_u32 s24, s21, 0xe0010 after the heap descriptor load (stride field of the selected slot), then + # v_mov_b32 v3, s24: the stride is used as a number + "stride_read": (words_list[:after_wait] + [0x9398ff15, 0x000e0010, 0x7e060218] + words_list[after_wait:], + "unbound numeric SGPR s24"), + # s_and_b32 s25, s21, 0xc000fffe: not the mask that clears the stride + "window_wrong_mask": (window([0xc000fffe if w == 0xc000ffff else w for w in rewrite]), "unbound numeric SGPR s21"), + # a second heap load s_load_dwordx4 s[32:35], s[2:3], s17 and word 0 from it (s_mov_b32 s24, s32) + "window_second_load": (second_load, "non-contiguous resource descriptor"), + # buffer_store_dword v2, v1, s[24:27], 0 offen: a store through the window + "window_store": (window(store_word=0x80060201), "a GPU-selected heap slot is read as a raw buffer SRV only"), + # s_cmp_lg_u32 s16, s16 and s_cbranch_scc1 back to the s_lshl_b32 before the heap load (never taken): the + # loop contains the heap load, which would run again for another selection + "window_loop": (loop_around_load, "heap byte window loaded inside a loop"), + } + for name, (program, expected) in shapes.items(): + directory = base / ("shape_" + name) + directory.mkdir() + shape_cdx = compute_two_inputs(words(*program)) + shape_stem = "req_%016x" % key_of(root, shape_cdx) + (directory / (shape_stem + ".cdx")).write_bytes(shape_cdx) + (directory / (shape_stem + ".root")).write_bytes(root) + (directory / (shape_stem + ".views")).write_text(good, newline="\n") + out_dir = base / (directory.name + "_out") + code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + require(code == 1 and expected in err, f"compile_dxil shape '{name}': refused with '{expected}'") + require(not any(out_dir.glob("*.cso")), f"compile_dxil shape '{name}': no .cso") + + # 9. The byte-address rewrite of the selected heap descriptor (stride, max 1, byte count, stride cleared, raw + # out-of-bounds mode) reads the selected raw slot: recorded, compiled offline and replayed like PROGRAM. A stride + # read that nothing uses compiles too. The descriptor words stay symbolic, so a stride > 1 is not exercised. + def window_request(name, program): + directory = base / name + directory.mkdir() + cdx_bytes = compute_two_inputs(words(*program)) + window_stem = "req_%016x" % key_of(root, cdx_bytes) + (directory / (window_stem + ".cdx")).write_bytes(cdx_bytes) + (directory / (window_stem + ".root")).write_bytes(root) + return directory, window_stem + + compiled_shapes = { + "stride_unused": (words_list[:after_wait] + [0x9398ff15, 0x000e0010] + words_list[after_wait:], + "an unused stride read compiles and publishes a .cso"), + # s_cmp_lg_u32 s16, s16 and s_cbranch_scc1 -2 (back to the compare, never taken) after the heap load: the loop + # does not contain the load, which runs once + "window_loop_after_load": (window(prefix=(0xbf071010, 0xbf85fffe)), + "a loop after the heap load does not refuse the window, a .cso is published"), + } + for name, (program, message) in compiled_shapes.items(): + directory, window_stem = window_request(name, program) + (directory / (window_stem + ".views")).write_text(good, newline="\n") + out_dir = base / (name + "_out") + code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + require(code == 0 and "requests=1 compiled=1 refused=0" in out and + (out_dir / (window_stem[len("req_"):] + ".cs.cso")).exists(), "compile_dxil: " + message) + window_outputs = {} + for n in (0, 1): + directory, window_stem = window_request(f"window{n}", WINDOW) + code, out, err = run([fixture, "record", sdk, cache, directory / (window_stem + ".cdx"), adapter, n, "ok"]) + require(code == 0 and "output matches slot %d data" % n in out, + f"record window select {n}: u0 equals the slot {n} data read through the rewritten descriptor") + out_dir = base / f"window{n}_out" + code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + cso = out_dir / (window_stem[len("req_"):] + ".cs.cso") + require(code == 0 and "requests=1 compiled=1 refused=0" in out and cso.exists(), + f"compile_dxil window select {n}: compiled and published a .cso") + window_outputs[n] = (directory, window_stem, cso) + code, out, err = run([fixture, "replay", sdk, cache, directory / (window_stem + ".cdx"), cso, + directory / (window_stem + ".views"), adapter, "ok", n]) + require(code == 0 and "output matches slot %d data" % n in out, f"replay window select {n}: output equals slot {n} data") + directory, window_stem, cso = window_outputs[0] + code, out, err = run([fixture, "replay", sdk, cache, directory / (window_stem + ".cdx"), cso, + directory / (window_stem + ".views"), adapter, "ok", 1]) + require(code == 1 and "mismatch word 0" in out, "replay window select 0 compared with slot 1 data reports a mismatch") + + missing = base / "missing" / (stem + ".views") + code, out, err = replay(selections[0], outputs[0], missing, "refused", 0) + require(code == 0 and "global SRV view metadata file missing: " + str(missing) in out and "sentinels intact" in out, + "replay with a missing .views path refuses with the file diagnostic, u0 sentinels intact") + +print("native_global_srv_heap_replay: all checks passed") diff --git a/tests/native_graphics_interface_library_check.py b/tests/native_graphics_interface_library_check.py new file mode 100644 index 000000000..79d3142ab --- /dev/null +++ b/tests/native_graphics_interface_library_check.py @@ -0,0 +1,94 @@ +"""Index source-built native containers and replay their raw runtime form.""" +import pathlib +import subprocess +import sys +import tempfile + +from native_direct_container_check import patched_pixel, publish, vertex, words + + +def main(compiler, sdk): + def run(*args, expected=None): + result = subprocess.run([compiler, *args], capture_output=True, text=True) + if expected is None: + assert result.returncode == 0, result.stderr + else: + assert result.returncode and expected in result.stderr, result.stderr + return result.stdout + + with tempfile.TemporaryDirectory() as tmp: + base = pathlib.Path(tmp) + library, cache, requests = (base / s for s in ("library", "cache", "requests")) + library.mkdir() + # The old raw reader has no PS state for this scalar branch. Exact + # native programs recover the full stage ABI from the catalog. + branch = [0xbf008180, 0xbf850002, 0x7e0002f2, 0xbf820001, 0x7e0002f4] + prefix = [0xd5800000, 255, 17, 0xd5800000, 255, 23] + program = prefix + branch + end = 0xbf810000 + vs = words(0x7e020b00, 0xf80008cf, 0x01010101, end) + ps = words(*program, 0xf800180f, 0, end) + pixel_file = library / "pixel.cdxil" + pixel_file.write_bytes(patched_pixel(len(program), program)) + vertex_file = library / "vertex.cdxil" + vertex_file.write_bytes(vertex()) + root = b"DXBC" + bytes(16) + words(1,68,1,36) + b"RTS0" + words(24,2,0,24,0,24,0) + stem = publish(requests, ps, vs, root) + def batch(folder, output, **kwargs): + return run(sdk, cache, "gfx1013-container-pair", "--requests", folder, output, **kwargs) + batch(requests, base / "bare", expected="verified stage interface") + install = ("--index-graphics-interfaces", library, cache) + run(*install) + for name, hit in (("cold",0), ("warm",1)): + assert f"frontend_cache_hit={hit}" in batch(requests, base / name) + run(sdk,cache,"gfx1013-container-pair",vertex_file,base/"vertex.cso",pixel_file,base/"pixel.cso") + for stage, name in (("vs","vertex"),("ps","pixel")): + binary = (base / (name+".cso")).read_bytes() + assert all((base / mode / (stem+"."+stage+".cso")).read_bytes() == binary for mode in ("cold","warm")) + # A second implementation shares the embedded ID. Exact matches + # still work, while a third unmatched implementation cannot pick one. + alternate = prefix + [0xbf800000] + branch + (library/"alternate.cdxil").write_bytes(patched_pixel(len(alternate),alternate)) + run(*install) + batch(requests,base/"exact") + other = base/"other" + publish(other, words(*prefix,0xbf800000,0xbf800000,*branch,0xf800180f,0,end),vs,root) + batch(other,base/"ambiguous",expected="ambiguous reviewed graphics interfaces") + # A failed rebuild must leave the published generation usable. + (library/"broken.cdxil").write_bytes(b"bad") + assert subprocess.run([compiler,*install],capture_output=True).returncode + batch(requests,base/"retained") + + # An exact VS writes a four-component image through the second + # guest slot. The serialized root covers just the first slot. + # The FSSM offset, descriptor width, class and SGPR establish the + # binding used by the C++ linker and copied to the runtime cache. + images = base / "images" + images.mkdir() + (images / "pixel.cdxil").write_bytes(pixel_file.read_bytes()) + vs_file = images / "store.cdxil" + op = [0xbe810380, 0xf40c0200, 0xfa000020, + 0x7e000280, 0x7e020280, 0x7e0802f2, 0x7e0a02f2, + 0xf0200f08, 0x80020400, 0xf80008cf, 0, end] + root_src, root_bin = base / "uav.hlsl", base / "uav.bin" + root_src.write_text('#define RS "DescriptorTable(UAV(u0))"') + subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-T", "rootsig_1_1", "-E", "RS", + root_src, "-Fo", root_bin], check=True) + job = base / "image-request" + publish(job, ps, words(*op), root_bin.read_bytes()) + for kind, width, sgpr, error in ( + (3, 8, 0, None), (0, 8, 0, "disagrees with reflected table record"), + (3, 4, 0, "disagrees with reflected table record"), + (3, 8, 1, "no matching user SGPR")): + vs_file.write_bytes(vertex(program=op, table=True, uses=[(0x300 | kind, 8, 0, 0, width | sgpr << 8)])) + run("--index-graphics-interfaces", images, cache) + output = base / f"store-{kind}-{width}-{sgpr}" + batch(job, output, expected=error) + if error: + assert not list(output.glob("*.cso")) + else: + assert "frontend_cache_hit=1" in batch(job, base / "warm-store") + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/tests/native_graphics_vertex_vcc_join_check.py b/tests/native_graphics_vertex_vcc_join_check.py new file mode 100644 index 000000000..0d0215afa --- /dev/null +++ b/tests/native_graphics_vertex_vcc_join_check.py @@ -0,0 +1,130 @@ +"""Draw source-built guest VS programs whose per-vertex VCC crosses a two-arm join.""" +import re +import struct +import subprocess +import sys +from pathlib import Path +from tempfile import TemporaryDirectory + +from native_direct_container_check import signature_rows, vertex +from native_scalar_lds_check import sop1, vmove + +NOP = 0xbf800000 +ARM_WORD = 8 +ARM_B_COMPARE = 15 +JOIN = 17 +LANE_JOIN = 17 + + +def cndmask(dst, taken, other): + # dst = VCC ? v[taken] : other + return 0x02000000 | dst << 17 | taken << 9 | other + + +def program(arm_b): + # Fullscreen triangle (-1,-1), (4,-1), (-1,4) from SV_VertexID in v0. + seq = [vmove(6, 246), + 0x7d040081, cndmask(1, 6, 243), # x = id == 1 ? 4 : -1 + 0x7d040082, cndmask(2, 6, 243), # y = id == 2 ? 4 : -1 + vmove(3, 128), vmove(7, 242), + # The harness supplies zero in b0, so the arm is chosen at draw time. + sop1(3, 4, 255), int(arm_b), 0x89040004, 0xbf008004, + 0xbf840003, # s4 != 0: arm B + 0x7d040081, vmove(4, 244), 0xbf820002, # A: VCC = id == 1, v4 = 2 + 0x7d0a0082, vmove(4, 246), # B: VCC = id != 2, v4 = 4 + vmove(5, 240), cndmask(5, 4, 261), # after the join: VCC ? v4 : 0.5 + 0xf80000cf, 0x07030201, 0xf8000a0f, 0x05050405, 0xbf810000] + assert seq[ARM_WORD] == arm_b and seq[ARM_B_COMPARE] == 0x7d0a0082 and seq[JOIN] == vmove(5, 240) + return seq + + +def lane_program(): + # The compare itself splits the wave: vertex 1 runs THEN, the others ELSE. + # VCC is written once, before the region, and read after EXEC is restored. + # The frontend lowers these arms to per-vertex selects in one block. + seq = program(False)[:7] + # A masked write keeps the previous v4 on the other lanes. + seq += [vmove(4, 242), + 0x7d040081, 0xbe88246a, 0xbf880002, # VCC = id == 1; save EXEC; skip THEN + vmove(4, 244), NOP, # THEN: v4 = 2 + 0x8afe7e08, 0xbf880001, vmove(4, 246), # ELSE: v4 = 4 + 0xbefe0408, + 0x101008f3, cndmask(5, 4, 264), # v8 = -v4; VCC ? v4 : v8 + 0xf80000cf, 0x07030201, 0xf8000a0f, 0x05050405, 0xbf810000] + assert seq[LANE_JOIN] == 0x101008f3 + return seq + + +def container(seq): + outputs = signature_rows([(b"TEXCOORD", 0, 3, 0, 15), (b"SV_Position", 1, 3, 1, 15)]) + return vertex(constants=(0, 1), program=seq, varying=True, extra=((b"OSG1", outputs),)) + + +def reference(arm_b): + """Per-vertex CPU model: three selected values, then the arm's own value.""" + arm = 4.0 if arm_b else 2.0 + vcc = [(vid != 2) if arm_b else (vid == 1) for vid in range(3)] + return [arm if bit else 0.5 for bit in vcc] + [arm] + + +def main(cli, raster, sdk, backend): + with TemporaryDirectory() as tmp: + work = Path(tmp) + source, vs, ps, expected = work/"source", work/"vs.cso", work/"ps.cso", work/"expected.bin" + # Every pixel reports the unblended value of each of the three vertices. + source.write_text("float4 main(nointerpolation float4 v:TEXCOORD, float4 p:SV_Position):SV_Target {" + "return float4(GetAttributeAtVertex(v,0).x,GetAttributeAtVertex(v,1).x," + "GetAttributeAtVertex(v,2).x,GetAttributeAtVertex(v,0).y);}") + subprocess.run([Path(sdk)/"dxc.exe", "-T", "ps_6_6", "-Fo", ps, source], check=True) + + def draw(seq, words): + source.write_bytes(container(seq)) + subprocess.run([cli, sdk, work/"cache", "gfx1013-container-vs", source, vs], check=True) + expected.write_bytes(struct.pack("<4f", *words)*8) + result = subprocess.run([raster, backend, "--startup-pixel-words", vs, ps, "4", "2", expected], + capture_output=True, text=True) + if result.returncode == 77: + print(result.stdout, result.stderr) + sys.exit(77) + return result + + def differs(result): + assert result.returncode == 1 and "8 of 8 pixels differ" in result.stderr, (result.stdout, result.stderr) + return result.stderr.splitlines()[0] + + for arm_b in (False, True): + result = draw(program(arm_b), reference(arm_b)) + assert result.returncode == 0, (result.stdout, result.stderr) + ir = subprocess.check_output([Path(sdk)/"dxc.exe", "-dumpbin", vs], text=True) + # Each arm supplies its own compare to the mask the select reads. + joined = re.search(r"(%\w+) = phi i32 \[ (%\w+), %g\d+ \], \[ (%\w+), %g\d+ \]\n", ir) + assert joined and joined[2] != joined[3] and "@dx.op.wave" not in ir, ir + mask = re.search(rf"(%\w+) = icmp ne i32 {joined[1]}, 0\n", ir) + assert mask and f"select i1 {mask[1]}," in ir, ir + print(*(line for line in result.stdout.splitlines() + if line.startswith(("backend=", "adapter=", "driver=", "debug_"))), sep="\n") + print(f"arm {'AB'[arm_b]}: vertices 0..2 and arm value matched {reference(arm_b)}") + # Vertex 0 supplies the fourth word, so it is the ELSE value. + lane = [-4.0, 2.0, -4.0, 4.0] + result = draw(lane_program(), lane) + assert result.returncode == 0, (result.stdout, result.stderr) + print(f"per-vertex arms: THEN on vertex 1, ELSE on vertices 0 and 2 matched {lane}") + uniform = lane_program() + uniform.insert(LANE_JOIN, 0x7d040100) + print("uniform mask after the per-vertex arms:", differs(draw(uniform, lane))) + # Control: arm B no longer contributes its own compare. The join + # then receives the stale id == 2 mask on that edge only. + dropped = program(True) + dropped[ARM_B_COMPARE] = NOP + print("dropped arm B contribution:", differs(draw(dropped, reference(True)))) + dropped[ARM_WORD] = 0 + assert draw(dropped, reference(False)).returncode == 0 + # Control: a uniform v0 == v0 replaces the joined mask. + for arm_b in (False, True): + uniform = program(arm_b) + uniform.insert(JOIN, 0x7d040100) + print(f"uniform mask after the join, arm {'AB'[arm_b]}:", differs(draw(uniform, reference(arm_b)))) + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/tests/native_graphics_wqm_check.py b/tests/native_graphics_wqm_check.py new file mode 100644 index 000000000..819b0de3d --- /dev/null +++ b/tests/native_graphics_wqm_check.py @@ -0,0 +1,328 @@ +"""Check whole-wave zero and pixel coverage using source-built guest shaders.""" +import re +import struct +import subprocess +import sys +from pathlib import Path +from tempfile import TemporaryDirectory + +from native_direct_container_check import patched_pixel, signature +from native_scalar_lds_check import sop1, vmove + + +def packed(lo, hi, narrow=False): + move = 3 if narrow else 4 + wqm = 9 if narrow else 10 + # Both paths are scalar until the original coverage is restored. + # Observe the actual expanded words and which direction EXECZ took. + # The harness supplies zero in b0. The front end and DXIL optimizer + # must still evaluate both words from runtime data at draw time. + def xor_root_word(dst, root): + return 0x80000000 | (0x12 << 23) | (dst << 16) | (root << 8) | dst + seq = [sop1(move,20,126), sop1(3,4,255),lo, sop1(3,5,255),hi, + xor_root_word(4,0), xor_root_word(5,1), + sop1(3,10,128), sop1(3,11,128), sop1(3,12,129), + sop1(wqm,126,4),0xbf880002,sop1(move,10,126),sop1(3,12,130), + sop1(move,126,20)] + # Byte-sized values remain exactly representable in the float target. + seq += [vmove(0,10),vmove(1,11),vmove(2,12),vmove(3,10)] + for v in (0,1,3): + seq += [(0x16<<25) | (v<<17) | (v<<9) | (152 if v==3 else 128), + (0x1b<<25) | (v<<17) | (v<<9) | 255,255] + for v in range(4): + seq += [0x7e000c00 | (v<<17) | (256+v)] + return patched_pixel(len(seq),seq,constants=(0,2),wave32=narrow,export=(0xf800180f,0x03020100), + input_signature=((b"OSG1",signature(b"SV_Target",64)),)) + + +def raster_program(limit=None, *, lower=None, cross=False): + # Drop coverage where limit < SV_Position.x. In a surviving quad + # the horizontal peer's coordinate must remain available, even if its + # own coverage was dropped. An empty quad branches to EXP_NULL. + seq=[sop1(4,12,126), sop1(10,126,126)] + attributes=() + if limit is None: + # Perspective-center P1/P2 of attr3.z, followed by 0 > v5. + p1=0xc8000000 | (5<<18) | (3<<10) | (2<<8) + seq += [p1, p1 | (1<<16) | 1, 0x7c080000 | (5<<9) | 128] + attributes=((6,0,15,3,0,0,0,0),) + inputs, input_address, value = signature(b"TEXCOORD"), 2, 5 + else: + threshold=struct.unpack("= value; the compare sets VCC for the lanes it removes. +def term_compare(axis, op, value): + return [(0x7c020000 if op=="le" else 0x7c080000) | ({"x":0,"y":1}[axis]<<9) | 255, + struct.unpack("=v) + for a,op,v in terms) + survives=lambda lane, helper: not helper and position(lane)[0]<=limit + def bit(lane, helper): + if base=="survivors" and not survives(lane,helper): + return False + if vote=="plain" and helper or vote=="survivors" and not survives(lane,helper): + return False + return keep(lane) + voted={(w if vote!="quad" else (w,lanes)) for w,lanes in quads if any(bit(*l) for l in lanes)} + pixels=[(-1.0,)*4]*16 + for w,lanes in quads: + flag=2.0 if (w if vote!="quad" else (w,lanes)) in voted else 1.0 + for lane,helper in lanes: + if survives(lane,helper): + pixels[lane]=(position(lane)[0],position(lane)[0],flag,flag) + return pixels + + +def desktop_quads(work, raster, sdk, backend, vs): + """Measure the quads and waves of the 8x2 draw with HLSL pixel stages on the same draw. + + Wave operations leave helper lanes out, so each covered pixel reports its wave (the smallest covered id in + it), the ids of its three quad peers and whether each peer is a helper (IsHelperLane, SM 6.6).""" + reads={"ids": ("ps_6_0","float4(WaveActiveMin(id),QuadReadAcrossX(id),QuadReadAcrossY(id)," + "QuadReadAcrossDiagonal(id))"), + "helpers": ("ps_6_6","float4(WaveGetLaneCount(),QuadReadAcrossX(h),QuadReadAcrossY(h)," + "QuadReadAcrossDiagonal(h))")} + data={} + for key,(profile,value) in reads.items(): + source, ps, out = work/f"{key}.hlsl", work/f"{key}.cso", work/f"{key}.bin" + source.write_text("float4 main(float4 p:SV_Position):SV_Target {uint id=uint(p.y)*8u+uint(p.x);" + f"uint h=IsHelperLane()?1u:0u; return {value};}}" if profile=="ps_6_6" else + "float4 main(float4 p:SV_Position):SV_Target {uint id=uint(p.y)*8u+uint(p.x);" + f"return {value};}}") + subprocess.run([Path(sdk)/"dxc.exe","-T",profile,"-Fo",ps,source],check=True) + result=subprocess.run([raster,backend,"--startup-pixel-dump",vs,ps,"8","2",out],capture_output=True,text=True) + if result.returncode==77: sys.exit(77) + assert result.returncode==0,(result.stdout,result.stderr) + values=struct.unpack("<64f",out.read_bytes()) + data[key]=[values[4*i:4*i+4] for i in range(16)] + quads, widths = {}, set() + for lane in range(16): + if data["ids"][lane]==(-1.0,)*4: + continue # not covered: the clear value + wave,*peers=(int(v) for v in data["ids"][lane]) + width,*helpers=(int(v) for v in data["helpers"][lane]) + widths.add(width) + members=((lane,False),*((p,bool(h)) for p,h in zip(peers,helpers))) + assert len({m[0] for m in members})==4 and all(position(p)[0]//2==position(lane)[0]//2 and + position(p)[1]//2==position(lane)[1]//2 for p,_ in members),\ + ("a desktop quad is not the aligned 2x2 block",lane,members) + quads.setdefault((wave,frozenset(members)),set()).add(lane) + assert len(widths)==1,widths + for (wave,members),lanes in quads.items(): + # Every covered lane of a quad reports the same quad, and its smallest covered lane names a wave. + assert lanes=={l for l,h in members if not h},(wave,members,lanes) + return [(w,tuple(sorted(m))) for w,m in quads], widths.pop() + + +VERTEX={"full": "float4 main(uint i:SV_VertexID):SV_Position {return float4(i==1?3:-1,i==2?3:-1,0,1);}", + # Covers the pixels with x + y < 5.5, so the quad at x = 4..5 has one covered lane, (4,0). + "diagonal": "float4 main(uint i:SV_VertexID):SV_Position {" + "return float4(i==0?-0.25:(i==1?0.5:-5),i==0?-1.5:(i==1?1.5:0),0,1);}"} +# (vertex, limit, terms, base): one quad's survivors hold the mask; a wider mask; an empty wave; a mask in +# covered quads without survivors (WQM before the filter); the same from the survivors; and masks that only +# the diagonal, horizontal or vertical helper of the one covered lane (4,0) holds. +CASES=(("full",6.5,(("x","le",1.0),),"survivors"), ("full",9,(("x","le",4.5),),"survivors"), + ("full",6.5,(("x","le",-1.0),),"survivors"), ("full",3.5,(("x","ge",4.5),),"wqm"), + ("full",3.5,(("x","ge",4.5),),"survivors"), + ("diagonal",4.5,(("x","ge",5.0),("y","ge",1.0)),"wqm"), + ("diagonal",4.5,(("x","ge",5.0),("y","le",1.0)),"wqm"), + ("diagonal",4.5,(("x","ge",4.0),("x","le",5.0),("y","ge",1.0)),"wqm")) + + +def ir_main(dump): + """Without a GPU: the vote's three quad reads and the wave vote come before any conditional branch, where + every lane of the quad, helpers included, still runs them (quad operations need quad-uniform control flow). + + The patterns follow the frontend's current text form (immediate i8 operands, attributes written inline on + the declaration); a change to that form, for example attribute groups, needs these patterns updated.""" + with TemporaryDirectory() as tmp: + blob=Path(tmp)/"cross.bin" + blob.write_bytes(cross_quad_program(6.5,(("x","le",1.0),))) + result=subprocess.run([dump,blob],capture_output=True,text=True) + assert result.returncode==0,result.stderr + body=result.stdout[result.stdout.index("define void @main"):] + first_branch=body.index("\n br i1 ") # the first conditional branch: the vote's own + quad=[m.group(1) for m in re.finditer(r"@dx\.op\.quadOp\.i32\(i32 123, i32 %\w+, i8 (\d)\)",body)] + vote=[m.start() for m in re.finditer(r"@dx\.op\.waveAnyTrue\(i32 113, i1 %\w+\)",body)] + assert sorted(quad)==["0","1","2"] and len(vote)==1,(quad,vote) + assert all(m.start()>24) + draw(packed(lo,hi,narrow),[pixel]*16) + print(f"wave{32 if narrow else 64} {hi:08x}:{lo:08x} -> {pixel}") + for limit in (0,0.5,2.5,9): + values=[(float((x^1)+0.5) if x+0.5<=limit else -1.0,)*4 for y in range(2) for x in range(8)] + draw(raster_program(limit),values) + print(f"filtered coverage limit={limit}: {sum(x[0]!=-1.0 for x in values)}/16 pixels survived") + for lower in (1.5,4.5): + values=[(float((x^1)+0.5) if lower<=x+0.5<=2.5 else -1.0,)*4 for y in range(2) for x in range(8)] + draw(raster_program(2.5,lower=lower),values) + print(f"two coverage filters [{lower},2.5]: {sum(x[0]!=-1.0 for x in values)}/16 pixels survived") + rejected=compile_guest(raster_program(2.5,cross=True)) + assert rejected.returncode and "complete guest vote or a quad-local continuation" in rejected.stderr,rejected.stderr + # Cross-quad EXECZ: the CPU reference comes from the measured desktop quads and waves of each draw. + controls, cross_controls, measured = {}, 0, {} + for kind,limit,terms,base in CASES: + vertex(kind) + if kind not in measured: + measured[kind]=desktop_quads(work,raster,sdk,backend,vs) + quads,width=measured[kind] + waves={w for w,_ in quads} + print(f"{kind} draw: {width} lanes, {len(quads)} quads in {len(waves)} waves, " + f"{sum(1 for w in waves if sum(1 for q,_ in quads if q==w)>1)} waves with more than one quad, " + f"{sum(h for _,lanes in quads for _,h in lanes)} helper lanes") + quads,_=measured[kind] + blob=cross_quad_program(limit,terms,base=base) + reference=lambda vote: cross_quad_reference(limit,terms,quads,vote,base=base) + whole=reference("wave") + draw(blob,whole) + label=f"{kind} limit={limit} {base} {terms}" + print(f"cross-quad {label}: {sum(p[0]!=-1.0 for p in whole)}/16 survive, " + f"s14 {sorted({p[2] for p in whole if p[0]!=-1.0})}") + for vote in ("quad","plain","survivors"): + other=reference(vote) + if other==whole: + continue + result=run(blob,other) + assert result.returncode==1 and "pixels differ" in result.stderr,(vote,label,result.stderr) + print(f" {vote} vote reference: {next(l for l in result.stderr.splitlines() if 'pixels differ' in l)}") + controls[vote]=controls.get(vote,0)+1 + cross_controls+=vote=="quad" + assert cross_quad_reference(6.5,(("x","le",-1.0),),measured["full"][0],"wave")== \ + cross_quad_reference(6.5,(("x","le",-1.0),),measured["full"][0],"quad") + assert controls.get("plain",0)>=3,controls # the three single-helper masks are decided by the quad OR + vertex("full") + # Lane reads, vector writes, branches and EXEC changes inside the region keep a named refusal. + for label,region,reason in ( + ("DPP inside the region",(0x7e0402fa,0xff04b100),"may only write scalars"), + ("VGPR write inside the region",(vmove(1,14),),"may only write scalars"), + ("EXEC read inside the region",(sop1(4,20,126),),"may only write scalars"), + ("branch inside the region",(0xbf820000,),"region contains a branch"), + ("EXEC rewritten inside the region",(sop1(4,126,16),),"must branch to the exact coverage restore"), + ("s_setreg_b32 inside the region",(0xb98e0801,),"hardware register"), + ("s_getreg_b32 inside the region",(0xb9140801,),"hardware register")): + rejected=compile_guest(cross_quad_program(6.5,(("x","le",1.0),),region=region)) + assert rejected.returncode and reason in rejected.stderr,(label,rejected.stderr) + print(f"refused: {label}: ok") + # The pixel program now consumes an interpolated value produced by + # the VS, including a negative coordinate from a WQM helper. + source.write_text("struct Out { float4 tc:TEXCOORD; float4 pos:SV_Position; };" + "Out main(uint i:SV_VertexID) { Out o;" + "o.pos=float4(i==1?3:-1,i==2?3:-1,0,1);" + "o.tc=float4(0,0,3.25-(o.pos.x+1)*4,0); return o; }") + subprocess.run([Path(sdk)/"dxc.exe","-T","vs_6_6","-Fo",vs,source],check=True) + values=[(16+3.25-((x^1)+0.5) if x+0.5<=3.25 else -1.0,)*4 for y in range(2) for x in range(8)] + draw(raster_program(),values) + print("attr3.z perspective interpolation, VCC filter and WQM/EXECZ: all 16 pixels matched") + print(f"cross-quad EXECZ negative controls that differ from the readback: {controls}") + if not cross_controls: + reason=f"no desktop wave holds two quads ({measured['full'][1]} lanes)" + if backend=="hardware": + # Every other check passed; the cross-quad decision itself was not exercised. + print(f"skip: the cross-quad quad-local control needs two quads in one wave: {reason}") + sys.exit(77) + print(f"SKIPPED cross-quad quad-local control: {reason}") + + +if __name__=="__main__": + if sys.argv[1]=="ir": + ir_main(sys.argv[2]) + else: + main(*sys.argv[1:]) diff --git a/tests/native_half_grid.cpp b/tests/native_half_grid.cpp new file mode 100644 index 000000000..af7d08c93 --- /dev/null +++ b/tests/native_half_grid.cpp @@ -0,0 +1,176 @@ +#include "desktop_gpu.h" +#include "native_compute_pipeline.h" +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; +namespace { +constexpr UINT width = 40, height = 54; +struct Surface { + ComPtr texture, upload, readback; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 size{}; + bool half{}, writable{}; +}; +Surface make_surface(ID3D12Device *device, ID3D12GraphicsCommandList *list, bool writable, bool half, bool bit_input, bool prefix) { + Surface s; + s.writable = writable; + s.half = half; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; + desc.Format = half ? DXGI_FORMAT_R16_FLOAT : DXGI_FORMAT_R32G32B32A32_FLOAT; + desc.Flags = writable ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE; + s.texture = resource(device, desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST); + device->GetCopyableFootprints(&desc, 0, 1, 0, &s.footprint, nullptr, nullptr, &s.size); + s.upload = make_buffer(device, s.size, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + void *mapped; + check(s.upload->Map(0, nullptr, &mapped), "upload"); + for (UINT y = 0; y < height; ++y) { + auto row = static_cast(mapped) + y * s.footprint.Footprint.RowPitch; + for (UINT x = 0; x < width; ++x) { + if (half) { + reinterpret_cast(row)[x] = 0x5400; // +64 sentinel + } else { + auto pixel = reinterpret_cast(row) + 4*x; + for (UINT k = 0; k < 4; ++k) + pixel[k] = writable ? 64.f : float(1+x+16*y+k); + if (!writable && prefix) + pixel[0] = x == 1+y ? 2.f : x == 9-y ? -2.f : x == 14 ? float(y+1) : 0.f; + if (!writable && bit_input && ((x+y)&1)) { + UINT bits; + std::memcpy(&bits, pixel, 4); + bits |= 2; + std::memcpy(pixel, &bits, 4); + } + } + } + } + s.upload->Unmap(0, nullptr); + D3D12_TEXTURE_COPY_LOCATION src{s.upload.Get(),D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + D3D12_TEXTURE_COPY_LOCATION dst{s.texture.Get(),D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + src.PlacedFootprint = s.footprint; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + transition(list, s.texture.Get(), D3D12_RESOURCE_STATE_COPY_DEST, writable ? + D3D12_RESOURCE_STATE_UNORDERED_ACCESS : D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + if (writable) + s.readback = make_buffer(device, s.size, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + return s; +} +} + +int check_half_grid(ID3D12Device *device, x2w::ShaderDxilCompiler &compiler, const wchar_t *marker, + const wchar_t *cache, const std::wstring &mode) { + const bool shift = mode == L"half-shift", bits = mode == L"half-bit", offset = mode == L"half-offset"; + const bool fixture = mode == L"half-value" || mode == L"half-mutant"; + if (!shift && !bits && !offset && !fixture && mode != L"half-clear" && mode != L"half-dual") + return 2; + auto request = x2w::read_compute_request(marker); + UINT shape; + std::memcpy(&shape, request.sa.data()+12, 4); + const UINT gx = shape & 65535, gy = shape >> 16; + auto p = x2w::create_native_compute_pipeline(device, compiler, marker, fixture ? 0 : 36, cache); + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, UINT(p.bindings.size()), + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr heap; + check(device->CreateDescriptorHeap(&hd,IID_PPV_ARGS(&heap)), "half heap"); + UINT step = device->GetDescriptorHandleIncrementSize(hd.Type); + auto cpu = heap->GetCPUDescriptorHandleForHeapStart(); + ComputeCommands cmd(device,p.state.Get(),D3D12_COMMAND_LIST_TYPE_DIRECT); + // Multiple desktop views of one guest slot must see the same underlying storage. + using Slot = std::pair; + std::map surfaces; + ComPtr params; + for (const auto &b : p.bindings) { + const bool write = x2w::compute_uav(b.kind); + Slot slot{b.root_parameter,b.byte_offset}; + if (b.kind == x2w::ComputeViewKind::buffer_srv && offset && slot.second == 32) { + params = make_buffer(device, 24, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + const UINT words[]{91,98,87,77,3,5}; + void *data; + check(params->Map(0,nullptr,&data),"offset buffer"); + std::memcpy(data, words,sizeof(words)); + params->Unmap(0,nullptr); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.Buffer.NumElements = 6; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(params.Get(),&srv,cpu); + } else { + bool half = b.kind == x2w::ComputeViewKind::half_scalar_uav || (shift && slot.second == 64); + if (!surfaces.count(slot)) + surfaces.emplace(slot,make_surface(device,cmd.list.Get(),write,half,bits,shift)); + auto &s = surfaces.at(slot); + if (write) + device->CreateUnorderedAccessView(s.texture.Get(),nullptr,nullptr,cpu); + else + device->CreateShaderResourceView(s.texture.Get(),nullptr,cpu); + } + cpu.ptr += step; + } + if (surfaces.size() != (shift || bits ? 3u : mode == L"half-dual" ? 2u : 1u)) + return 2; + const UINT groups_x = shift ? 1 : 2, groups_y = 3; + std::vector constants(p.constant_words,0); + p.bind(cmd.list.Get(),heap.Get(),heap->GetGPUDescriptorHandleForHeapStart(),step,constants.data()); + cmd.list->Dispatch(groups_x,groups_y,1); + for (auto &[slot,s] : surfaces) { + if (!s.writable) continue; + transition(cmd.list.Get(),s.texture.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS,D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION src{s.texture.Get(),D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + D3D12_TEXTURE_COPY_LOCATION dst{s.readback.Get(),D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + dst.PlacedFootprint = s.footprint; + cmd.list->CopyTextureRegion(&dst,0,0,0,&src,nullptr); + } + cmd.submit_and_wait(device); + check(device->GetDeviceRemovedReason(),"half completion"); + UINT differences = 0, checked = 0; + for (auto &[slot,s] : surfaces) { + if (!s.writable) continue; + void *mapped; + check(s.readback->Map(0,nullptr,&mapped),"half readback"); + for (UINT y = 0; y < height; ++y) { + auto row = static_cast(mapped) + y*s.footprint.Footprint.RowPitch; + for (UINT x = 0; x < width; ++x) { + UINT ox = offset ? 3 : 0, oy = offset ? 5 : 0; + bool covered = x >= ox && y >= oy && x-ox < gx*groups_x && y-oy < gy*groups_y; + if (s.half) { + UINT expected = covered ? (fixture ? 0xc100u : 0u) : 0x5400u; + if (shift) { + expected = 0x5400; + if (x < 16 && y < groups_y) { + // Exclusive u32 prefix of the bit patterns for +2 and -2. + // Their modulo-2^32 sum is zero. The last source value is y+1. + constexpr uint16_t tail[]{0x3c00, 0x4000, 0x4200}; + expected = x == 15 ? tail[y] : x > 1+y && x <= 9-y ? 0x4000 : 0; + } + } + differences += reinterpret_cast(row)[x] != expected; + ++checked; + } else { + float expected = 64.f; + if (shift && y == 0 && x < groups_y) expected = float(x+1); + if (bits && covered) { + UINT value = ((x+y)&1) * 2; + std::memcpy(&expected,&value,4); + } + for (UINT k = 0; k < 4; ++k) { + differences += std::memcmp(row+(4*x+k)*4,&expected,4) != 0; + ++checked; + } + } + } + } + s.readback->Unmap(0,nullptr); + } + std::printf("components=%u differing_components=%u cache_hit=%d frontend_ms=%.4f backend_ms=%.4f pso_ms=%.4f\n", + checked,differences,p.cache_hit,p.frontend_ms,p.backend_ms,p.pipeline_ms); + return differences ? 1 : 0; +} diff --git a/tests/native_heap_handle_probe.cpp b/tests/native_heap_handle_probe.cpp new file mode 100644 index 000000000..6fb745d5d --- /dev/null +++ b/tests/native_heap_handle_probe.cpp @@ -0,0 +1,292 @@ +// Cycle 1 of the global SRV work: can a native compute module read through ResourceDescriptorHeap[index]? +// +// Two shaders select a heap slot from a GPU word and copy that slot's raw buffer to a UAV: one is HLSL compiled by DXC +// (the reference), the other is the textual DXIL module the native compiler builds (dx.op.createHandleFromHeap, opcode +// 218). Both run on the same pipeline shape (root flag CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) with two different selector +// words: the readbacks must be the distinct data of slot A and slot B, and a UAV guard word past the copied range must +// stay intact. Usage: native_heap_handle_probe ADAPTER SDK_DIRECTORY WORK_DIRECTORY SHADER_FLAGS +// ADAPTER is warp or hardware. Exit 77 when the adapter lacks shader model 6.6 or resource binding tier 3. +#include "dxil_module.h" +#include "shader_dxil_compiler.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +namespace { +constexpr UINT words = 64; +constexpr UINT guard_word = 0xC0FFEE11u; +constexpr UINT sentinel = 0xCAFEF00Du; + +UINT slot_word(UINT slot, UINT i) { return (slot == 0 ? 0x1000u : 0x9000u) + i * (slot == 0 ? 7u : 13u); } + +ComPtr make_buffer(ID3D12Device *device, UINT64 bytes, D3D12_HEAP_TYPE type, D3D12_RESOURCE_STATES state, + D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + D3D12_HEAP_PROPERTIES heap{type}; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = flags; + ComPtr resource; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(&resource)))) + return {}; + return resource; +} + +struct Gpu { + ComPtr device; + ComPtr queue; + ComPtr allocator; + ComPtr list; + ComPtr fence; + UINT64 value = 0; + bool open(ID3D12Device *d) { + device = d; + D3D12_COMMAND_QUEUE_DESC q{D3D12_COMMAND_LIST_TYPE_DIRECT}; + return SUCCEEDED(d->CreateCommandQueue(&q, IID_PPV_ARGS(&queue))) && + SUCCEEDED(d->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) && + SUCCEEDED(d->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(&list))) && + SUCCEEDED(list->Close()) && SUCCEEDED(d->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))); + } + template bool run(Record &&record) { + if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.Get(), nullptr))) return false; + record(list.Get()); + if (FAILED(list->Close())) return false; + ID3D12CommandList *lists[]{list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.Get(), ++value))) return false; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + fence->SetEventOnCompletion(value, event); + WaitForSingleObject(event, 30000); + CloseHandle(event); + return fence->GetCompletedValue() >= value; + } +}; + +void transition(ID3D12GraphicsCommandList *list, ID3D12Resource *r, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) { + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {r, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, from, to}; + list->ResourceBarrier(1, &b); +} + +// The dxil module of the native compiler: output[tid] = ResourceDescriptorHeap[selection[0]][tid]. +std::string native_module(unsigned shader_flags) { + x2w::DxilModule m; + m.features = shader_flags | 16; + const auto selection = m.handle({0, 0, 11, 0, 0, 0}); + const auto output = m.handle({1, 0, 11, 0, 0, 0}); + const auto thread = m.invoke("i32", "threadId.i32", 93, {{"i32", "0"}}, "nounwind readnone"); + const auto address = m.binary("shl", thread, "2"); + const auto word = m.invoke("%dx.types.ResRet.i32", "rawBufferLoad.i32", 139, + {{"%dx.types.Handle", selection}, {"i32", "0"}, {"i32", "undef"}, {"i8", "1"}, {"i32", "4"}}, + "nounwind readonly"); + const auto slot = m.value("extractvalue %dx.types.ResRet.i32 " + word + ", 0"); + const auto data = m.heap_handle(slot, 11, 0); + const auto loaded = m.invoke("%dx.types.ResRet.i32", "rawBufferLoad.i32", 139, + {{"%dx.types.Handle", data}, {"i32", address}, {"i32", "undef"}, {"i8", "1"}, {"i32", "4"}}, + "nounwind readonly"); + const auto value = m.value("extractvalue %dx.types.ResRet.i32 " + loaded + ", 0"); + m.invoke("void", "rawBufferStore.i32", 140, + {{"%dx.types.Handle", output}, {"i32", address}, {"i32", "undef"}, {"i32", value}, {"i32", "undef"}, + {"i32", "undef"}, {"i32", "undef"}, {"i8", "1"}, {"i32", "4"}}, + "nounwind"); + m.body << " ret void\n"; + return m.finish_compute(words, 1, 1); +} + +const char *reference_hlsl = + "ByteAddressBuffer selection : register(t0);\n" + "RWByteAddressBuffer output : register(u0);\n" + "[numthreads(64, 1, 1)] void main(uint3 id : SV_DispatchThreadID) {\n" + " ByteAddressBuffer data = ResourceDescriptorHeap[selection.Load(0)];\n" + " output.Store(id.x * 4, data.Load(id.x * 4));\n" + "}\n"; +} // namespace + +int wmain(int argc, wchar_t **argv) { + if (argc != 5) { + std::fputs("usage: native_heap_handle_probe ADAPTER SDK WORK SHADER_FLAGS\n", stderr); + return 2; + } + const std::wstring adapter = argv[1]; + const unsigned shader_flags = static_cast(std::stoull(argv[4])); + const std::filesystem::path work = argv[3]; + std::filesystem::create_directories(work); + + ComPtr factory; + ComPtr chosen; + ComPtr device; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 77; + if (adapter == L"warp") { + if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&chosen)))) return 77; + } else { + for (UINT i = 0; i < 8; ++i) { + ComPtr candidate; + if (factory->EnumAdapters1(i, &candidate) == DXGI_ERROR_NOT_FOUND) break; + DXGI_ADAPTER_DESC1 desc{}; + candidate->GetDesc1(&desc); + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) { chosen = candidate; break; } + } + if (!chosen) { std::puts("no hardware adapter"); return 77; } + } + if (FAILED(D3D12CreateDevice(chosen.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) { std::puts("no device"); return 77; } + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_6}; + D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; + if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &model, sizeof model)) || + model.HighestShaderModel < D3D_SHADER_MODEL_6_6 || + FAILED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof options)) || + options.ResourceBindingTier < D3D12_RESOURCE_BINDING_TIER_3) { + std::printf("adapter lacks shader model 6.6 or resource binding tier 3 (tier %d)\n", int(options.ResourceBindingTier)); + return 77; + } + // The native module declares WaveSize=32 (the guest wave), so an adapter without 32-lane waves cannot create it. + D3D12_FEATURE_DATA_D3D12_OPTIONS1 waves{}; + if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, &waves, sizeof waves)) || !waves.WaveOps || + waves.WaveLaneCountMin > 32 || waves.WaveLaneCountMax < 32) { + std::printf("adapter has no 32-lane waves (%u..%u)\n", waves.WaveLaneCountMin, waves.WaveLaneCountMax); + return 77; + } + try { + x2w::ShaderDxilCompiler compiler(argv[2]); + const auto module = native_module(shader_flags); + std::ofstream(work / "native_module.ll") << module; + x2w::CompiledShader reference, native; + reference = compiler.compile(reference_hlsl, L"cs_6_6", work); + try { + native = compiler.compile(module, L"cs_6_6", work, x2w::ShaderSourceFormat::dxil_ir); + } catch (const std::exception &error) { + std::printf("FAIL: the native module was refused by the compiler or validator: %s\n", error.what()); + return 3; + } + + // Both containers go to the work directory so the check script can print how they differ. + for (const auto &[name, shader] : {std::pair{"reference.dxil", &reference}, + std::pair{"native.dxil", &native}}) + std::ofstream(work / name, std::ios::binary) + .write(reinterpret_cast(shader->dxil.data()), static_cast(shader->dxil.size())); + + // Root signature: root SRV t0 (selector), root UAV u0 (output), and the heap indexed directly. + D3D12_ROOT_PARAMETER1 parameters[2]{}; + parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC versioned{}; + versioned.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + versioned.Desc_1_1.NumParameters = 2; + versioned.Desc_1_1.pParameters = parameters; + versioned.Desc_1_1.Flags = static_cast(0x400); // CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED + ComPtr blob, error; + ComPtr root; + if (FAILED(D3D12SerializeVersionedRootSignature(&versioned, &blob, &error)) || + FAILED(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root)))) { + std::puts("FAIL: root signature with the heap-indexed flag"); + return 4; + } + ComPtr states[2]; + const x2w::CompiledShader *shaders[2]{&reference, &native}; + for (int k = 0; k < 2; ++k) { + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = root.Get(); + pso.CS = {shaders[k]->dxil.data(), shaders[k]->dxil.size()}; + if (FAILED(device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&states[k])))) { + std::printf("FAIL: pipeline state of the %s shader\n", k ? "native" : "reference"); + return 5; + } + } + + // Heap slots 0 and 1: two raw buffers with different data. Slot 2: a buffer of another size, never selected. + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 3, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr heap; + if (FAILED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)))) return 6; + const UINT step = device->GetDescriptorHandleIncrementSize(heap_desc.Type); + ComPtr data[2], decoy; + void *mapped = nullptr; + for (UINT s = 0; s < 2; ++s) { + data[s] = make_buffer(device.Get(), words * 4, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + if (!data[s] || FAILED(data[s]->Map(0, nullptr, &mapped))) return 6; + for (UINT i = 0; i < words; ++i) static_cast(mapped)[i] = slot_word(s, i); + data[s]->Unmap(0, nullptr); + } + decoy = make_buffer(device.Get(), words * 4, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Buffer.NumElements = words; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + auto cpu = heap->GetCPUDescriptorHandleForHeapStart(); + for (ID3D12Resource *r : {data[0].Get(), data[1].Get(), decoy.Get()}) { + device->CreateShaderResourceView(r, &srv, cpu); + cpu.ptr += step; + } + + auto selection = make_buffer(device.Get(), 256, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + auto output = make_buffer(device.Get(), (words + 1) * 4, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + auto seed = make_buffer(device.Get(), (words + 1) * 4, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + auto readback = make_buffer(device.Get(), (words + 1) * 4, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + if (!selection || !output || !seed || !readback) return 6; + Gpu gpu; + if (!gpu.open(device.Get())) return 6; + int failures = 0; + for (int k = 0; k < 2; ++k) { + const char *name = k ? "native" : "reference"; + std::vector seen[2]; + for (UINT selected = 0; selected < 2; ++selected) { + seed->Map(0, nullptr, &mapped); + for (UINT i = 0; i < words; ++i) static_cast(mapped)[i] = sentinel; + static_cast(mapped)[words] = guard_word; + seed->Unmap(0, nullptr); + selection->Map(0, nullptr, &mapped); + static_cast(mapped)[0] = selected; + selection->Unmap(0, nullptr); + const bool ok = gpu.run([&](ID3D12GraphicsCommandList *list) { + transition(list, output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyResource(output.Get(), seed.Get()); + transition(list, output.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + ID3D12DescriptorHeap *heaps[]{heap.Get()}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootSignature(root.Get()); + list->SetPipelineState(states[k].Get()); + list->SetComputeRootShaderResourceView(0, selection->GetGPUVirtualAddress()); + list->SetComputeRootUnorderedAccessView(1, output->GetGPUVirtualAddress()); + list->Dispatch(1, 1, 1); + transition(list, output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyResource(readback.Get(), output.Get()); + transition(list, output.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + }); + if (!ok || FAILED(device->GetDeviceRemovedReason())) { + std::printf("FAIL: %s dispatch selecting slot %u did not complete\n", name, selected); + return 7; + } + readback->Map(0, nullptr, &mapped); + seen[selected].assign(static_cast(mapped), static_cast(mapped) + words + 1); + readback->Unmap(0, nullptr); + bool match = true; + for (UINT i = 0; i < words; ++i) match &= seen[selected][i] == slot_word(selected, i); + const bool guard = seen[selected][words] == guard_word; + std::printf("%s selector %u: data %s, guard %s\n", name, selected, match ? "matches the CPU reference" : "DIFFERS", + guard ? "intact" : "OVERWRITTEN"); + failures += !match || !guard; + } + if (seen[0] == seen[1]) { + std::printf("FAIL: %s read the same data for both selectors\n", name); + ++failures; + } + } + std::puts(failures ? "native_heap_handle_probe: FAIL" : "native_heap_handle_probe: PASS"); + return failures ? 1 : 0; + } catch (const std::exception &error) { + std::printf("FAIL: %s\n", error.what()); + return 8; + } +} diff --git a/tests/native_heap_handle_probe_check.py b/tests/native_heap_handle_probe_check.py new file mode 100644 index 000000000..eb9fa22c1 --- /dev/null +++ b/tests/native_heap_handle_probe_check.py @@ -0,0 +1,58 @@ +"""Cycle 1 of the global SRV work: compile a reference ResourceDescriptorHeap shader with DXC, show how DXC spells the heap handle and +its shader flags, then run the native heap-handle probe with those flags (exit 77 from the probe is a skip).""" +import re +import subprocess +import sys +import tempfile +from pathlib import Path + + +REFERENCE = """ByteAddressBuffer selection : register(t0); +RWByteAddressBuffer output : register(u0); +[numthreads(64, 1, 1)] void main(uint3 id : SV_DispatchThreadID) { + ByteAddressBuffer data = ResourceDescriptorHeap[selection.Load(0)]; + output.Store(id.x * 4, data.Load(id.x * 4)); +} +""" + + +def main(probe, sdk, adapter): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + source = work / "reference.hlsl" + source.write_text(REFERENCE) + listing = work / "reference.ll" + subprocess.run([str(Path(sdk) / "dxc.exe"), "-T", "cs_6_6", "-E", "main", "-Fc", str(listing), str(source)], check=True, + capture_output=True) + text = listing.read_text() + flags = re.search(r"!\{i32 0, i64 (\d+)", text) + if not flags: + raise AssertionError("the reference listing has no shader flags tag") + for line in text.splitlines(): + if "createHandleFromHeap" in line or "annotateHandle(i32 216" in line and "ResourceProperties { i32 11" in line: + print("reference:", line.strip()) + print("reference shader flags:", flags.group(1)) + result = subprocess.run([probe, adapter, sdk, str(work / "probe"), flags.group(1)], capture_output=True, text=True) + print(result.stdout, end="") + print(result.stderr, end="") + if result.returncode not in (0, 77): + # Show how the two containers differ (module, shader flags, pipeline state validation data). + import difflib + listings = {} + for name in ("reference", "native"): + container = work / "probe" / f"{name}.dxil" + if container.exists(): + listings[name] = subprocess.run([str(Path(sdk) / "dxc.exe"), "-dumpbin", str(container)], + capture_output=True, text=True).stdout.splitlines() + if len(listings) == 2: + diff = list(difflib.unified_diff(listings["reference"], listings["native"], "reference", "native", lineterm="", n=1)) + print("\n".join(diff[:160])) + if result.returncode == 77: + return 77 + assert result.returncode == 0, f"probe exit {result.returncode}" + assert "native_heap_handle_probe: PASS" in result.stdout + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:4])) diff --git a/tests/native_indexed_atomic_check.py b/tests/native_indexed_atomic_check.py new file mode 100644 index 000000000..2efea33e7 --- /dev/null +++ b/tests/native_indexed_atomic_check.py @@ -0,0 +1,100 @@ +"""Check indexed atomics against recorded structured, raw and typed UAV windows.""" +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from native_compute_clear_check import write_request +from native_scalar_lds_check import sop1, scalar, vmove + + +def program(mutant): + # s4 is the table, s5 is group.x. Only lane zero may perform each atomic. + words = [sop1(3, 20, 4), sop1(3, 21, 128), sop1(3, 126, 129), + scalar(0x1e, 7, 5, 132), scalar(0, 7, 7, 132), scalar(0x1e, 8, 5, 135), vmove(8, 8)] + for j in range(5): + words += [0xf4080000 | ((32 + 4*j) << 6) | 10, 0xfa000000 | (32 + 32*j)] + for j in range(4): + slot, first = (8 + j) << 16, 10 + 3*j + # Aliased vaddr/vdata. GLC returns the original value. Without GLC + # the source stays unchanged. The huge unsigned index must never wrap. + words += [vmove(1, 7), 0xe0c86000, 0x80000101 | slot, vmove(first, 257), + vmove(1, 7), vmove(2, 132 if mutant else 131), 0xe0c82000, 0x80000201 | slot, + vmove(first+1, 258), vmove(1, 193), 0xe0c86000, 0x80000201 | slot, vmove(first+2, 258)] + for j in range(12): + words += [0xe0701000 | (4*j), 0x800c0008 | (10+j) << 8] + # Only group zero touches each window's last complete dword. Group one + # keeps a different pre-existing VGPR value while EXEC is empty. + for j in range(4): + slot = (8 + j) << 16 + last = 8188 if j == 3 else 2047 + words += [vmove(2, 137), vmove(3, 137), vmove(1, 255), last, vmove(4, 255), last + 1, + 0xbf068005, scalar(0x0a, 126, 129, 128), + 0xe0c86000, 0x80000201 | slot, 0xe0c86000, 0x80000304 | slot, sop1(3, 126, 129), + 0xe0701000 | (48 + 8*j), 0x800c0208, 0xe0701000 | (52 + 8*j), 0x800c0308] + return words + [0xbf810000] + + +def check_output(blob, layout, mutant): + rest = memoryview(blob) + for _, offset, _, stride, write in layout: + assert write == 1 + words = (2048 + 16) * stride // 4 + data = struct.unpack_from(f"<{words}I", rest) + rest = rest[4 * words:] + expected = [0x69696969] * words + for group in range(2): + index = 4 + 16*group + increment = 4 if mutant else 3 + if offset == 160: + window = 8 + group*32 + expected[window:window+12] = [0x69696969, increment, 0] * 4 + expected[window+12:window+20] = ([9, 9] if group else [0x69696969, 0]) * 4 + else: + assert offset in (32, 64, 96, 128) + start = 8 * stride // 4 + word = index//4 if offset == 128 else index*stride//4 + expected[start + word] += index + increment + if not group: + last = 2047 if offset == 128 else 2047 * stride // 4 + expected[start + last] += 9 + assert data == tuple(expected), (offset, [(j, a, b) for j,(a,b) in enumerate(zip(data,expected)) if a!=b][:8]) + assert not rest and len(layout) == 5 + + +def main(cli, gpu, sdk): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src, root = work/"root.hlsl", work/"root.bin" + src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk)/"dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, src], check=True) + sa = struct.pack("<7I",0,0,0,32 | 1<<16,1,0,0x8a) + previous = None + for mutant in (False, True): + words = program(mutant) + marker = write_request(work, words, root.read_bytes(), sa) + dest = work/"result.bin" + run = subprocess.run([gpu, sdk, marker, work/"cache", "0", dest, "--direct"], capture_output=True,text=True) + if run.returncode == 77: + print(run.stderr); sys.exit(77) + assert run.returncode == 0, run.stderr + data = dest.read_bytes() + check_output(data, [tuple(map(int,line.split())) for line in run.stdout.splitlines()], mutant) + if previous is not None: + diff = sum(a != b for a,b in zip(struct.iter_unpack("> lane) & 1 else 5, + value, lanes[first], lanes[5], lanes[first], 0x89abcdef, 0x89abcdef] + return expected + + +def check_refusals(cli, sdk, work, root): + direct = "gfx1013-direct-cs@0" + hlsl = "gfx1013-compute-wave32@0" + partial = "lane read/write needs full waves" + invalid = "invalid scalar lane read destination" + cases = [ + (direct, 30, readlane(14, 1, 13), partial), + (direct, 30, writelane(1, 129, 159), partial), + (direct, 62, readlane(14, 1, 13), partial), + (direct, 32, readlane(14, 1, 257), "lane read/write needs a constant or SGPR lane"), + (direct, 32, [0xd7610811, 129 | 128 << 9], "lane read/write encoding or operand modifiers"), + (direct, 32, readlane(108, 1, 128), invalid), + (direct, 32, [readfirstlane(108, 1)], invalid), + (hlsl, 32, readlane(106, 1, 128), invalid), + (hlsl, 32, [readfirstlane(106, 1)], invalid), + (hlsl, 32, readlane(107, 1, 128), invalid), + (hlsl, 32, [readfirstlane(107, 1)], invalid), + ] + for profile, threads, operation, diagnostic in cases: + words = [vmove(1, 128), sop1(3, 13, 129), *operation, 0xbf810000] + marker = write_request(work, words, root, launch(threads)) + dest = work / "refused.cso" + result = subprocess.run([cli, sdk, work / "cache", profile, marker, dest], + capture_output=True, text=True) + assert result.returncode != 0 and diagnostic in result.stdout + result.stderr, ( + profile, threads, operation, result.stdout, result.stderr) + assert not dest.exists() + + +def main(cli, replay, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + source, root_file = work / "root.hlsl", work / "root.bin" + source.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root_file, source], check=True) + root = root_file.read_bytes() + check_refusals(cli, sdk, work, root) + marker = write_request(work, program(), root, launch(32)) + dest = work / "result.bin" + result = subprocess.run([replay, sdk, marker, work / "cache", "0", dest, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack("<2064I", dest.read_bytes()) + expected = reference() + mismatches = [(i, a, b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b] + assert not mismatches, mismatches[:12] + print("Two workgroups matched 768 lane-access words and all guards.") + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_lds_control_flow_check.py b/tests/native_lds_control_flow_check.py new file mode 100644 index 000000000..da00c508c --- /dev/null +++ b/tests/native_lds_control_flow_check.py @@ -0,0 +1,51 @@ +"""Exercise the shared-memory frontend's reconvergence and rejection paths.""" +from pathlib import Path +import struct +import sys +from types import SimpleNamespace + +sys.path.insert(0,str(Path(__file__).resolve().parents[1]/"tools/startup")) +from compile_lds_request import ComputeStage +from gfx2hlsl import Unsupported + + +barrier = "GroupMemoryBarrierWithGroupSync();" +blocks = [(0,[],("branch","(exec & 1) == 0",16)), (8,["v1 = 2;"],None), + (16,[barrier],("end",))] +source = "\n".join(ComputeStage.body(SimpleNamespace(blocks=blocks))) +assert "!WaveActiveAnyTrue((exec&1u)!=0u)" in source +assert "}\n"+barrier+"\nif(pc==" in source + +for invalid, expected in [ + ([(0,[],("branch","scc",16)),(8,[barrier],None),(16,[],("end",))],"conditional"), + ([(0,[barrier],("jump",0))],"forward"), +]: + try: + ComputeStage.body(SimpleNamespace(blocks=invalid)) + except Unsupported as error: + assert expected in str(error), error + else: + raise AssertionError("accepted invalid compute control flow") +print("uniform barrier and wave-level EXEC branch passed; divergent barrier and back edge rejected") + +# A returning atomic replaces the entire destination, including a previous +# partial d16 result. Its address must still be readable when the registers alias. +def atomic_with_partial_register(address): + stage = ComputeStage.__new__(ComputeStage) + stage.pipe = SimpleNamespace(lds_words=128) + stage.exec_known = True + stage.used_v, stage.low16_only_v, stage.lines = set(), set(), [] + stage.pc = 0 + stage.code = struct.pack(' +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; +int wmain(int argc,wchar_t** argv) { + if(argc!=5) return 2; + try { + std::ifstream input(argv[3],std::ios::binary); + if(!input) return 2; + std::string source{std::istreambuf_iterator(input),{}}; + x2w::ShaderDxilCompiler compiler(argv[2]); + auto shader=compiler.compile(source,L"cs_6_0",argv[4]); + ComPtr factory; + ComPtr adapter; + check(CreateDXGIFactory1(IID_PPV_ARGS(&factory)),"factory"); + const bool warp=std::wstring(argv[1])==L"warp"; + if(warp) check(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)),"warp"); + else { + ComPtr candidate; + for(UINT i=0;factory->EnumAdapters1(i,candidate.ReleaseAndGetAddressOf())==S_OK;++i) { + DXGI_ADAPTER_DESC1 description{}; + check(candidate->GetDesc1(&description),"adapter description"); + if(!(description.Flags&DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(),D3D_FEATURE_LEVEL_11_0,__uuidof(ID3D12Device),nullptr))) { + adapter=candidate; + break; + } + } + if(!adapter) { std::puts("no D3D12 hardware adapter"); return 77; } + } + ComPtr device; + check(D3D12CreateDevice(adapter.Get(),D3D_FEATURE_LEVEL_11_0,IID_PPV_ARGS(&device)),"device"); + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_0}; + if(FAILED(device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL,&model,sizeof(model))) || + model.HighestShaderModel serialized; + check(D3D12SerializeRootSignature(&layout,D3D_ROOT_SIGNATURE_VERSION_1,&serialized,nullptr),"serialize"); + ComPtr root; + check(device->CreateRootSignature(0,serialized->GetBufferPointer(),serialized->GetBufferSize(),IID_PPV_ARGS(&root)),"root"); + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature=root.Get(); + desc.CS={shader.dxil.data(),shader.dxil.size()}; + ComPtr pipeline; + check(device->CreateComputePipelineState(&desc,IID_PPV_ARGS(&pipeline)),"pipeline"); + ComputeCommands cmd(device.Get(),pipeline.Get()); + constexpr unsigned words=29; + constexpr size_t bytes=32*words*sizeof(unsigned); + auto output=make_buffer(device.Get(),bytes,D3D12_HEAP_TYPE_DEFAULT,D3D12_RESOURCE_STATE_UNORDERED_ACCESS,D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + auto readback=make_buffer(device.Get(),bytes,D3D12_HEAP_TYPE_READBACK,D3D12_RESOURCE_STATE_COPY_DEST); + cmd.list->SetComputeRootSignature(root.Get()); + cmd.list->SetComputeRootUnorderedAccessView(0,output->GetGPUVirtualAddress()); + cmd.list->Dispatch(1,1,1); + transition(cmd.list.Get(),output.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS,D3D12_RESOURCE_STATE_COPY_SOURCE); + cmd.list->CopyResource(readback.Get(),output.Get()); + cmd.submit_and_wait(device.Get()); + void* data=nullptr; + D3D12_RANGE range{0,bytes}; + check(readback->Map(0,&range,&data),"readback"); + for(unsigned lane=0;lane<32;++lane) { + unsigned other=(lane+1)%32; + auto bits=[](float f){ unsigned u; std::memcpy(&u,&f,sizeof(u)); return u; }; + float a=static_cast(lane+1); + std::array expected{100+other,200+other,300+other,400+other,100,231,500+other,600+other, + 700+other,800+other,900+other,bits(a+2),bits(a-2),bits(2-a),bits(2*a), + lane*3,lane*2,(0x80000000u+lane)-1,lane+11,700+other,800+other,900+other,1000+other, + 303+other,404+other,101+other,202+other,lane+100,99}; + for(unsigned i=0;i(data)[words*lane+i]; + if(actual!=expected[i]) { + std::fprintf(stderr,"lane %u component %u expected %u got %u\n",lane,i,expected[i],actual); + return 1; + } + } + } + D3D12_RANGE empty{}; + readback->Unmap(0,&empty); + std::printf("%u LDS and vector ALU readback words matched\n",32*words); + } catch(const std::exception& e) { + std::fprintf(stderr,"%s\n",e.what()); + return 1; + } +} diff --git a/tests/native_lds_gpu.hlsl b/tests/native_lds_gpu.hlsl new file mode 100644 index 000000000..9ba59ed62 --- /dev/null +++ b/tests/native_lds_gpu.hlsl @@ -0,0 +1,78 @@ +RWByteAddressBuffer output : register(u0); +groupshared uint lds[1024]; + +[numthreads(32,1,1)] +void main(uint lane : SV_GroupIndex) { + uint exec=1, v0=4*lane, v1=100+lane, v2=200+lane, v3=0, v4=0; + uint v5=0, v6=0, v7=0, v8=0; + lds[320+lane]=300+lane; + lds[448+lane]=400+lane; + lds[128+lane]=500+lane; + lds[160+lane]=600+lane; + if(lane==0) { lds[512]=0xffffffff; lds[513]=0; } + GroupMemoryBarrierWithGroupSync(); + // stride-64 write, then atomic min and max on two shared words + #pragma x2w_lds d83c0301 00020100 + v3=2048; + #pragma x2w_lds d81c0000 00000103 + #pragma x2w_lds d8200004 00000203 + v3=4*(640+3*lane); + v5=700+lane; v6=800+lane; v7=900+lane; + #pragma x2w_lds db780000 00000503 + v3=4*(736+4*lane); + v8=1000+lane; + #pragma x2w_lds db7c0000 00000503 + exec=0; + v8=0; + #pragma x2w_lds db7c0000 00000503 + exec=1; + GroupMemoryBarrierWithGroupSync(); + uint other=(lane+1)%32; + uint base=116*lane; + uint wide=736+4*other; + output.Store4(base+76,uint4(lds[wide],lds[wide+1],lds[wide+2],lds[wide+3])); + output.Store2(base,uint2(lds[64+other],lds[192+other])); + v4=4*other; + // The first read overwrites the incoming address register. + #pragma x2w_lds d8e00705 04000004 + output.Store4(base+8,uint4(v4,v5,lds[512],lds[513])); + // One inactive store cannot disturb the initialized value. + exec=0; + #pragma x2w_lds d8340200 00000100 + exec=1; + v6=4*other; + #pragma x2w_lds d8dca080 07000006 + output.Store2(base+24,uint2(v7,v8)); + v4=4*(640+3*other); + #pragma x2w_lds d9d80000 04000004 + output.Store3(base+32,uint3(v4,v5,lds[642+3*other])); + v1=asuint(float(lane+1)); v2=asuint(2.0f); + #pragma x2w_vop2 06060501 + #pragma x2w_vop2 08080501 + #pragma x2w_vop2 0a0a0501 + #pragma x2w_vop2 100c0501 + output.Store4(base+44,uint4(v3,v4,v5,v6)); + v1=0xff000003; v2=0x80000000|lane; + #pragma x2w_vop2 16060501 + #pragma x2w_vop2 340804ff 00000021 + #pragma x2w_vop2 4a0a04c1 + #pragma x2w_vop2 4a0c04ff 8000000b + exec=0; + #pragma x2w_vop2 4a0c0481 + output.Store4(base+60,uint4(v3,v4,v5,v6)); + exec=1; + v0=4*(864+4*lane); + v1=101+lane; v2=202+lane; v5=303+lane; v6=404+lane; + // Each offset is measured in 64-bit elements. Reverse them for the read. + #pragma x2w_lds d9380100 00050100 + v0=4*(864+4*other); + GroupMemoryBarrierWithGroupSync(); + #pragma x2w_lds d9dc0001 00000000 + output.Store4(base+92,uint4(v0,v1,v2,v3)); + // Each lane atomically subtracts from its own word. Alias DATA0 with VDST. + v0=4*(992+lane); + lds[992+lane]=lane+100; + v1=lane+1; + #pragma x2w_lds d8840000 01000100 + output.Store2(base+108,uint2(v1,lds[992+lane])); +} diff --git a/tests/native_lds_request_check.py b/tests/native_lds_request_check.py new file mode 100644 index 000000000..585b93e98 --- /dev/null +++ b/tests/native_lds_request_check.py @@ -0,0 +1,37 @@ +"""Compile a source-built slot 67 request through the LDS replay CLI.""" +from pathlib import Path +import subprocess +import sys +import tempfile + +from startup_compute_translate_check import state_a, write_request +from startup_gfx2hlsl_compute_check import CASES + + +def main(compiler, sdk): + script = Path(__file__).resolve().parents[1] / 'tools/startup/compile_lds_request.py' + _, code, rsrc2, group, _ = CASES['F'] + with tempfile.TemporaryDirectory() as directory: + work = Path(directory) + key = write_request(work, code, state_a(group, rsrc2)) + marker = work / f'req_{key:016x}.c67' + command = [sys.executable, '-B', script, marker, work / 'output', + '--compiler', compiler, '--sdk', sdk, '--cache', work / 'cache', + '--rw-image', '0', '0', '--wave-size', '32'] + subprocess.run(command, check=True) + bundle, = (work / 'output').iterdir() + source = (bundle / f'{key:016x}.cs.hlsl').read_text() + assert '#pragma x2w_lds ' in source and '#pragma x2w_vop2 ' in source + assert 'GroupMemoryBarrierWithGroupSync();' in source + assert (bundle / f'{key:016x}.cs.cso').read_bytes().startswith(b'DXBC') + assert 'group 64 1 1' in (bundle / f'{key:016x}.txt').read_text().splitlines() + + data = marker.with_suffix('.data') + data.write_bytes(bytes(b ^ 1 for b in data.read_bytes())) + refused = subprocess.run(command, capture_output=True, text=True) + assert refused.returncode and 'do not match the key' in refused.stderr, refused.stderr + assert list((work / 'output').iterdir()) == [bundle] + + +if __name__ == '__main__': + main(*sys.argv[1:]) diff --git a/tests/native_mtbuf_check.py b/tests/native_mtbuf_check.py new file mode 100644 index 000000000..8f98e5100 --- /dev/null +++ b/tests/native_mtbuf_check.py @@ -0,0 +1,106 @@ +"""Decode explicit MTBUF formats through the runtime's direct C++ compute backend.""" +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from native_compute_clear_check import write_request +from native_scalar_lds_check import scalar, sop1, vmove + + +# format, channels actually requested, immediate byte displacement (plus group.x) +CASES = [(24, 2, 0), (24, 2, 4), (56, 4, 3), (60, 4, 7), (13, 1, 12), + (71, 4, 12), (75, 4, 4), (2, 1, 7), (12, 1, 7), (25, 2, 3), (24, 2, 8188)] +PACKED = struct.pack("<6I", 0x7fff8000, 0x40008001, 0x007fff81, 0xfc003c00, 0x0001bc00, 0x42987ec5) + + +def program(unsigned): + # Load a raw SRV and UAV from separate table parameters. One writer per group. + words = [sop1(3, 20, 4), sop1(3, 21, 128), sop1(3, 22, 5), sop1(3, 23, 128), + 0xf4080000 | 32 << 6 | 10, 0xfa000020, 0xf4080000 | 36 << 6 | 11, 0xfa000020, + scalar(0x1e, 7, 6, 135), vmove(8, 7), sop1(3, 126, 129)] + pos = 0 + for index, (fmt, channels, disp) in enumerate(CASES): + if unsigned and index == 0: + fmt = 23 + if disp > 4095: + words += [scalar(0, 9, 6, 255), disp, vmove(10, 9)] + disp = 0 + else: + words += [vmove(10, 6)] + words += [0xe8001000 | fmt << 19 | (channels - 1) << 16 | disp, + 0x80080a0a] # v10 is both byte offset and first output + for component in range(channels): + words += [0xe0701000 | 4 * pos, 0x80090008 | (10 + component) << 8] + pos += 1 + return words + [0xbf810000] + + +def fbits(value): + return struct.unpack(" len(data): + result.extend([0] * count) + continue + for c in range(count): + at = disp + group + c * width + v = int.from_bytes(data[at:at + width], "little", signed=fmt in (2, 12, 24)) + if fmt in (13, 71): + v = fbits(struct.unpack_from("> 26 == 0x3a) + for op, error in ((words[insn] | (1 << 13), "without index"), + (0xe8001000 | 24 << 19 | 3 << 16, "absent component")): + bad = words.copy() + bad[insn] = op + marker = write_request(work, bad, root.read_bytes(), sa) + reject = subprocess.run([cli, sdk, work/"cache", "gfx1013-direct-cs@0", marker, work/"bad.cso"], + capture_output=True, text=True) + assert reject.returncode and error in reject.stderr and not (work/"bad.cso").exists(), reject.stderr + print(f"MTBUF matched {2 * len(row)} result words and all guards; changed format, index and component controls passed.") + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/tests/native_pack_b32_f16_check.py b/tests/native_pack_b32_f16_check.py new file mode 100644 index 000000000..efa2e4f8a --- /dev/null +++ b/tests/native_pack_b32_f16_check.py @@ -0,0 +1,210 @@ +"""v_pack_b32_f16 (VOP3 0x311) in the direct C++ DXIL path. + +D[15:0] = S0.f16 and D[31:16] = S1.f16. Per source, op_sel picks the high or low half, abs clears bit 15 of the +half, then neg toggles it. Only integer bit operations are allowed, so signed zero and NaN payloads are kept. +The reference is `ref` of startup_gfx2hlsl_pack_b32_f16_check.py, the model of the Python translator. + + native_pack_b32_f16_check.py ir DUMPER no GPU: build pixel containers, dump the emitted IR with + native_pixel_ir_dump, evaluate it and compare with the model + native_pack_b32_f16_check.py gpu STORE_REPLAY SDK compute readback of the packed bits (exit 77: no adapter) + +Refused forms (explicit diagnostics): clamp, omod, a destination op_sel bit, op_sel[2], abs/neg on source 2, inline +constants and a literal source. +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from native_direct_container_check import patched_pixel +from startup_gfx2hlsl_pack_b32_f16_check import ref +from native_compute_clear_check import write_request +from native_scalar_lds_check import scalar, sop1, vmove + +GROUPS = 2 +WORDS = 2064 +BASE = 8 # words before group 0's results (as in half_mad_readback) +STRIDE = 128 # words per group: 512 bytes, so the 66 results of one group never reach the next +SHIFT = 9 # s_lshl_b32 amount giving the per-group byte base +assert 4 * STRIDE == 1 << SHIFT + +PAIRS = [(0x3c00bc00, 0x80017fff), (0xfc007e00, 0x7d557c01), (0x12345678, 0xffff0001), (0x00008000, 0x80000000)] + + +def pack(dst, s0, s1, opsel=0, absm=0, neg=0, clamp=0, omod=0): + return [0xd7110000 | clamp << 15 | opsel << 11 | absm << 8 | dst, s0 | s1 << 9 | omod << 27 | neg << 29] + + +def mov(reg, value): + return [0x7e0002ff | reg << 17, value] + + +def mov_s(reg, value): + return [0xbe8003ff | reg << 16, value] + + +def container(code, outputs=(4, 5, 6, 7)): + return patched_pixel(len(code), code, export=(0xf800180f, sum(r << 8 * i for i, r in enumerate(outputs)))) + + +def evaluate(ir): + """Evaluate the straight-line integer IR; return the four exported words. Anything else is an error.""" + values, out = {}, {} + + def val(token): + return values[token] if token.startswith('%') else int(token) & 0xffffffff + + for line in ir.splitlines(): + line = line.strip() + m = re.fullmatch(r'(%\w+) = (and|or|xor|shl|lshr|add|sub) i32 (\S+), (\S+)', line) + if m: + a, b = val(m.group(3)), val(m.group(4)) + values[m.group(1)] = {'and': a & b, 'or': a | b, 'xor': a ^ b, 'shl': a << b, 'lshr': a >> b, + 'add': a + b, 'sub': a - b}[m.group(2)] & 0xffffffff + continue + m = re.fullmatch(r'(%\w+) = bitcast i32 (\S+) to float', line) + if m: + values[m.group(1)] = val(m.group(2)) + continue + m = re.fullmatch(r'call void @dx\.op\.storeOutput\.f32\(i32 5, i32 0, i32 0, i8 (\d), float (\S+)\)', line) + if m: + out[int(m.group(1))] = val(m.group(2)) + continue + # Any float operation, conversion call or select would break the bit-exactness requirement. + assert not re.search(r'\b(fadd|fmul|fcmp|fptrunc|fpext|select|legacy|call float)', line), line + return [out[c] for c in range(4)] + + +def dump(dumper, work, code, name='case'): + path = work / (name + '.cdxil') + path.write_bytes(container(code)) + run = subprocess.run([dumper, path], capture_output=True, text=True) + return run + + +def run_ir(dumper): + cases = 0 + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + # Every op_sel x abs x neg form, four value pairs per container (v1/v2 in, v4..v7 out). + for sel in range(4): + for absm in range(4): + for neg in range(4): + code, want = [], [] + for k, (a, b) in enumerate(PAIRS): + code += mov(1, a) + mov(2, b) + pack(4 + k, 257, 258, sel, absm, neg) + want.append(ref(a, b, sel, absm, neg)) + run = dump(dumper, work, code) + assert run.returncode == 0, (sel, absm, neg, run.stderr) + got = evaluate(run.stdout) + assert got == want, (sel, absm, neg, [hex(g) for g in got], [hex(w) for w in want]) + cases += len(want) + # Controls: the order of abs and neg, and the half order, must be observable by this check. + if absm & neg: + assert got != [ref(a, b, sel, absm, neg, neg_first=True) for a, b in PAIRS], (sel, absm, neg) + if sel == 1 and not absm and not neg: + swapped = [(w & 0xffff) << 16 | w >> 16 for w in want] + assert got != swapped + # The issue reproduction: v4 = 0x77883344 and v5 is untouched. Without the pack both are 0x55667788. + issue = [0x7e0802ff, 0x11223344, 0x7e0a02ff, 0x55667788, 0xd7110004, 0x00020b04] + path = work / 'issue.cdxil' + path.write_bytes(patched_pixel(len(issue), issue, export=(0xf800180f, 0x05040504))) + run = subprocess.run([dumper, path], capture_output=True, text=True) + assert run.returncode == 0, run.stderr + assert evaluate(run.stdout) == [0x77883344, 0x55667788, 0x77883344, 0x55667788], run.stdout + control = patched_pixel(4, issue[:4], export=(0xf800180f, 0x05040504)) + path.write_bytes(control) + run = subprocess.run([dumper, path], capture_output=True, text=True) + assert run.returncode == 0 and evaluate(run.stdout) == [0x11223344, 0x55667788] * 2, run.stderr + # Destination overlap, SGPR sources (including a high half) and one source used twice. + a, b = 0x80017e55, 0xfc00bc01 + shapes = [ + (mov(4, a) + mov(5, b) + pack(4, 260, 261, 1, 1, 2), a, b, 1, 1, 2), # dst = src0 + (mov(4, a) + mov(5, b) + pack(5, 260, 261, 2, 0, 1), a, b, 2, 0, 1), # dst = src1 + (mov(4, a) + pack(4, 260, 260, 1, 3, 3), a, a, 1, 3, 3), # one reg twice + (mov_s(5, a) + mov(5, b) + pack(4, 5, 261, 1, 1, 0), a, b, 1, 1, 0), # SGPR src0 + (mov_s(5, b) + mov(4, a) + pack(4, 260, 5, 2, 2, 3), a, b, 2, 2, 3), # SGPR src1 + ] + # The SGPR shapes reuse number 5 for an unrelated VGPR; keep each case independent. + for code, x, y, sel, absm, neg in shapes: + run = dump(dumper, work, sum((mov(r, 0) for r in range(4, 8)), []) + code) + assert run.returncode == 0, (code, run.stderr) + dst = code[-2] & 255 if code[-2] >> 16 == 0xd711 else 4 + assert evaluate(run.stdout)[dst - 4] == ref(x, y, sel, absm, neg), (hex(evaluate(run.stdout)[dst - 4]), code) + cases += 1 + # Unsupported forms are refused with a named diagnostic and no IR. + base = mov(1, a) + mov(2, b) + for words, why in [(pack(4, 257, 258, clamp=1), 'clamp or omod'), (pack(4, 257, 258, omod=1), 'clamp or omod'), + (pack(4, 257, 258, opsel=4), 'destination or third-source'), + (pack(4, 257, 258, opsel=8), 'destination or third-source'), + (pack(4, 257, 258, absm=4), 'destination or third-source'), + (pack(4, 257, 258, neg=4), 'destination or third-source'), + (pack(4, 242, 258), 'constant source'), (pack(4, 129, 258), 'constant source'), + (pack(4, 257, 255) + [0x3c00], 'constant source')]: + run = dump(dumper, work, base + words, 'refused') + assert run.returncode != 0 and 'v_pack_b32_f16' in run.stderr and why in run.stderr, (why, run.stderr) + print('pack_b32_f16 IR: %d results match the model; issue reproduction, control, overlap, SGPR and refusals ' + 'pass; swapped-half and neg-before-abs variants differ from the emitted bits' % cases) + + +def group_offsets(count): + """Word indices written by each workgroup; they must be disjoint and inside the result buffer.""" + offsets = [[BASE + group * STRIDE + i for i in range(count)] for group in range(GROUPS)] + flat = [i for group in offsets for i in group] + assert len(set(flat)) == len(flat), 'two workgroups write the same word' + assert 0 <= min(flat) and max(flat) < WORDS, 'a store falls outside the result buffer' + return offsets + + +def run_gpu(gpu, sdk): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src, root = work / 'root.hlsl', work / 'root.bin' + src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, src], check=True) + sa = struct.pack('<7I', 0, 0, 0, 32 | 1 << 16, 1, 0, 0x80 | 5 << 1) + checked = 0 + for a, b in PAIRS: + # Same preamble as half_mad_readback in native_scalar_lds_check.py: s20:21 table, v8 = group * 512 bytes (STRIDE words). + words = [sop1(3, 20, 4), sop1(3, 21, 128), 0xf408080a, 0xfa000020, + scalar(0x1e, 7, 5, 128 + SHIFT), vmove(8, 7), sop1(3, 126, 129)] + words += mov(1, a) + mov(2, b) + want = [] + for sel in range(4): + for absm in range(4): + for neg in range(4): + # v3 is both the destination and (through the preceding move) a pre-existing value. + words += mov(3, 0x69696969) + pack(3, 257, 258, sel, absm, neg) + words += [0xe0701000 | 4 * len(want), 0x80080308] + want.append(ref(a, b, sel, absm, neg)) + # SGPR source and destination overlapping a source. + words += mov_s(9, a) + pack(3, 9, 258, 1, 1, 1) + [0xe0701000 | 4 * len(want), 0x80080308] + want.append(ref(a, b, 1, 1, 1)) + words += mov(3, a) + pack(3, 259, 258, 2, 2, 1) + [0xe0701000 | 4 * len(want), 0x80080308] + want.append(ref(a, b, 2, 2, 1)) + marker = write_request(work, words + [0xbf810000], root.read_bytes(), sa) + dest = work / 'pack-readback.bin' + run = subprocess.run([gpu, sdk, marker, work / 'cache', '0', dest, '--direct']) + if run.returncode == 77: + sys.exit(77) + run.check_returncode() + offsets = group_offsets(len(want)) + expected = [0x69696969] * WORDS + for group in range(GROUPS): + expected[offsets[group][0]:offsets[group][-1] + 1] = want + actual = struct.unpack('<2064I', dest.read_bytes()) + bad = [(i, hex(x), hex(y)) for i, (x, y) in enumerate(zip(actual, expected)) if x != y][:10] + assert not bad, (hex(a), hex(b), bad) + checked += GROUPS * len(want) + print('pack_b32_f16 GPU: %d packed words matched the model bit for bit' % checked) + + +if __name__ == '__main__': + if len(sys.argv) == 3 and sys.argv[1] == 'ir': + run_ir(sys.argv[2]) + elif len(sys.argv) == 4 and sys.argv[1] == 'gpu': + run_gpu(*sys.argv[2:]) + else: + sys.exit(__doc__) diff --git a/tests/native_pixel_dxil_check.py b/tests/native_pixel_dxil_check.py new file mode 100644 index 000000000..5909e44a1 --- /dev/null +++ b/tests/native_pixel_dxil_check.py @@ -0,0 +1,68 @@ +"""Compare a source-built gfx1013 packet with independently written HLSL.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + + +def main(exe, sdk): + with tempfile.TemporaryDirectory() as folder: + work = Path(folder) + def compile_one(profile, source, output, success=True): + p = subprocess.run([exe, sdk, work/"cache", profile, work/source, work/output], + capture_output=True, text=True) + if (p.returncode == 0) != success: + raise AssertionError((p.stdout, p.stderr)) + return p.stdout if success else p.stderr + + words = [0x7e0002f2,0x7e0202f0,0x7e040280,0x7e0602ff,0x3e800000, + 0xf800180f,0x03020100,0xbf810000] + (work/"pixel.bin").write_bytes(struct.pack("<8I", *words)) + (work/"pixel.hlsl").write_text("float4 main() : SV_Target0 { return float4(1,0.5,0,0.25); }") + mode = "gfx1013-constant-ps" + assert "cold_compile" in compile_one(mode,"pixel.bin","native.cso") + assert "cache_hit" in compile_one(mode,"pixel.bin","warm.cso") + cached, = (work/"cache").glob("*.bin") + damaged = bytearray(cached.read_bytes()) + damaged[-1] ^= 1 + cached.write_bytes(damaged) + assert "cold_compile" in compile_one(mode,"pixel.bin","recovered.cso") + compile_one("ps_6_0","pixel.hlsl","ref.cso") + expected=(work/"ref.cso").read_bytes() + assert all((work/name).read_bytes() == expected for name in ("native.cso","warm.cso","recovered.cso")) + words[2]=0xbf800000 # s_nop is outside the supported instruction family + (work/"pixel.bin").write_bytes(struct.pack("<8I", *words)) + assert "instruction at 8" in compile_one(mode,"pixel.bin","invalid.cso",False) + assert not (work/"invalid.cso").exists() + sources=[work/f"batch{i}.hlsl" for i in range(4)] + for i,path in enumerate(sources): + path.write_text(f"float4 main() : SV_Target0 {{ return {i+1}; }}") + args=[exe,sdk,work/"parallel-cache","--jobs","3","ps_6_0"] + pairs=[str(arg) for path in sources for arg in (path,path.with_suffix(".cso"))] + cold=subprocess.run(args+pairs,capture_output=True,text=True,check=True) + warm=subprocess.run(args+pairs,capture_output=True,text=True,check=True) + assert cold.stdout.count("cold_compile")==4 and warm.stdout.count("cache_hit")==4 + for path in sources: + compile_one("ps_6_0",path.name,"serial.cso") + assert path.with_suffix(".cso").read_bytes()==(work/"serial.cso").read_bytes() + bad=pairs.copy() + bad[-1]=pairs[1].upper() + assert "distinct" in subprocess.run(args+bad,capture_output=True,text=True).stderr + # One failed input keeps its previous output. Other jobs still finish. + previous=sources[0].with_suffix(".cso").read_bytes() + sources[0].write_text("invalid HLSL") + result=subprocess.run(args+pairs,capture_output=True,text=True) + assert result.returncode==1 and "job=1" in result.stderr and result.stdout.count("cache_hit")==3 + assert sources[0].with_suffix(".cso").read_bytes()==previous + for pragma,error in [("x2w_vop2 340804ff","literal length"), + ("x2w_vop2 02060501","unsupported VOP2 opcode"), + ("x2w_vop3 00000000","unknown native compute pragma")]: + (work/"bad-ir.hlsl").write_text(f"#pragma {pragma}\n[numthreads(1,1,1)] void main() {{}}") + assert error in compile_one("cs_6_0","bad-ir.hlsl","invalid-ir.cso",False) + assert not (work/"invalid-ir.cso").exists() + print("native pixel DXIL, independent reference, persistent hit, cache repair and refusal passed") + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/tests/native_pixel_ir_dump.cpp b/tests/native_pixel_ir_dump.cpp new file mode 100644 index 000000000..f09d9a6e9 --- /dev/null +++ b/tests/native_pixel_ir_dump.cpp @@ -0,0 +1,21 @@ +// Print the DXIL-text IR that the direct C++ frontend builds for a pixel container. +// Used by native_pack_b32_f16_check.py to evaluate the emitted operations without a GPU. +// usage: native_pixel_ir_dump CONTAINER (exit 1 and the diagnostic on stderr if refused) +#include "gfx1013_compute_native.h" +#include +#include +#include +#include + +int main(int argc, char **argv) { + if (argc != 2) return 2; + std::ifstream file(argv[1], std::ios::binary); + const std::string bytes((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + try { + std::cout << x2w::translate_graphics_container(bytes, true).dxil_ir; + } catch (const std::exception &error) { + std::cerr << error.what() << "\n"; + return 1; + } + return 0; +} diff --git a/tests/native_recording_check.cpp b/tests/native_recording_check.cpp new file mode 100644 index 000000000..602aba393 --- /dev/null +++ b/tests/native_recording_check.cpp @@ -0,0 +1,228 @@ +#include "startup_stubs/native_recording.h" +#include "native_compute_pipeline.h" +#include "direct_compute_cache.h" +#include "native_graphics_bindings.h" +#include "native_texture_store_view.h" +#include "startup_stubs/native_dispatch_states.h" +#include +#include +#include +#include +#include +#include + +static int graphics_pso(ID3D12Device *device, ID3D12RootSignature *root, D3D12_SHADER_BYTECODE vs, + D3D12_SHADER_BYTECODE gs, D3D12_SHADER_BYTECODE ps) { + D3D12_GRAPHICS_PIPELINE_STATE_DESC p{}; + p.VS = vs; + p.GS = gs; + p.PS = ps; + p.pRootSignature = root; + p.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + p.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + p.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + p.RasterizerState.DepthClipEnable = TRUE; + p.BlendState.RenderTarget[0] = {FALSE, + FALSE, + D3D12_BLEND_ONE, + D3D12_BLEND_ZERO, + D3D12_BLEND_OP_ADD, + D3D12_BLEND_ONE, + D3D12_BLEND_ZERO, + D3D12_BLEND_OP_ADD, + D3D12_LOGIC_OP_NOOP, + D3D12_COLOR_WRITE_ENABLE_ALL}; + p.NumRenderTargets = 1; + p.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + p.SampleDesc.Count = 1; + p.SampleMask = UINT_MAX; + Microsoft::WRL::ComPtr pipeline; + const HRESULT hr = device->CreateGraphicsPipelineState(&p, IID_PPV_ARGS(&pipeline)); + if (FAILED(hr)) { + std::fprintf(stderr, "graphics PSO failed: 0x%08lx\n", static_cast(hr)); + return 10; + } + return 0; +} + +static std::string file_bytes(const std::filesystem::path &path) { + std::ifstream file(path, std::ios::binary); + if (!file) throw std::runtime_error("missing shader fixture"); + return {std::istreambuf_iterator(file), {}}; +} + +static int dispatch_states(ID3D12Device *device) { + using x2w_startup::NativeDispatchStates; + const auto rg = x2w::native_half_store_format(x2w::ComputeViewKind::half2_texture_uav); + if (!rg.accepts(DXGI_FORMAT_R16G16_FLOAT, DXGI_FORMAT_R16G16_TYPELESS) || + !rg.accepts(DXGI_FORMAT_R16G16_FLOAT, DXGI_FORMAT_R16G16_FLOAT) || + rg.accepts(DXGI_FORMAT_R16G16_UNORM, DXGI_FORMAT_R16G16_TYPELESS) || + rg.accepts(DXGI_FORMAT_R16G16_FLOAT, DXGI_FORMAT_R16G16B16A16_TYPELESS)) return 22; + struct View { + Microsoft::WRL::ComPtr resource; + bool write{}; + x2w_startup::NativeTextureWindow texture{}; + struct { bool upload = false; } buffer; + }; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = desc.Height = 8; + desc.DepthOrArraySize = 6; + desc.MipLevels = 3; + desc.Format = DXGI_FORMAT_R32_FLOAT; + desc.SampleDesc.Count = 1; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + Microsoft::WRL::ComPtr texture; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&texture)))) return 15; + // Read mips 0 and 1 on all six faces; write mip 2. Two duplicate SRVs + // exercise the merge. The read-only plan does not expand the face range. + View read{texture, false, {0,2,0,6}}, write{texture, true, {2,1,0,6}}; + NativeDispatchStates reads(std::vector{read, read}); + unsigned whole = 0; + reads.whole_states([&](auto *r, auto state) { + if (r == texture.Get() && state == D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE) ++whole; + }); + if (whole != 1 || !reads.split().empty() || !reads.writes().empty()) return 16; + NativeDispatchStates mixed(std::vector{read, write, read, write}); + if (!mixed.mixed(texture.Get()) || mixed.split().size() != 18 || + mixed.writes().size() != 1 || mixed.writes()[0].UAV.pResource != texture.Get()) return 17; + for (unsigned sub = 0; sub < 18; ++sub) { + const auto &t = mixed.split()[sub].Transition; + if (t.Subresource != sub || t.StateBefore != D3D12_RESOURCE_STATE_COMMON || + t.StateAfter != (sub % 3 == 2 ? D3D12_RESOURCE_STATE_UNORDERED_ACCESS : + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)) return 18; + } + mixed.reverse(); + if (mixed.split()[17].Transition.StateAfter != D3D12_RESOURCE_STATE_COMMON) return 19; + // All mips of faces 0-3 vs all mips of faces 4-5 are adjacent. + read.texture = {0,3,0,4}; + write.texture = {0,3,4,2}; + if (NativeDispatchStates(std::vector{write,read}).split().size() != 18) return 20; + write.texture = {1,1,3,1}; + try { NativeDispatchStates invalid(std::vector{write, read}); } + catch (const std::runtime_error &e) { + if (std::string(e.what()) == "overlapping compute SRV and UAV subresource 10") return 0; + } + return 21; +} + +// Allocation and lifetime smoke. No command list or GPU workload is required. +int wmain(int argc, wchar_t **argv) { + using Microsoft::WRL::ComPtr; + using x2w_startup::NativeRecording; + ComPtr factory; + ComPtr warp; + ComPtr device; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))) || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp))) || + FAILED(D3D12CreateDevice(warp.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) { + std::puts("WARP device unavailable"); + return 77; + } + try { + if (argc == 2 && std::wstring_view(argv[1]) == L"--subresources") + return dispatch_states(device.Get()); + if (argc > 1) { + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_6}; + if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &model, sizeof model)) || + model.HighestShaderModel < D3D_SHADER_MODEL_6_6) + return 77; + } + if (argc == 7 && std::wstring_view(argv[1]) == L"--graphics-sampler") { + const auto a = file_bytes(argv[3]), b = file_bytes(argv[4]), guest_root = file_bytes(argv[5]); + x2w::ShaderDxilCompiler compiler(argv[2]); + for (bool warm : {false, true}) { + bool hit = false; + auto pair = x2w::prepare_direct_graphics(a, b, argv[6], hit, guest_root); + x2w::NativeGraphicsBindings bindings(pair); + auto statics = x2w_startup::decode_statics(bindings.samplers); + if (hit != warm || bindings.srv_count != 2 || bindings.views.size() != 4 || statics.size() != 2 || + bindings.views[2].kind != x2w::ComputeViewKind::half_scalar_uav || bindings.views[2].shader_register != 0 || + bindings.views[2].byte_offset != 64 || bindings.views[3].byte_offset != 32 || + bindings.views[3].shader_register != 1 || + bindings.views[0].kind != x2w::ComputeViewKind::comparison_texture_srv || + statics[0].Filter != D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT || + statics[0].ComparisonFunc != D3D12_COMPARISON_FUNC_LESS || + statics[1].Filter != D3D12_FILTER_MIN_MAG_MIP_POINT) + return 13; + ComPtr root; + if (FAILED(x2w_startup::create_translated_root(device.Get(), 1, bindings.srv_count, bindings.samplers, &root, 2))) + return 8; + auto vs = compiler.compile(pair.vertex.dxil_ir, L"vs_6_6", argv[6], x2w::ShaderSourceFormat::dxil_ir); + auto ps = compiler.compile(pair.pixel.dxil_ir, L"ps_6_6", argv[6], x2w::ShaderSourceFormat::dxil_ir); + if (vs.cache_hit != warm || ps.cache_hit != warm) return 14; + int result = graphics_pso(device.Get(), root.Get(), {vs.dxil.data(), vs.dxil.size()}, {}, + {ps.dxil.data(), ps.dxil.size()}); + if (result) return result; + } + std::puts("WARP created cold and cached graphics pipelines with regular/comparison samples and vertex/pixel UAVs"); + return 0; + } + if (argc == 5 && std::wstring_view(argv[1]) == L"--sampler") { + D3D12_FEATURE_DATA_D3D12_OPTIONS1 options{}; + if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, &options, sizeof options)) || + !options.WaveOps || options.WaveLaneCountMin > 32 || options.WaveLaneCountMax < 32) { + std::printf("compute requires wave32: WaveOps=%u range=%u..%u\n", options.WaveOps, + options.WaveLaneCountMin, options.WaveLaneCountMax); + return 77; + } + x2w::ShaderDxilCompiler compiler(argv[2]); + for (bool warm : {false, true}) { + auto pipeline = x2w::create_native_compute_pipeline(device.Get(), compiler, argv[3], 0, argv[4], true); + if (!pipeline.state || pipeline.frontend_cache_hit != warm || pipeline.cache_hit != warm || + pipeline.srv_count != 2 || pipeline.bindings[0].kind != x2w::ComputeViewKind::comparison_texture_srv) + return 11; + bool hit = false; + const auto shader = x2w::prepare_direct_compute(argv[3], 0, true, argv[4], hit); + if (!hit || shader.samplers.size() != 2 || !shader.samplers[0].comparison || + shader.samplers[1].comparison || shader.samplers[0].words != shader.samplers[1].words) + return 12; + } + std::puts("WARP created cold and cached comparison-sampling compute pipelines"); + return 0; + } + if (argc == 4) { + D3D12_ROOT_SIGNATURE_DESC empty{}; + ComPtr blob; + ComPtr root; + if (FAILED(D3D12SerializeRootSignature(&empty, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr)) || + FAILED(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root)))) + return 8; + const auto vs = file_bytes(argv[1]), gs = file_bytes(argv[2]), ps = file_bytes(argv[3]); + return graphics_pso(device.Get(), root.Get(), {vs.data(), vs.size()}, {gs.data(), gs.size()}, {ps.data(), ps.size()}); + } + if (argc != 1) + return 1; + auto recording = std::make_shared(); + if (recording->allocate(device.Get(), 0).heap) + return 1; + const auto first = recording->allocate(device.Get(), 1); + const UINT page_size = first.heap->GetDesc().NumDescriptors; + const auto rest = recording->allocate(device.Get(), page_size - 1); + if (rest.heap != first.heap || !first.increment || rest.gpu.ptr != first.gpu.ptr + first.increment || + rest.cpu.ptr != first.cpu.ptr + first.increment) + return 2; + const auto next = recording->allocate(device.Get(), 1); + if (next.heap == first.heap) + return 3; + recording->retain(first.heap); + if (recording->objects.size() != 2) + return 4; + + auto submit1 = recording, submit2 = recording; + std::weak_ptr previous = recording; + recording = std::make_shared(); + auto fresh = recording->allocate(device.Get(), 1); + submit1.reset(); + if (fresh.heap == first.heap || first.heap->GetDesc().NumDescriptors != page_size || previous.expired()) + return 5; + submit2.reset(); + if (!previous.expired()) + return 6; + std::puts("WARP descriptor ranges, rollover, reset and repeated submission ownership passed"); + } catch (const std::exception &error) { + std::fprintf(stderr, "%s\n", error.what()); + return 7; + } +} diff --git a/tests/native_rtv_variant_check.py b/tests/native_rtv_variant_check.py new file mode 100644 index 000000000..f1e2c47de --- /dev/null +++ b/tests/native_rtv_variant_check.py @@ -0,0 +1,326 @@ +"""RTV variant requests (req_.rtv) resolved, compiled and cached by compile_dxil --requests (#2980). + +usage: + native_rtv_variant_check.py controls + native_rtv_variant_check.py e2e + +The pair is source-built: the vertex container of native_startup_request_cache_check.py, which covers the viewport +from the vertex index, and a pixel container that moves four literal words into v0..v3 and exports them to MRT0. +A variant request is the ASCII text "rtv1 ...", in a file named by the FNV-1a hash of that text +(tools/startup/gfx2hlsl.py request_source). The reader checks it and the base parts it names, the formats type the +pixel stage's color targets, and the variant is published as .{vs.cso,ps.cso,txt} with the request as +the manifest's last line, which is what the runtime matches. + +controls (no device): +1. One directory holds the base request and four variants of it: R16G16B16A16_UINT, R16G16B16A16_SINT and + R16G16_UINT, each with an R8G8B8A8_UNORM second target, and R32G32B32A32_FLOAT. With an empty compiler cache + the tool compiles all five with four parallel workers; the two UINT variants have the same target types and + share one frontend cache entry. Each variant's manifest is the base manifest plus its request line, the report + names the target types (u32, i32, f32), the compiled pixel stages declare SV_Target0 as uint, int and float, + and the base manifest and stages are those of the base alone. A second run hits the frontend and bytecode + caches for every request and publishes the same bytes. gfx2hlsl.pending_keys then finds nothing left to do. +2. Refusals, each in a fresh directory with only .fail and its reason under the variant key: a forged variant key, base + content that no longer matches the base key, no format, nine formats, a format above 32 bits, a trailing + newline, a missing base, the two integer formats without a verified readback (7 and 8) in the exported slot, + and a forged variant file under the base's own key. Wherever the base request is intact it still compiles. + Format 7 in a slot the pixel stage does not export to is accepted, and refused again when it is moved to the + exported slot although the frontend entry of those target types is then cached. A base with an input layout + publishes its stages without a manifest, as before; its variant is refused for having none, and again when + the layout no longer matches the base key. +3. A published variant whose base then changes is refused on the next run, and every manifest of the directory + is withdrawn. +4. A pixel container whose own output signature says uint: the UINT variant compiles, the FLOAT variant is + refused by name, and the base pair publishes no manifest (as before this change). + +e2e: the consumer creates the pair through device slot 86 and draws one pixel into a target of each format, which +makes the stand-in publish the base request and the three variant requests. The tool compiles the directory with +an empty compiler cache and again with the populated one. The consumer then draws each format in a new process: +the stand-in loads .txt, creates the desktop pipeline with the bound formats and the target is read +back after the fence. Expected, for the exported words ffff7ffe, 15, eb, 68: UINT 16 clamps to ffff 0015 00eb 0068, +SINT 16 clamps to 8000 0015 00eb 0068, FLOAT 32 keeps all four words bit for bit (the first is a NaN with a +payload), and the untyped RGBA8 base draw stores 00000000 over the blue clear. Exit 77 without the adapter. +""" +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +from native_startup_request_cache_check import compile_graphics_table_root, put_graphics_request, stream_vertex_container +from native_direct_container_check import patched_pixel, publish, signature, vertex +from startup_stream_draw_check import vop1 +import gfx2hlsl as G + +WORDS = (0xffff7ffe, 0x15, 0xeb, 0x68) +UINT16, SINT16, FLOAT32, UNORM8, UINT16_RG = 12, 14, 2, 28, 36 +# request formats, report types, SV_Target0 type, MRT0 bytes, bytes of the second (RGBA8, cleared) target +VARIANTS = ( + (UINT16, (UINT16, UNORM8), 'u32,f32', 'uint', 'ffff1500eb006800', '0000ffff'), + (SINT16, (SINT16, UNORM8), 'i32,f32', 'int', '00801500eb006800', '0000ffff'), + (FLOAT32, (FLOAT32,), 'f32', 'float', struct.pack('<4I', *WORDS).hex(), ''), +) + + +def pixel_stage(words=WORDS, parts=()): + prefix = [] + for register, value in enumerate(words): + prefix += [vop1(1, register, 255), value] + return patched_pixel(len(prefix), prefix, export=(0xf800180f, 0x03020100), input_signature=parts) + + +def put_variant(cache, base, formats, name_key=None, text=None): + line = text if text is not None else 'rtv1 ' + ' '.join(map(str, (base, *formats))) + key = G.fnv(line.encode('ascii')) if name_key is None else name_key + (cache / f'req_{key:016x}.rtv').write_bytes(line.encode('ascii')) + return key, line + + +def run_tool(cli, sdk, frontend, cache, jobs=()): + return subprocess.run([cli, sdk, frontend, *jobs, 'gfx1013-container-pair', '--requests', cache, cache], + capture_output=True, text=True) + + +def target_types(sdk, blob): + listing = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', blob], capture_output=True, text=True, check=True).stdout + found = re.findall(r'^\s*;\s+SV_Target\s+(\d+)\s+\S+\s+\d+\s+\S+\s+(float|uint|int)\b', listing, re.M) + assert found, listing[:2000] + return dict(found) + + +def published(cache, key): + return sorted(p.name for p in cache.glob(f'{key:016x}.*')) + + +def only_failure(cache, key, reason): + """A refused request leaves .fail with its reason, and no stage or manifest.""" + assert published(cache, key) == [f'{key:016x}.fail'], published(cache, key) + assert reason in (cache / f'{key:016x}.fail').read_text(encoding='ascii'), (cache / f'{key:016x}.fail').read_text() + + +def check_published(cli, sdk, frontend, cache, base, variants, jobs=(), shared=0): + """variants: (key, line, report types, SV_Target0 type). Cold run, checks, warm run. Returns the cold report. + + shared: how many variants have the target types of another one. Such a pair has one frontend cache entry, so + with parallel jobs the later one may already hit it in the cold run.""" + cold = run_tool(cli, sdk, frontend, cache, jobs) + count = len(variants) + 1 + assert cold.returncode == 0 and f'requests={count} compiled={count} refused=0' in cold.stdout, (cold.stdout, cold.stderr) + # Every pair is linked anew. The stage bytecode cache already hits within this run: the requests share one vertex + # stage, and a pixel stage with float targets is the base's. + assert count - shared <= cold.stdout.count('graphics_pair frontend_cache_hit=0') <= count, cold.stdout + # One vertex stage and one pixel stage per distinct set of target types; parallel workers can compile one twice. + stages = 1 + len({types for _, _, types, _ in variants} | {'f32'}) + compiled = cold.stdout.count('cold_compile_and_publish_ms=') + assert compiled >= stages if jobs else compiled == stages, cold.stdout + base_manifest = (cache / f'{base:016x}.txt').read_text(encoding='ascii') + assert 'rtv1' not in base_manifest and base_manifest.startswith('x2w-manifest 1\n'), base_manifest + assert target_types(sdk, cache / f'{base:016x}.ps.cso') == {'0': 'float'} + for key, line, types, target in variants: + assert published(cache, key) == [f'{key:016x}.ps.cso', f'{key:016x}.txt', f'{key:016x}.vs.cso'], published(cache, key) + manifest = cache / f'{key:016x}.txt' + assert manifest.read_text(encoding='ascii') == base_manifest + line + '\n', manifest.read_text(encoding='ascii') + assert f'rtv_variant {line} types={types}\n' in cold.stdout, cold.stdout + assert target_types(sdk, cache / f'{key:016x}.ps.cso') == {'0': target}, (line, target) + assert manifest.stat().st_mtime_ns >= max((cache / f'{key:016x}{e}').stat().st_mtime_ns for e in ('.vs.cso', '.ps.cso')) + before = {p.name: p.read_bytes() for p in cache.iterdir() if not p.name.startswith('req_')} + warm = run_tool(cli, sdk, frontend, cache, jobs) + assert warm.returncode == 0 and f'requests={count} compiled={count} refused=0' in warm.stdout, (warm.stdout, warm.stderr) + assert warm.stdout.count('graphics_pair frontend_cache_hit=1') == count, warm.stdout + assert warm.stdout.count('cache_hit_ms=') == 2 * count and 'cold_compile_and_publish_ms=' not in warm.stdout, warm.stdout + assert {p.name: p.read_bytes() for p in cache.iterdir() if not p.name.startswith('req_')} == before + assert G.pending_keys(str(cache), skip_failed=False) == [], 'published entries are not recognised as complete' + return cold + + +def check_controls(cli, sdk): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + frontend = work / 'frontend' + root = compile_graphics_table_root(Path(sdk), work) + vs, ps = stream_vertex_container(), pixel_stage() + + cache = work / 'cache' + cache.mkdir() + base = put_graphics_request(cache, vs, ps, root) + variants = [put_variant(cache, base, formats) + (types, target) for _, formats, types, target, _, _ in VARIANTS] + # R16G16_UINT has the target types of the first variant, so the two share a frontend cache entry. Four + # workers compile the five requests side by side. + variants.append(put_variant(cache, base, (UINT16_RG, UNORM8)) + ('u32,f32', 'uint')) + check_published(cli, sdk, frontend, cache, base, variants, jobs=('--jobs', '4'), shared=1) + + # 3. The base changes under a published variant: the next run refuses it and withdraws its manifest. + (cache / f'req_{base:016x}.b').write_bytes(pixel_stage((1, 2, 3, 4))) + stale = run_tool(cli, sdk, frontend, cache) + assert stale.returncode != 0 and 'requests=5 compiled=0 refused=5' in stale.stdout, (stale.stdout, stale.stderr) + assert stale.stderr.count('RTV variant source: graphics request key mismatch') == len(variants), stale.stderr + assert not list(cache.glob('*.txt')), 'a request with a changed base kept a loadable manifest' + + refusals = 0 + + def refuse(label, expected, setup, base_intact=True): + nonlocal refusals + folder = work / label + folder.mkdir() + base_key = put_graphics_request(folder, vs, ps, root) + key = setup(folder, base_key) + result = run_tool(cli, sdk, frontend, folder) + assert result.returncode != 0 and expected in result.stderr, (label, result.returncode, result.stderr) + only_failure(folder, key, expected) + if base_intact: + assert 'compiled=1 refused=1' in result.stdout, (label, result.stdout) + assert (folder / f'{base_key:016x}.txt').is_file(), f'{label}: the base pair no longer compiles' + refusals += 1 + + def remove_base(folder, base_key): + for extension in ('.a', '.b', '.root'): + (folder / f'req_{base_key:016x}{extension}').unlink() + return put_variant(folder, base_key, (UINT16, UNORM8))[0] + + def change_base(folder, base_key): + key = put_variant(folder, base_key, (UINT16, UNORM8))[0] + (folder / f'req_{base_key:016x}.b').write_bytes(pixel_stage((1, 2, 3, 4))) + return key + + invalid = 'invalid RTV variant request' + refuse('forged-key', invalid, + lambda d, b: put_variant(d, b, (UINT16, UNORM8), name_key=G.fnv(f'rtv1 {b} 12 28'.encode()) ^ 1)[0]) + refuse('base-changed', 'RTV variant source: graphics request key mismatch', change_base, base_intact=False) + refuse('no-format', invalid, lambda d, b: put_variant(d, b, ())[0]) + refuse('nine-formats', invalid, lambda d, b: put_variant(d, b, (UNORM8,) * 9)[0]) + refuse('wide-format', 'invalid RTV variant values', lambda d, b: put_variant(d, b, (1 << 32,))[0]) + refuse('trailing-newline', invalid, lambda d, b: put_variant(d, b, (), text=f'rtv1 {b} 12 28\n')[0]) + refuse('missing-base', 'RTV variant source: missing or oversized .a', remove_base, base_intact=False) + refuse('unverified-uint', 'unverified UINT RTV format 7', lambda d, b: put_variant(d, b, (7, UNORM8))[0]) + refuse('unverified-sint', 'unverified SINT RTV format 8', lambda d, b: put_variant(d, b, (8, UNORM8))[0]) + # Both markers under one key are one request, the variant: a forged one refuses that key and nothing else runs + # under it. + refuse('forged-base-key', invalid, lambda d, b: put_variant(d, b, (UINT16, UNORM8), name_key=b)[0], base_intact=False) + + # As in gfx2hlsl.py, an unverified format in a slot the pixel stage does not export to is not refused. The + # frontend entry of these target types is cached by the first request, so the second is refused on a hit. + unwritten = work / 'unwritten' + unwritten.mkdir() + slot_base = put_graphics_request(unwritten, vs, ps, root) + accepted, line = put_variant(unwritten, slot_base, (UINT16, 7)) + result = run_tool(cli, sdk, frontend, unwritten) + assert result.returncode == 0 and f'rtv_variant {line} types=u32,u32\n' in result.stdout, (result.stdout, result.stderr) + assert (unwritten / f'{accepted:016x}.txt').is_file() + (unwritten / f'req_{accepted:016x}.rtv').unlink() + rejected, _ = put_variant(unwritten, slot_base, (7, UINT16)) + result = run_tool(cli, sdk, frontend, unwritten) + assert result.returncode != 0 and 'unverified UINT RTV format 7' in result.stderr, (result.stdout, result.stderr) + only_failure(unwritten, rejected, 'unverified UINT RTV format 7') + refusals += 1 + + # A base with an input layout: the layout is read and checked with the base key, the base publishes its + # stages without a manifest (as before), and its variant is refused because it would have none either. + fetched = work / 'layout' + layout_base = int(publish(fetched, vertex(True), ps, root, b'ia1 1\nposition 0 2 3 4294967295 0 0\n'), 16) + layout_variant, _ = put_variant(fetched, layout_base, (UINT16, UNORM8)) + result = run_tool(cli, sdk, frontend, fetched) + assert result.returncode != 0 and 'requests=2 compiled=1 refused=1' in result.stdout, (result.stdout, result.stderr) + assert 'RTV variant has no runtime manifest' in result.stderr, result.stderr + assert published(fetched, layout_base) == [f'{layout_base:016x}.ps.cso', f'{layout_base:016x}.vs.cso'] + only_failure(fetched, layout_variant, 'RTV variant has no runtime manifest') + (fetched / f'req_{layout_base:016x}.ia').write_bytes(b'ia1 1\nposition 0 2 3 0 0 0\n') + result = run_tool(cli, sdk, frontend, fetched) + assert 'RTV variant source: graphics request key mismatch' in result.stderr, result.stderr + only_failure(fetched, layout_variant, 'RTV variant source: graphics request key mismatch') + refusals += 2 + + # 4. A container whose own signature types the target: the format has to agree with it. + typed = work / 'signature' + typed.mkdir() + uint_ps = pixel_stage(parts=[(b'OSG1', signature(b'SV_Target', system=64, component=1))]) + typed_base = put_graphics_request(typed, vs, uint_ps, root) + agree, _ = put_variant(typed, typed_base, (UINT16, UNORM8)) + disagree, _ = put_variant(typed, typed_base, (FLOAT32,)) + result = run_tool(cli, sdk, frontend, typed) + assert result.returncode != 0 and 'requests=3 compiled=2 refused=1' in result.stdout, (result.stdout, result.stderr) + assert 'RTV variant format disagrees with the pixel signature of target 0' in result.stderr, result.stderr + assert (typed / f'{agree:016x}.txt').is_file() and target_types(sdk, typed / f'{agree:016x}.ps.cso') == {'0': 'uint'} + only_failure(typed, disagree, 'RTV variant format disagrees with the pixel signature of target 0') + assert not (typed / f'{typed_base:016x}.txt').exists(), 'a base pair with an integer target published a manifest' + + print(f'native_rtv_variant controls: the base and 4 variants (uint, int, float SV_Target0) compiled cold and warm ' + f'by 4 workers with identical bytes; {refusals} refusals left only a .fail; a changed base withdrew every manifest; ' + f'a signature that disagrees with the format is refused') + return 0 + + +def check_e2e(cli, consumer, sdk, backend): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + cache = work / 'cache' + cache.mkdir() + vs, ps, root, pixels = (work / name for name in ('vs', 'ps', 'root', 'pixels')) + vs.write_bytes(stream_vertex_container()) + ps.write_bytes(pixel_stage()) + env = dict(os.environ, X2W_D3D12_PERMISSIVE='1', X2W_D3D12_LIST_NOOP='1', X2W_D3D12_RENDER='1', + X2W_D3D12_DEBUG='1', X2W_SHADER_CACHE=str(cache)) + env.pop('X2W_NATIVE_SHADERS', None) + + def draw(fmt=None): + pixels.unlink(missing_ok=True) + result = subprocess.run([consumer, vs, ps, root, backend, pixels] + ([str(fmt)] if fmt else []), + env=env, capture_output=True, text=True) + if result.returncode == 77: + print(result.stdout + result.stderr[-2000:], end='') + print(f'native_rtv_variant e2e: SKIP on {backend}: the adapter is not available') + sys.exit(77) + assert result.returncode == 0, f'consumer exit {result.returncode}\n{result.stderr[-3000:]}' + errors = [line for line in result.stderr.splitlines() if 'x2w-d3d12-debug ' in line and (' sev=0 ' in line or ' sev=1 ' in line)] + assert not errors, errors[0] + return pixels.read_bytes(), result + + # The stand-in publishes the requests: no translation exists, so nothing is drawn. + cleared = {} + for fmt, *_ in VARIANTS: + cleared[fmt], result = draw(fmt) + assert '-> drawn;' not in result.stderr and 'no RTV translation' in result.stderr, result.stderr[-3000:] + print(result.stdout, end='') + base = G.pipeline_key(vs.read_bytes(), ps.read_bytes(), root.read_bytes()) + variants = [] + for fmt, formats, types, target, _, _ in VARIANTS: + line = 'rtv1 ' + ' '.join(map(str, (base, *formats))) + key = G.fnv(line.encode('ascii')) + assert (cache / f'req_{key:016x}.rtv').read_bytes() == line.encode('ascii'), line + variants.append((key, line, types, target)) + assert sorted(p.name for p in cache.iterdir()) == sorted( + [f'req_{base:016x}{e}' for e in ('.a', '.b', '.root')] + [f'req_{key:016x}.rtv' for key, *_ in variants]) + + check_published(cli, sdk, work / 'frontend', cache, base, variants) + + for (fmt, _, _, _, first, second), (key, line, _, _) in zip(VARIANTS, variants): + image, result = draw(fmt) + log = result.stderr + assert image.hex() == first + second, f'format {fmt}: {image.hex()} expected {first + second}\n{log[-3000:]}' + assert image != cleared[fmt], f'format {fmt}: the expected value equals the cleared target' + targets = 2 if second else 1 + assert f'desktop pipeline for {key:016x}, {targets} targets (format {fmt}) -> 0x00000000' in log, log[-3000:] + assert f'pipeline {key:016x} topology 0x4 -> drawn;' in log, log[-3000:] + print(f'{backend} format {fmt} variant {key:016x}: MRT0={first}' + (f' MRT1={second}' if second else '')) + image, result = draw() + assert image == (bytes(4) * 4 + bytes((0, 0, 255, 255)) * 4) * 4, image.hex() + assert f'pipeline {base:016x} topology 0x4 -> drawn;' in result.stderr, result.stderr[-3000:] + layer = [line for line in result.stderr.splitlines() if 'x2w-d3d12 debug layer: ' in line] + assert layer, result.stderr[-3000:] + print('debug layer: ' + ('enabled, no error message' if '0x00000000' in layer[0] else 'unavailable')) + + print(f'native_rtv_variant e2e: PASS on {backend} (3 runtime-published variants of one base compiled cold and warm; ' + f'UINT16, SINT16 and FLOAT32 readbacks match; the base pair draws)') + return 0 + + +def main(argv): + if len(argv) == 3 and argv[0] == 'controls': + return check_controls(*argv[1:]) + if len(argv) == 5 and argv[0] == 'e2e' and argv[4] in ('warp', 'hardware'): + return check_e2e(*argv[1:]) + raise SystemExit(__doc__) + + +if __name__ == '__main__': + raise SystemExit(main(sys.argv[1:])) diff --git a/tests/native_sad_check.py b/tests/native_sad_check.py new file mode 100644 index 000000000..76fcdac13 --- /dev/null +++ b/tests/native_sad_check.py @@ -0,0 +1,136 @@ +"""v_sad_u8, v_sad_hi_u8, v_sad_u16, v_sad_u32 and v_msad_u8 in the direct compute path (#2987). + + native_sad_check.py controls + native_sad_check.py hardware + +Each operation sums unsigned absolute differences of S0 and S1 (four bytes, two halfwords or one dword) and adds +S2, modulo 2^32, as gfx2hlsl.py's sad_u8, sad4_u8, sad_u16 and sad_u32 helpers and tools/pixel_aot.py do. +v_msad_u8 skips each byte whose S1 byte is zero, and v_sad_hi_u8 shifts the byte sum left by 16. All words below +were assembled with LLVM 15.0.7 (clang -cc1as, gfx1013). + +The dispatch has two groups of 32 lanes. With n = lane + 32 * group, S0 = mul_u32_u24(n, 0x050311) ^ 0x80f00a33, +S1 = mul_u32_u24(n, 0x010203) & 0xffff00ff (byte 1 is always zero, byte 0 is zero for n = 0) and +S2 = mul_u32_u24(n, 0x1001). Bytes of S0 below and above those of S1 both occur. Each lane stores the five +results. References with signed byte differences, msad without its mask, sad_hi without its shift and S2 dropped +must each differ from the expected words. +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request + +# s_mov_b32 s20, s4 / s_mov_b32 s21, 0 / s_load_dwordx4 s[32:35], s[20:21], 0x20 / s_lshl_b32 s7, s5, 10 / +# s_lshl_b32 s8, s5, 5 / v_lshlrev_b32 v8, 5, v0 / v_add_nc_u32 v8, s7, v8 / v_add_nc_u32 v9, s8, v0 / +# v_mul_u32_u24 v1, 0x50311, v9 / v_xor_b32 v1, 0x80f00a33, v1 / v_mul_u32_u24 v2, 0x10203, v9 / +# v_and_b32 v2, 0xffff00ff, v2 / v_mul_u32_u24 v3, 0x1001, v9 / v_sad_u8 v10, v_sad_hi_u8 v11, v_sad_u16 v12, +# v_sad_u32 v13, v_msad_u8 v14 (each v1, v2, v3) / s_waitcnt lgkmcnt(0) / buffer_store_dword v10..v14 at +# v8 + 0..16 through s[32:35] / s_endpgm +HEX = ('040394be 800395be 0a0808f4200000fa 058a078f 0585088f 85001034 0710104a 0800124a ff12021611030500 ' + 'ff02023a330af080 ff12041603020100 ff040436ff00ffff ff12061601100000 0a005ad501050e04 0b005bd501050e04 ' + '0c005cd501050e04 0d005dd501050e04 0e0071d501050e04 7fc08cbf 001070e0080a0880 041070e0080b0880 ' + '081070e0080c0880 0c1070e0080d0880 101070e0080e0880 000081bf') +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 +MASK = 0xFFFFFFFF + + +def words(text): + out = [] + for h in text.split(): + out += [int.from_bytes(bytes.fromhex(h[i:i + 8]), 'little') for i in range(0, len(h), 8)] + return out + + +def mul24(x, y): + return ((x & 0xFFFFFF) * (y & 0xFFFFFF)) & MASK + + +def operands(n): + return mul24(n, 0x050311) ^ 0x80F00A33, mul24(n, 0x010203) & 0xFFFF00FF, mul24(n, 0x1001) + + +def parts(x, width): + return [(x >> at) & ((1 << width) - 1) for at in range(0, 32, width)] + + +def signed8(x): + return x - 256 if x & 0x80 else x + + +def results(a, b, c, signed=False, unmasked=False, no_shift=False, no_add=False): + def diff(x, y): + return abs(signed8(x) - signed8(y)) if signed else abs(x - y) + add = 0 if no_add else c + bytes_sum = sum(diff(x, y) for x, y in zip(parts(a, 8), parts(b, 8))) + masked = sum(diff(x, y) for x, y in zip(parts(a, 8), parts(b, 8)) if unmasked or y) + return [(bytes_sum + add) & MASK, + ((bytes_sum << (0 if no_shift else 16)) + add) & MASK, + (sum(abs(x - y) for x, y in zip(parts(a, 16), parts(b, 16))) + add) & MASK, + (abs(a - b) + add) & MASK, + (masked + add) & MASK] + + +def reference(**mutation): + expected = [SENTINEL] * OUTPUT_WORDS + for group in range(2): + for lane in range(32): + base = GUARD_WORDS + (group * 32 + lane) * 8 + expected[base:base + 5] = results(*operands(lane + 32 * group), **mutation) + return expected + + +def controls(cli, sdk, work, root): + marker = request(work, root, words(HEX)) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + # The same v_sad_u8 with a clamp bit is refused, as source and output modifiers are on integer VOP3 here. + clamped = words(HEX) + clamped[clamped.index(0xD55A000A)] |= 0x8000 + marker = request(work, root, clamped) + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, marker.with_suffix('.cso')], + capture_output=True, text=True) + assert result.returncode and 'direct ALU operand modifiers' in result.stderr, (result.stdout, result.stderr) + expected = reference() + a, b, _ = zip(*(operands(n) for n in range(64))) + assert any(x > y for v, w in zip(a, b) for x, y in zip(parts(v, 8), parts(w, 8))) + assert any(x < y for v, w in zip(a, b) for x, y in zip(parts(v, 8), parts(w, 8))) + for label, mutation in (('signed byte differences', {'signed': True}), ('msad without its mask', {'unmasked': True}), + ('sad_hi without its shift', {'no_shift': True}), ('S2 dropped', {'no_add': True})): + assert reference(**mutation) != expected, label + print('compiled; clamp refused; the signed, unmasked, unshifted and S2-dropped references each differ') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, words(HEX)) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = list(struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes())) + expected = reference() + diff = [(i, hex(x), hex(y)) for i, (x, y) in enumerate(zip(actual, expected)) if x != y] + assert not diff, diff[:10] + print('five SAD operations: 320 words of two groups and the guards matched') + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_salu64_check.py b/tests/native_salu64_check.py new file mode 100644 index 000000000..25c52f838 --- /dev/null +++ b/tests/native_salu64_check.py @@ -0,0 +1,119 @@ +"""Direct compute 64-bit SALU readback and EXEC destination refusal.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import scalar, sop1, vmove + + +BFM, CSELECT, CSELECT32, NOT = 0x25, 0x0B, 0x0A, 0x08 +ZERO, ONE, NEG_ONE, LITERAL = 128, 129, 193, 255 +PAIR = (0x89ABCDEF, 0x01234567) +LITERAL_VALUE = 0x80000001 +MASK32 = (1 << 32) - 1 +LANES = 64 +PLANE_BYTES = LANES * 8 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 +SENTINEL = 0x69696969 + + +def set_pair(words): + return [sop1(3, 22, LITERAL), words[0], sop1(3, 23, LITERAL), words[1]] + + +def set_scc(value): + # s_cmp_eq_u32 0, (0 for true, 1 for false) + return 0xBF060080 | (ZERO if value else ONE) << 8 + + +def compute_program(instructions, dst): + # Two 32-lane groups, with 8 bytes per lane and 256 bytes per group in each plane. + program = [sop1(3, 20, 4), sop1(3, 21, ZERO), + 0xF4080000 | 32 << 6 | 10, 0xFA000020, + scalar(0x1E, 7, 5, 136), vop2(0x1A, 8, 131, 0), vop2(0x25, 8, 7, 8)] + program += instructions + # One pair per lane in each of two planes. A ninth plane would set OFFEN + # because the store's immediate offset is only 12 bits. + program += [vmove(2, dst), vmove(3, dst + 1), 0xE0741000, 0x80080208, + scalar(CSELECT32, 26, ONE, ZERO), vmove(2, 26), vmove(3, ZERO), + 0xE0741000 | PLANE_BYTES, 0x80080208, 0xBF810000] + return program + + +def controls(cli, sdk, work, root): + for words, error in (([scalar(CSELECT, 126, NEG_ONE, ZERO), 0xBF810000], "invalid s_cselect_b64 destination"), + ([sop1(NOT, 24, 106), 0xBF810000], "invalid s_not_b64 source")): + marker = request(work, root, words) + output = marker.with_suffix(".cso") + result = subprocess.run([cli, sdk, work / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True) + assert result.returncode and error in result.stderr, (result.stdout, result.stderr) + assert not output.exists(), output + print(error) + return 0 + + +def cases(): + # Manual mutants that must fail: 32-bit s_bfm_b64 with a zero high word, + # zero-extending -1 in s_cselect_b64, and s_not_b64 SCC from the low word only. + for width, offset in ((0, 0), (1, 0), (31, 1), (32, 32), (33, 0), (63, 1), (64, 0)): + bits = ((1 << (width & 63)) - 1) << (offset & 63) + scc = int(bits == 0) + # Use odd SGPR s23 for the width and s22 for the offset in the measured case. + if (width, offset) == (32, 32): + code = [sop1(3, 23, ZERO + width), sop1(3, 22, ZERO + offset), + set_scc(scc), scalar(BFM, 24, 23, 22)] + else: + code = [set_scc(scc), scalar(BFM, 24, ZERO + width, ZERO + offset)] + yield f"bfm {width},{offset}", code, 24, (bits & MASK32, (bits >> 32) & MASK32), scc + + for scc in (0, 1): + yield (f"cselect pair,-1 SCC={scc}", + set_pair(PAIR) + [set_scc(scc), scalar(CSELECT, 24, 22, NEG_ONE)], + 24, PAIR if scc else (MASK32, MASK32), scc) + yield (f"cselect literal,pair SCC={scc}", + set_pair(PAIR) + [set_scc(scc), scalar(CSELECT, 106, LITERAL, 22), LITERAL_VALUE], + 106, (LITERAL_VALUE, 0) if scc else PAIR, scc) + + for source in (PAIR, (0, 0), (MASK32, MASK32), (MASK32, 0)): + words = tuple(word ^ MASK32 for word in source) + scc = int(any(words)) + yield (f"not {source}", set_pair(source) + [set_scc(1 - scc), sop1(NOT, 106, 22)], + 106, words, scc) + + +def hardware(replay, sdk, work, root): + for name, code, dst, words, scc in cases(): + marker = request(work, root, compute_program(code, dst)) + output = work / "out.bin" + result = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + end = GUARD_WORDS + LANES * 4 + assert actual[:GUARD_WORDS] == (SENTINEL,) * GUARD_WORDS, name + assert actual[GUARD_WORDS:end] == words * LANES + (scc, 0) * LANES, (name, words, scc) + assert actual[end:] == (SENTINEL,) * (OUTPUT_WORDS - end), name + print(f"{name}: result words, SCC and guards matched") + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / "root.hlsl" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, shader], check=True) + return {"controls": controls, "hardware": hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_sampled_pixel_gpu.cpp b/tests/native_sampled_pixel_gpu.cpp new file mode 100644 index 000000000..df1f808fd --- /dev/null +++ b/tests/native_sampled_pixel_gpu.cpp @@ -0,0 +1,270 @@ +#include "desktop_gpu.h" +#include "gfx1013_sampled_pixel.h" +#include "gfx1013_vertex_id.h" +#include "shader_dxil_compiler.h" +#include "xmem_test_device.h" +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; +namespace { +using Color=std::array; +constexpr unsigned width=8,height=4; +constexpr Color left{0.125f,1,2,1},right{2,0.5f,1,1}; +constexpr Color first{0.25f,0,0,1},last{4,0,0,1}; +constexpr Color sentinel{8,8,8,8}; +constexpr DXGI_FORMAT formats[]{DXGI_FORMAT_R32G32B32A32_FLOAT,DXGI_FORMAT_R32_FLOAT, + DXGI_FORMAT_R11G11B10_FLOAT,DXGI_FORMAT_R16_FLOAT}; + +// Two independently sampled inputs. Coordinates include a runtime offset. +// Rename registers and use table 0 to exercise decoded operands and bindings. +std::string packet(unsigned color_mask=7, bool implicit=false, unsigned sampler_word2=0) { + std::vector w; + auto emit=[&](std::initializer_list a){w.insert(w.end(),a);}; + auto mov=[&](unsigned d,unsigned s){emit({0xbe800300u|d<<16|s});}; + auto interp=[&](unsigned d,unsigned c){for(unsigned i=0;i<2;++i)emit({0xc8000000u|d<<18|i<<16|c<<8|i});}; + auto sample=[&](unsigned d,unsigned mask,unsigned tex){ + emit({(implicit ? 0xf0800008u : 0xf09c0008u)|mask<<8,6u|d<<8|(tex/4)<<16|(44u/4)<<21}); + }; + auto mix=[&](unsigned d,unsigned src,bool high){ + emit({(high?0xcc224000u:0xcc214000u)|d,0x82000000u|(256+src)<<9|(256+84)}); + }; + mov(20,8);mov(21,128); + emit({0xf4080000u|32u<<6|10,0xfa000060u,0xf4100000u|16u<<6|10,0xfa000020u}); + emit({0xf4240000u|12u<<6|16,0xfa000038u}); // offsets into t0 + emit({0x92800000u|44u<<16|182u<<8|130u}); // s_bfm_b64 s[44:45], 2, 54 + emit({0xbe800400u|46u<<16|255u,sampler_word2}); // s_mov_b64 with a 32-bit literal + mov(124,10);interp(4,0);interp(5,1); + emit({0x06000000u|6u<<17|4u<<9|12u,0x06000000u|7u<<17|5u<<9|13u}); + sample(32,color_mask,16);sample(12,1,24); + // Two VOP3 sources share a single trailing literal. The next dword is an opcode. + emit({0xd54b0000u|84u,255u|(255u<<9)|(128u<<18),0x3f800000u}); + mix(80,32,false);mix(80,33,true);mix(81,34,false);mix(47,12,false); + emit({0xf800040fu,0x80800000u|81u<<8|80u,0xf8001c13u,0x80808000u|47u,0xbf810000u}); + return {reinterpret_cast(w.data()),w.size()*4}; +} + +std::string vertex_packet() { + const auto vop2=[](unsigned op,unsigned dst,unsigned a,unsigned b) { + return op<<25 | dst<<17 | b<<9 | a; + }; + const auto vop1=[](unsigned op,unsigned dst,unsigned src) { + return 0x7e000000u | dst<<17 | op<<9 | src; + }; + const auto args=[](unsigned a,unsigned b,unsigned c){ return a | b<<9 | c<<18; }; + const unsigned words[]{ + vop2(26,7,129,0), vop2(27,6,130,0), vop2(27,7,130,7), + vop1(5,7,263), vop1(5,6,262), vop1(1,10,128), vop1(1,11,242), + 0xd54b0008u,args(244,263,243), 0xd54b0009u,args(245,262,242), + 0xf80008cfu,0x0b0a0908u, 0xf8000203u,0x80800607u, 0xbf810000u + }; + return {reinterpret_cast(words),sizeof(words)}; +} + +void write_fixture(const std::filesystem::path& folder) { + const auto write=[&](const char* name,const std::string& bytes) { + std::ofstream out(folder/name,std::ios::binary); + out.exceptions(std::ios::failbit|std::ios::badbit); + out.write(bytes.data(),bytes.size()); + }; + write("vertex.bin",vertex_packet()); + write("pixel.bin",packet()); + D3D12_DESCRIPTOR_RANGE ranges[2]{}; + D3D12_ROOT_PARAMETER tables[2]{}; + for(unsigned i=0;i<2;++i) { + ranges[i]={D3D12_DESCRIPTOR_RANGE_TYPE_SRV,4,0,i,0}; + tables[i].ParameterType=D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + tables[i].DescriptorTable={1,&ranges[i]}; + } + D3D12_ROOT_SIGNATURE_DESC desc{2,tables,0,nullptr,D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT}; + ComPtr root; + check(D3D12SerializeRootSignature(&desc,D3D_ROOT_SIGNATURE_VERSION_1,&root,nullptr),"fixture root"); + write("root.bin",{static_cast(root->GetBufferPointer()),root->GetBufferSize()}); +} + +ComPtr heap(ID3D12Device* dev,D3D12_DESCRIPTOR_HEAP_TYPE type,unsigned count,bool visible) { + D3D12_DESCRIPTOR_HEAP_DESC d{type,count,visible?D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE:D3D12_DESCRIPTOR_HEAP_FLAG_NONE}; + ComPtr h;check(dev->CreateDescriptorHeap(&d,IID_PPV_ARGS(&h)),"descriptor heap");return h; +} +ComPtr signature(ID3D12Device* dev,bool graphics) { + D3D12_DESCRIPTOR_RANGE ranges[]{{D3D12_DESCRIPTOR_RANGE_TYPE_SRV,graphics?3u:2u,0,0,0}, + {D3D12_DESCRIPTOR_RANGE_TYPE_UAV,1,0,0,2}}; + D3D12_ROOT_PARAMETER p[2]{};p[0].ParameterType=D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + p[0].DescriptorTable={graphics?1u:2u,ranges}; + p[1].ParameterType=D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + p[1].Constants.Num32BitValues=3; + p[1].ShaderVisibility=D3D12_SHADER_VISIBILITY_VERTEX; + D3D12_STATIC_SAMPLER_DESC s{};s.Filter=D3D12_FILTER_MIN_MAG_MIP_POINT; + s.AddressU=s.AddressV=s.AddressW=D3D12_TEXTURE_ADDRESS_MODE_CLAMP;s.MaxLOD=D3D12_FLOAT32_MAX; + s.MaxAnisotropy=1;s.ComparisonFunc=D3D12_COMPARISON_FUNC_ALWAYS; + D3D12_ROOT_SIGNATURE_DESC d{graphics?2u:1u,p,graphics?1u:0u,graphics?&s:nullptr}; + ComPtr blob;check(D3D12SerializeRootSignature(&d,D3D_ROOT_SIGNATURE_VERSION_1,&blob,nullptr),"root serialization"); + ComPtr root; + check(dev->CreateRootSignature(0,blob->GetBufferPointer(),blob->GetBufferSize(),IID_PPV_ARGS(&root)),"root"); + return root; +} + +void run(ID3D12Device* dev,x2w::ShaderDxilCompiler& compiler,const wchar_t* cache, + const std::vector& vs,const std::vector& ps) { + auto graphics=signature(dev,true),compute=signature(dev,false); + auto cs=compiler.compile(R"( +Texture2D a:register(t0);Texture2D b:register(t1);RWByteAddressBuffer dst:register(u0); +[numthreads(8,4,1)]void main(uint3 id:SV_DispatchThreadID){ +dst.Store4(16*(id.y*8+id.x),asuint(float4(a.Load(int3(id.xy,0)),b.Load(int3(id.xy,0)))));})",L"cs_6_0",cache); + D3D12_GRAPHICS_PIPELINE_STATE_DESC g{};g.pRootSignature=graphics.Get(); + g.VS={vs.data(),vs.size()};g.PS={ps.data(),ps.size()};g.SampleMask=UINT_MAX; + g.BlendState.RenderTarget[0].RenderTargetWriteMask=D3D12_COLOR_WRITE_ENABLE_ALL; + g.RasterizerState.FillMode=D3D12_FILL_MODE_SOLID;g.RasterizerState.CullMode=D3D12_CULL_MODE_NONE; + g.RasterizerState.DepthClipEnable=TRUE;g.PrimitiveTopologyType=D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + g.NumRenderTargets=2;g.RTVFormats[0]=formats[2];g.RTVFormats[1]=formats[3];g.SampleDesc.Count=1; + ComPtr gp,cp; + const auto start=std::chrono::steady_clock::now(); + auto hr=dev->CreateGraphicsPipelineState(&g,IID_PPV_ARGS(&gp)); + const auto pso_ms=std::chrono::duration(std::chrono::steady_clock::now()-start).count(); + if(FAILED(hr)){ + ComPtr queue; + if(SUCCEEDED(dev->QueryInterface(IID_PPV_ARGS(&queue)))){ + for(UINT64 i=0;iGetNumStoredMessages();++i){ + SIZE_T size=0;queue->GetMessage(i,nullptr,&size); + std::vector bytes(size); + auto* msg=reinterpret_cast(bytes.data()); + if(SUCCEEDED(queue->GetMessage(i,msg,&size)))std::fprintf(stderr,"%s\n",msg->pDescription); + } + } + } + check(hr,"graphics PSO"); + D3D12_COMPUTE_PIPELINE_STATE_DESC c{};c.pRootSignature=compute.Get();c.CS={cs.dxil.data(),cs.dxil.size()}; + check(dev->CreateComputePipelineState(&c,IID_PPV_ARGS(&cp)),"compute PSO"); + auto rtvs=heap(dev,D3D12_DESCRIPTOR_HEAP_TYPE_RTV,4,false); + auto views=heap(dev,D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,6,true); + auto cpu=[&](ID3D12DescriptorHeap* h,unsigned i){auto v=h->GetCPUDescriptorHandleForHeapStart(); + v.ptr+=SIZE_T(i)*dev->GetDescriptorHandleIncrementSize(h->GetDesc().Type);return v;}; + auto gpu=[&](unsigned i){auto v=views->GetGPUDescriptorHandleForHeapStart(); + v.ptr+=UINT64(i)*dev->GetDescriptorHandleIncrementSize(views->GetDesc().Type);return v;}; + auto constants=make_buffer(dev,64,D3D12_HEAP_TYPE_UPLOAD,D3D12_RESOURCE_STATE_GENERIC_READ); + void* data{};check(constants->Map(0,nullptr,&data),"map offsets");std::memset(data,0,64);constants->Unmap(0,nullptr); + D3D12_SHADER_RESOURCE_VIEW_DESC buf{};buf.Format=DXGI_FORMAT_R32_TYPELESS;buf.ViewDimension=D3D12_SRV_DIMENSION_BUFFER; + buf.Shader4ComponentMapping=D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;buf.Buffer.NumElements=16;buf.Buffer.Flags=D3D12_BUFFER_SRV_FLAG_RAW; + dev->CreateShaderResourceView(constants.Get(),&buf,cpu(views.Get(),0)); + std::array,4> surfaces; + for(unsigned i=0;i<4;++i){ + D3D12_RESOURCE_DESC d{};d.Dimension=D3D12_RESOURCE_DIMENSION_TEXTURE2D;d.Width=i<2?2*width:width; + d.Height=i<2?2*height:height;d.DepthOrArraySize=d.MipLevels=d.SampleDesc.Count=1; + d.Format=formats[i];d.Flags=D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + surfaces[i]=resource(dev,d,D3D12_HEAP_TYPE_DEFAULT,D3D12_RESOURCE_STATE_RENDER_TARGET); + dev->CreateRenderTargetView(surfaces[i].Get(),nullptr,cpu(rtvs.Get(),i)); + dev->CreateShaderResourceView(surfaces[i].Get(),nullptr,cpu(views.Get(),1+i)); + } + constexpr unsigned bytes=width*height*sizeof(Color); + auto dest=make_buffer(dev,bytes,D3D12_HEAP_TYPE_DEFAULT,D3D12_RESOURCE_STATE_UNORDERED_ACCESS,D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + auto readback=make_buffer(dev,bytes,D3D12_HEAP_TYPE_READBACK,D3D12_RESOURCE_STATE_COPY_DEST); + D3D12_UNORDERED_ACCESS_VIEW_DESC u{};u.Format=DXGI_FORMAT_R32_TYPELESS;u.ViewDimension=D3D12_UAV_DIMENSION_BUFFER; + u.Buffer.NumElements=bytes/4;u.Buffer.Flags=D3D12_BUFFER_UAV_FLAG_RAW; + dev->CreateUnorderedAccessView(dest.Get(),nullptr,&u,cpu(views.Get(),5)); + ComputeCommands cmd(dev,gp.Get(),D3D12_COMMAND_LIST_TYPE_DIRECT); + UINT64 frequency=0; + check(cmd.queue->GetTimestampFrequency(&frequency),"timestamp frequency"); + D3D12_QUERY_HEAP_DESC query_desc{D3D12_QUERY_HEAP_TYPE_TIMESTAMP,2,0}; + ComPtr timestamps; + check(dev->CreateQueryHeap(&query_desc,IID_PPV_ARGS(×tamps)),"timestamp heap"); + auto timing=make_buffer(dev,2*sizeof(UINT64),D3D12_HEAP_TYPE_READBACK,D3D12_RESOURCE_STATE_COPY_DEST); + auto* list=cmd.list.Get();ID3D12DescriptorHeap* heaps[]{views.Get()};list->SetDescriptorHeaps(1,heaps); + D3D12_RECT right_half{width,0,2*width,2*height},bottom_half{0,height,2*width,2*height}; + list->ClearRenderTargetView(cpu(rtvs.Get(),0),left.data(),0,nullptr); + list->ClearRenderTargetView(cpu(rtvs.Get(),0),right.data(),1,&right_half); + list->ClearRenderTargetView(cpu(rtvs.Get(),1),first.data(),0,nullptr); + list->ClearRenderTargetView(cpu(rtvs.Get(),1),last.data(),1,&bottom_half); + for(unsigned i=0;i<2;++i){ + transition(list,surfaces[i].Get(),D3D12_RESOURCE_STATE_RENDER_TARGET,D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + list->ClearRenderTargetView(cpu(rtvs.Get(),2+i),sentinel.data(),0,nullptr); + } + const auto targets=cpu(rtvs.Get(),2);list->OMSetRenderTargets(2,&targets,TRUE,nullptr); + D3D12_VIEWPORT viewport{0,0,width,height,0,1};D3D12_RECT scissor{0,0,width-1,height}; + list->RSSetViewports(1,&viewport);list->RSSetScissorRects(1,&scissor);list->SetGraphicsRootSignature(graphics.Get()); + list->SetGraphicsRootDescriptorTable(0,gpu(0));list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->SetGraphicsRoot32BitConstant(1,0,0); + list->EndQuery(timestamps.Get(),D3D12_QUERY_TYPE_TIMESTAMP,0); + list->DrawInstanced(3,1,0,0); + list->EndQuery(timestamps.Get(),D3D12_QUERY_TYPE_TIMESTAMP,1); + list->ResolveQueryData(timestamps.Get(),D3D12_QUERY_TYPE_TIMESTAMP,0,2,timing.Get(),0); + for(unsigned i=2;i<4;++i)transition(list,surfaces[i].Get(),D3D12_RESOURCE_STATE_RENDER_TARGET,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + list->SetPipelineState(cp.Get());list->SetComputeRootSignature(compute.Get());list->SetComputeRootDescriptorTable(0,gpu(3)); + list->Dispatch(1,1,1); + transition(list,dest.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS,D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyResource(readback.Get(),dest.Get());cmd.submit_and_wait(dev); + D3D12_RANGE range{0,bytes};check(readback->Map(0,&range,&data),"map compute result"); + for(unsigned y=0;y(data)[y*width+x]; + if(actual!=expected)throw std::runtime_error("sampled MRT mismatch at "+std::to_string(x)+","+std::to_string(y)); + } + D3D12_RANGE empty{};readback->Unmap(0,&empty); + D3D12_RANGE time_range{0,2*sizeof(UINT64)}; + check(timing->Map(0,&time_range,&data),"read timestamps"); + const auto* ticks=static_cast(data); + if(!frequency || ticks[1]Unmap(0,&empty); +} +} + +int wmain(int argc,wchar_t** argv) { + try { + if(argc==3 && std::wstring_view(argv[1])==L"--write-fixture") { + write_fixture(argv[2]); + return 0; + } + if(argc<4 || argc>6)return 2; + if(GetEnvironmentVariableW(L"X2W_TEST_DEBUG_LAYER",nullptr,0)){ + ComPtr debug; + check(D3D12GetDebugInterface(IID_PPV_ARGS(&debug)),"debug layer");debug->EnableDebugLayer(); + } + bool unmatched=false; + auto device=create_device(std::wstring_view(argv[1])==L"warp",unmatched); + if(!device)return unmatched?1:77; + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_0}; + if(FAILED(device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL,&model,sizeof(model))) || + model.HighestShaderModel(std::istreambuf_iterator(input),{}); + }; + auto pixel=object(4,shader.hlsl,L"ps_6_0"); + auto vertex=object(5,x2w::translate_gfx1013_vertex_id(vertex_packet()),L"vs_6_0"); + run(device.Get(),compiler,argv[3],vertex,pixel); + if(argc==4) { + const auto biased=x2w::translate_gfx1013_sampled_pixel(packet(7,true,0x04003f80)); + if(biased.hlsl.find("-128.0/256.0") == std::string::npos || + biased.bindings.find("sampler 0 0 12582912 67108864 0") == std::string::npos) + throw std::runtime_error("implicit sampler bias or normalized manifest differs"); + run(device.Get(),compiler,argv[3],vertex,compiler.compile(biased.hlsl,L"ps_6_0",argv[3]).dxil); + } + std::puts("112 covered components and 16 uncovered sentinel components matched after compute read"); + } catch(const std::exception& e){std::fprintf(stderr,"%s\n",e.what());return 1;} +} diff --git a/tests/native_sampled_replay_check.py b/tests/native_sampled_replay_check.py new file mode 100644 index 000000000..47f06a5d7 --- /dev/null +++ b/tests/native_sampled_replay_check.py @@ -0,0 +1,50 @@ +"""Replay a source-built VS/PS pair, then damage each published identity in turn.""" +import hashlib +import json +from pathlib import Path +import subprocess +import sys +from tempfile import TemporaryDirectory + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools/startup')) +from compile_sampled_pixel_request import build +from gfx2hlsl import fnv, pipeline_key + + +def main(writer, compiler, sdk): + with TemporaryDirectory() as folder: + work = Path(folder) + subprocess.run([writer, '--write-fixture', work], check=True) + # Device slot order can differ from shader stage order. + stages = [(work / name).read_bytes() for name in ('pixel.bin', 'vertex.bin', 'root.bin')] + base = pipeline_key(*stages) + for ext, data in zip(('.a', '.b', '.root'), stages): + (work / f'req_{base:016x}{ext}').write_bytes(data) + request = f'rtv1 {base} 26 54'.encode() + marker = work / f'req_{fnv(request):016x}.rtv' + marker.write_bytes(request) + args = (marker, work / 'bundles', compiler, sdk, work / 'cache') + output = build(*args) + assert build(*args) == output + meta = json.loads((output / 'replay.json').read_bytes()) + assert meta['pixel_bytes'] == len(stages[0]) and meta['vertex_bytes'] == len(stages[1]) + for name, digest in meta['sha256'].items(): + assert hashlib.sha256((output / name).read_bytes()).hexdigest() == digest + def refuse(message): + try: + build(*args) + except ValueError as exc: + assert message in str(exc), exc + else: + raise AssertionError('accepted damaged replay input') + next(output.glob('*.vs.cso')).write_bytes(b'damaged') + refuse('damaged replay bundle') + (work / f'req_{base:016x}.b').write_bytes(stages[0]) + refuse('key mismatch') + marker.write_bytes(f'rtv1 {base} 54 26'.encode()) + refuse('matching R11G11B10_FLOAT') + print('Matched two-stage cold/warm replay and three refusal controls passed') + + +if __name__ == '__main__': + main(*sys.argv[1:]) diff --git a/tests/native_scalar_lds_check.py b/tests/native_scalar_lds_check.py new file mode 100644 index 000000000..aaa10bf6a --- /dev/null +++ b/tests/native_scalar_lds_check.py @@ -0,0 +1,238 @@ +"""Run the shared C++ direct-DXIL frontend on a source-built scalar/LDS request.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request + + +def scalar(op, dst, a, b): + return 0x80000000 | op << 23 | dst << 16 | b << 8 | a + + +def sop1(op, dst, src): + return 0xbe800000 | dst << 16 | op << 8 | src + + +def vmove(dst, src): + return 0x7e000200 | dst << 17 | src + + +def ds(op, addr, data0=0, data1=0, dst=0, offset=0): + return [0xd8000000 | op << 18 | offset, dst << 24 | data1 << 16 | data0 << 8 | addr] + + +def program(mutant): + # Root table s4, group.x in s5, 64 bytes per group. Keep lane zero active. + words = [sop1(3, 20, 4), sop1(3, 21, 128), 0xf4080000 | 32 << 6 | 10, 0xfa000020, + scalar(0x1e, 7, 5, 134), vmove(8, 7), sop1(3, 126, 129)] + # src = 0x81234567 ^ group.x. High signed/unsigned multiplication and bitset + # must preserve zero SCC. Make both the bit position and destination s11. + words += [scalar(0x12, 16, 5, 255), 0x81234567, 0xbf068180, + scalar(0x36 if mutant else 0x35, 10, 16, 193), vmove(1, 10), + scalar(0x36, 10, 16, 193), vmove(2, 10), + sop1(3, 11, 255), 0x8000001f, sop1(0x1b, 11, 11), vmove(3, 11), + sop1(0x3b, 16, 16), sop1(0x1d, 16, 134), sop1(0x1c, 16, 191), + sop1(0x1e, 16, 190), vmove(4, 16), vmove(5, 17), + # A nonempty mask (7 ones shifted by 3) must preserve SCC=0. + scalar(0x24, 24, 135, 131), vmove(16, 24), + scalar(0x0a, 10, 129, 128), vmove(6, 10), + sop1(0x34, 10, 255), 0x80000000, vmove(7, 10), + scalar(0x0a, 10, 129, 128), vmove(9, 10)] + # Use distinct b64 tuples, reverse offset order on read and alias the + # first result with the read's address. Returning subtract aliases data0. + words += [vmove(10, 128), vmove(11, 129), vmove(12, 130), vmove(13, 131), vmove(14, 132), + *ds(0x4e, 10, 11, 13, offset=0x0301), *ds(0x77, 10, dst=10, offset=0x0103), + vmove(14, 128), vmove(15, 129), *ds(0x21, 14, 15, dst=15, offset=8), 0xbfa3ffe3, + *ds(0x36, 14, dst=14, offset=8)] + for index, vgpr in enumerate([1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 15, 14, 16]): + words += [0xe0701000 | 4 * index, 0x80080008 | vgpr << 8] + return words + [0xbbfd0000, 0xbf8a0000, 0xbf810000] # drain stores, then group barrier + + +def reference(group): + a = 0x81234567 ^ group + replicated = sum(3 << (2 * i) for i in range(32) if a & (1 << i)) + replicated = (replicated | 1 << 6 | 1 << 62) & ~(1 << 63) + return [a * 0xffffffff >> 32, 0, 31, replicated & 0xffffffff, replicated >> 32, + 0, 0x80000000, 1, 3, 4, 1, 2, 1, 0, 127 << 3] + + +def built_root_readback(work, gpu, sdk): + source, root = work / "built.hlsl", work / "built.root" + source.write_text('#define SIG "SRV(t0),DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, source], check=True) + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1, 0, 0x80 | 7 << 1) + for offset in (96, 92): + # Build the byte-address V# in s16:19 from root SRV s4:5. Each + # group selects an aligned index. Group 1 ends at the view limit. + words = [sop1(4, 16, 4), sop1(3, 18, 255), 132, sop1(3, 19, 255), 0x31016fac, + sop1(3, 20, 6), sop1(3, 21, 128), 0xf4080000 | 40 << 6 | 10, 0xfa000020, + scalar(0x1e, 11, 7, 130), scalar(0xe, 11, 11, 132), + 0xf42c0808, 11 << 25 | offset, scalar(0x1e, 12, 7, 133), vmove(8, 12), + sop1(3, 126, 129)] + for j in range(8): + words += [vmove(9, 32 + j), 0xe0701000 | 4 * j, 0x800a0908] + marker = write_request(work, words + [0xbf810000], root.read_bytes(), sa) + dest = work / "built-readback.bin" + subprocess.run([gpu, sdk, marker, work / "cache", "0", dest, "--direct"], check=True) + expected = [0x69696969] * 2064 + for group in range(2): + for j in range(8): + expected[8 + 8 * group + j] = 0x51aa0000 + offset // 4 + group + j + actual = struct.unpack("<2064I", dest.read_bytes()) + assert list(actual) == expected, [(i, a, b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b][:10] + print("Root-built scalar x8 matched 16 words and all guards at each offset; shifting by one dword changed all 16.") + + +def vector_carry_readback(work, gpu, sdk): + def vop2(op, dst, a, b): + return op << 25 | dst << 17 | b << 9 | a + + forms = [(op, wide) for op in (0x128, 0x129, 0x12a) for wide in (False, True)] + forms += [(op, True) for op in (0x30f, 0x310, 0x319)] + full = (1 << 32) - 1 + active = 0xdedebdbd + cin = 0x5a3c96e1 + # Each lane owns 128 bytes. Generate (a,b) of (0,0), (~0,0), + # (0,1), (~0,1) repeating, covering carry on either addition step. + words = [sop1(3, 20, 4), sop1(3, 21, 128), 0xf408080a, 0xfa000020, + scalar(0x1e, 7, 5, 140), vop2(0x1a, 8, 135, 0), vop2(0x25, 8, 7, 8), + vop2(0x1a, 1, 159, 0), vop2(0x18, 1, 159, 1), vop2(0x16, 2, 129, 0), + vop2(0x1b, 2, 129, 2)] + expected = [0x69696969] * 2064 + for idx, (op, wide) in enumerate(forms): + ci = op in (0x128, 0x129, 0x12a) + add = op in (0x128, 0x30f) + reverse = op in (0x12a, 0x319) + mask = 30 if wide else 106 + words += [vmove(10, 257), sop1(3, mask, 255), cin, sop1(3, 126, 255), active] + if wide: + words += [0xd4000000 | op << 16 | mask << 8 | 10, 266 | 258 << 9 | (mask if ci else 0) << 18] + else: + words.append(vop2(op - 0x100, 10, 266, 2)) + words += [sop1(3, 126, 193), vmove(11, mask), 0xe0701000 | 8 * idx, 0x80080a08, + 0xe0701004 | 8 * idx, 0x80080b08] + ballot = 0 + for lane in range(32): + a, b = full * (lane & 1), (lane >> 1) & 1 + bit = int(ci) * ((cin >> lane) & 1) + exact = a + b + bit if add else (b - a if reverse else a - b) - bit + enabled = (active >> lane) & 1 + ballot |= int(enabled and (exact < 0 or exact > full)) << lane + for group in range(2): + pos = 8 + 32 * (group * 32 + lane) + 2 * idx + expected[pos] = exact & full if enabled else a + for lane in range(64): + expected[8 + 32 * lane + 2 * idx + 1] = ballot + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1, 0, 0x80 | 5 << 1) + marker = write_request(work, words + [0xbf810000], (work / "root.bin").read_bytes(), sa) + dest = work / "carry-readback.bin" + subprocess.run([gpu, sdk, marker, work / "cache", "0", dest, "--direct"], check=True) + actual = struct.unpack("<2064I", dest.read_bytes()) + assert list(actual) == expected, [(i, a, b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b][:10] + print("Nine carry/borrow encodings matched 1152 result and ballot words plus all guards.") + + +def half_mad_readback(work, gpu, sdk): + words = [sop1(3, 20, 4), sop1(3, 21, 128), 0xf408080a, 0xfa000020, + scalar(0x1e, 7, 5, 136), vmove(8, 7), sop1(3, 126, 129)] + a, b = 0x80007fff, 0xfffe0003 + words += [vmove(1, 255), a, vmove(2, 255), b] + values = [] + for signed in (False, True): + for addend in (0x80000010, 0x7ffffff0, 0xfffffffe): + for clamp in (False, True): + for halves in range(4): + # Alias the dword addend and the result VGPR. + inst = 0xd4000000 | (0x375 if signed else 0x373) << 16 | clamp << 15 | halves << 11 | 3 + offset = 4 * len(values) + words += [vmove(3, 255), addend, inst, 257 | 258 << 9 | 259 << 18, + 0xe0701000 | offset, 0x80080308] + x = (a >> (16 * (halves & 1))) & 65535 + y = (b >> (16 * (halves >> 1))) & 65535 + z = addend + if signed: + x -= (x >> 15) << 16 + y -= (y >> 15) << 16 + z -= (z >> 31) << 32 + exact = x * y + z + if clamp: + low, high = (-2**31, 2**31-1) if signed else (0, 2**32-1) + exact = min(high, max(low, exact)) + values.append(exact & 0xffffffff) + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1, 0, 0x80 | 5 << 1) + marker = write_request(work, words + [0xbf810000], (work / "root.bin").read_bytes(), sa) + dest = work / "half-mad-readback.bin" + subprocess.run([gpu, sdk, marker, work / "cache", "0", dest, "--direct"], check=True) + expected = [0x69696969] * 2064 + for group in range(2): + start = 8 + group * 64 + expected[start:start + len(values)] = values + actual = struct.unpack("<2064I", dest.read_bytes()) + assert list(actual) == expected, [(i, a, b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b][:10] + print("Halfword MAD matched 96 signed/unsigned results across half-selects, wrap, saturation and aliasing.") + + +def descriptor_scc_readback(work, gpu, sdk): + # Use the table only as provenance for s[16:19]. Its guest address bits + # are unavailable in the shader. OOB_SELECT=3 always sets SCC, whereas + # the masked address's SCC must be dead at SAVEEXEC. + words = [sop1(3, 20, 4), sop1(3, 21, 128), + 0xf408040a, 0xfa000000, 0xf408080a, 0xfa000020, + scalar(0x1e, 7, 5, 132), vmove(8, 7), + scalar(0xe, 23, 19, 255), 0xcfffffff, 0xbf068180, + scalar(0x10, 23, 23, 255), 0x30000000, sop1(3, 25, 253), + scalar(0xe, 17, 17, 255), 0xc000ffff, sop1(0x3c, 24, 5), + sop1(3, 26, 253), sop1(3, 126, 129), + vmove(9, 25), vmove(10, 26), 0xe0701000, 0x80080908, 0xe0701004, 0x80080a08, + # -0 has class bit 5. BYTE_3 selects this bit only in group 1, + # BYTE_0 selects it in both. Only lane zero contributes. + scalar(0x1e, 11, 5, 157), scalar(0x10, 11, 11, 160), vmove(5, 11), + 0x7d100af9, 0x03968e80, vmove(9, 14), 0xe0701008, 0x80080908, + 0x7d100af9, 0x00968e80, vmove(9, 14), 0xe070100c, 0x80080908, + 0xbf810000] + marker = write_request(work, words, (work / "root.bin").read_bytes(), + struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1, 0, 0x80 | 5 << 1)) + dest = work / "descriptor-scc.bin" + subprocess.run([gpu, sdk, marker, work / "cache", "0", dest, "--direct"], check=True) + expected = [0x69696969] * 2064 + expected[8:12] = [1, 0, 0, 1] + expected[12:16] = [1, 1, 1, 1] + actual = struct.unpack("<2064I", dest.read_bytes()) + assert list(actual) == expected, [(i, a, b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b][:10] + print("Descriptor OOB OR / SAVEEXEC SCC and both -0 SDWA class-mask selections matched eight words and all guards.") + + +def main(gpu, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + src, root = work / "root.hlsl", work / "root.bin" + src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, src], check=True) + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1, 0, 0x808a) + expected = [0x69696969] * 2064 + for group in range(2): + start = 8 + 16 * group + expected[start:start + 15] = reference(group) + for mutant in (False, True): + marker = write_request(work, program(mutant), root.read_bytes(), sa) + dest = work / "result.bin" + result = subprocess.run([gpu, sdk, marker, work / "cache", "0", dest, "--direct"]) + if result.returncode == 77: + sys.exit(77) + result.check_returncode() + actual = struct.unpack("<2064I", dest.read_bytes()) + mismatches = [i for i, (a, b) in enumerate(zip(actual, expected)) if a != b] + assert mismatches == ([8, 24] if mutant else []), [(i, actual[i], expected[i]) for i in mismatches[:10]] + print("Two direct-DXIL workgroups matched 30 result words and all guards; the signed-multiply control differed twice.") + built_root_readback(work, gpu, sdk) + vector_carry_readback(work, gpu, sdk) + half_mad_readback(work, gpu, sdk) + descriptor_scc_readback(work, gpu, sdk) + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/tests/native_sdwa_f16_check.py b/tests/native_sdwa_f16_check.py new file mode 100644 index 000000000..db233531b --- /dev/null +++ b/tests/native_sdwa_f16_check.py @@ -0,0 +1,152 @@ +"""Direct compute SDWA binary16 arithmetic. Use ir DUMPER or gpu STORE_REPLAY SDK.""" +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +import f16_packed_model as model +import native_f16_alu_check as fixture +from native_compute_clear_check import write_request + +BYTE_1, WORD_0, WORD_1, DWORD = 1, 4, 5, 6 +PAD, SEXT, PRESERVE = 0, 1, 2 +NEG, ABS, SCALAR = 0x10, 0x20, 0x80 +OLD = 0xa55a1357 +GUARD = 0x69696969 + + +def sdwa(opcode, dst, unused, src0, src1, reg0=1, reg1=2, dst_mod=0): + ext = (reg0 | (dst << 8) | (unused << 11) | dst_mod | + (src0 << 16) | (src1 << 24)) + return fixture.vop2(opcode, 3, 249, reg1) + [ext] + + +class Case: + dest = 3 + + def __init__(self, op, a, b, dst, unused, src0, src1): + self.op, self.a, self.b = op, a, b + self.dst, self.unused = dst, unused + self.src0, self.src1 = src0, src1 + self.shift = 16 if dst == WORD_1 else 0 + self.mask = 0xffff << self.shift + self.want = self.expected(src0, src1, unused) + + def expected(self, src0, src1, unused): + def read(value, control): + picked = model.pick(value, (control & 7) == WORD_1) + return fixture.modified(picked, bool(control & ABS), bool(control & NEG), 0) + + result = fixture.binary16(self.op, read(self.a, src0), read(self.b, src1)) + other = OLD & ~self.mask if unused == PRESERVE else 0 + return (result << self.shift) | other + + def emit(self): + return (fixture.mov(1, self.a) + fixture.mov(2, self.b) + fixture.mov(self.dest, OLD) + + sdwa(fixture.OP_CODE[self.op], self.dst, self.unused, self.src0, self.src1)) + + def matches(self, got): + return (got & ~self.mask == self.want & ~self.mask and + fixture.same_half((got & self.mask) >> self.shift, (self.want & self.mask) >> self.shift)) + + +def cases(): + shapes = [ + (0x3c004400, 0x45004000, WORD_0, PRESERVE, WORD_1, DWORD), + (0x44004200, 0x45003c00, WORD_0, PAD, DWORD, WORD_0), + (0x4400bc00, 0x40004500, WORD_1, PRESERVE, WORD_0 | ABS | NEG, WORD_1), + ] + items = [Case(op, *shape) for shape in shapes for op in fixture.OPS] + items += [ + Case('add', 0x3c014400, 0x45001000, WORD_0, PRESERVE, WORD_1, DWORD), + Case('mul', 0x44000003, 0x45003800, WORD_0, PAD, DWORD, WORD_0), + Case('mul', 0x44007bff, 0x40004500, WORD_1, PAD, WORD_0, WORD_1), + Case('add', 0x7e014400, 0x45003c00, WORD_0, PRESERVE, WORD_1, DWORD), + # neg on one source and abs on the other: -(1.0) + |-2.0| = 1.0; dropping either modifier changes the sum. + Case('add', 0x44003c00, 0xc0004500, WORD_1, PAD, WORD_0 | NEG, WORD_1 | ABS), + ] + assert len(items) < fixture.STRIDE + return items + + +def check_mutants(items): + # Manual lowering mutants that must fail: swap WORD_0/WORD_1 on either + # source, or ignore UNUSED_PRESERVE by zeroing the other destination half. + def swap(control): + return control ^ 1 if (control & 7) in (WORD_0, WORD_1) else control + + assert any(not case.matches(case.expected(swap(case.src0), case.src1, case.unused)) for case in items) + assert any(not case.matches(case.expected(case.src0, swap(case.src1), case.unused)) for case in items) + assert any(not case.matches(case.expected(case.src0, case.src1, PAD)) for case in items) + + +def refusals(): + add = fixture.OP_CODE['add'] + dest_error = 'unsupported SDWA destination modifier' + src_error = 'invalid SDWA source modifier' + vgpr_error = 'SDWA binary16 source must be a VGPR' + return [ + (sdwa(add, DWORD, PAD, WORD_0, WORD_0), dest_error), + (sdwa(add, WORD_0, PAD, BYTE_1, WORD_0), src_error), + (sdwa(add, WORD_0, PAD, WORD_0 | SCALAR, WORD_0), vgpr_error), + (sdwa(add, WORD_0, PAD, WORD_0, WORD_0 | SCALAR, reg1=242), vgpr_error), + (sdwa(add, WORD_0, PAD, WORD_0, WORD_0 | 8), src_error), + (sdwa(add, WORD_0, SEXT, WORD_0, WORD_0), dest_error), + (sdwa(add, WORD_0, PAD, WORD_0, WORD_0, dst_mod=1 << 13), dest_error), + (sdwa(add, WORD_0, PAD, WORD_0, WORD_0, dst_mod=1 << 14), dest_error), + (sdwa(0x39, WORD_0, PAD, WORD_0, WORD_0), 'unimplemented direct SDWA operand profile'), # max + (sdwa(0x3a, WORD_0, PAD, WORD_0, WORD_0), 'unimplemented direct SDWA operand profile'), # min + ] + + +def run_ir(dumper, items, code): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = fixture.dump(dumper, work, code, 'sdwa-f16') + assert run.returncode == 0, run.stderr + stores = sorted(fixture.interpret(run.stdout)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(items))] + for (addr, got), case in zip(stores, items): + assert case.matches(got), (addr, case.op, hex(got), hex(case.want)) + for index, (instruction, why) in enumerate(refusals()): + run = fixture.dump(dumper, work, instruction + [0xbf810000], 'refused-%d' % index) + assert run.returncode != 0 and why in run.stderr, (why, run.returncode, run.stderr) + print('native_sdwa_f16 IR: %d results and %d refusals' % (len(items), len(refusals()))) + + +def run_gpu(gpu, sdk, items, code): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src, root = work / 'root.hlsl', work / 'root.bin' + src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([str(Path(sdk) / 'dxc.exe'), '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, src], check=True) + sa = struct.pack('<7I', 0, 0, 0, 32 | (1 << 16), 1, 0, 0x80 | (5 << 1)) + marker = write_request(work, code, root.read_bytes(), sa) + dest = work / 'sdwa-f16-readback.bin' + run = subprocess.run([gpu, sdk, str(marker), str(work / 'cache'), '0', str(dest), '--direct']) + if run.returncode == 77: + sys.exit(77) + run.check_returncode() + offsets = fixture.group_offsets(len(items)) + stores = {slot: case for group in offsets for slot, case in zip(group, items)} + actual = struct.unpack(f'<{fixture.WORDS}I', dest.read_bytes()) + for index, got in enumerate(actual): + if index in stores: + case = stores[index] + assert case.matches(got), (index, case.op, hex(got), hex(case.want)) + else: + assert got == GUARD, (index, hex(got), hex(GUARD)) + print('native_sdwa_f16 GPU: %d results and %d guards' % (len(stores), fixture.WORDS - len(stores))) + + +if __name__ == '__main__': + items = cases() + check_mutants(items) + code, _ = fixture.program(items) + if len(sys.argv) == 3 and sys.argv[1] == 'ir': + run_ir(sys.argv[2], items, code) + elif len(sys.argv) == 4 and sys.argv[1] == 'gpu': + run_gpu(sys.argv[2], sys.argv[3], items, code) + else: + sys.exit(__doc__) diff --git a/tests/native_shift64_check.py b/tests/native_shift64_check.py new file mode 100644 index 000000000..5fd0eacde --- /dev/null +++ b/tests/native_shift64_check.py @@ -0,0 +1,104 @@ +"""Direct compute logical 64-bit shift readback and inline-float refusal.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import scalar, sop1 + + +AMOUNTS = (0, 1, 31, 32, 33, 63) +SGPR_LOW, SGPR_HIGH = 0x89ABCDEF, 0x01234567 +LITERAL = 0x80000001 +SOURCES = ( + ("inline -1", 193, -1), + ("inline -16", 208, -16), + ("inline 64", 192, 64), + ("inline 1", 129, 1), + ("literal", 255, LITERAL), + ("SGPR pair", 22, (SGPR_HIGH << 32) | SGPR_LOW), +) +SHIFTS = (("right", 0xD7000002), ("left", 0xD6FF0002)) +MASK64 = (1 << 64) - 1 +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +LANES = 64 +OUTPUT_WORDS = 2064 + + +def compute_program(amount, sources=SOURCES): + # Use the quad fixture's descriptor setup and group index. v8 holds the + # byte offset of a lane's two words within a plane of 64 result pairs: 8 bytes per lane, 256 per group. + program = [sop1(3, 20, 4), sop1(3, 21, 128), + 0xF4080000 | 32 << 6 | 10, 0xFA000020, + scalar(0x1e, 7, 5, 136), vop2(0x1a, 8, 131, 0), vop2(0x25, 8, 7, 8), + sop1(3, 22, 255), SGPR_LOW, sop1(3, 23, 255), SGPR_HIGH] + # Replay's UAV view already starts after the leading guard words. + offset = 0 + for _, source, _ in sources: + for _, opcode in SHIFTS: + program += [opcode, (128 + amount) | (source << 9)] + if source == 255: + program.append(LITERAL) + # buffer_store_dwordx2 v[2:3], v8, s[32:35], 0 offen + program += [0xE0741000 | offset, 0x80080208] + offset += LANES * 8 + return program + [0xBF810000] + + +def controls(cli, sdk, work, root): + marker = request(work, root, compute_program(1, (("inline float", 242, None),))) + output = marker.with_suffix(".cso") + result = subprocess.run([cli, sdk, work / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True) + error = "direct 64-bit shift operand" + assert result.returncode and error in result.stderr, (result.stdout, result.stderr) + assert not output.exists(), output + print(error) + return 0 + + +def hardware(replay, sdk, work, root): + # Manual mutants that must fail: zero-extend the negative inline values, + # sign-extend the literal, or swap the SGPR pair's words. + # One source per dispatch: the store's immediate offset is 12 bits. All twelve planes in one dispatch + # would not fit: the ninth starts at 4096, which is the OFFEN bit. + for amount in AMOUNTS: + for source in SOURCES: + marker = request(work, root, compute_program(amount, (source,))) + output = work / "out.bin" + result = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + assert actual[:GUARD_WORDS] == (SENTINEL,) * GUARD_WORDS + start = GUARD_WORDS + name, _, value = source + bits = value & MASK64 + for (direction, _), expected in zip(SHIFTS, (bits >> amount, (bits << amount) & MASK64)): + words = (expected & 0xFFFFFFFF, expected >> 32) + end = start + LANES * 2 + assert actual[start:end] == words * LANES, (name, direction, amount, words, actual[start:end]) + start = end + assert actual[start:] == (SENTINEL,) * (OUTPUT_WORDS - start) + print(f"Shift by {amount}: all 6 sources, both directions and guards matched") + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / "root.hlsl" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, shader], check=True) + return {"controls": controls, "hardware": hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_signed_forms_check.py b/tests/native_signed_forms_check.py new file mode 100644 index 000000000..2f5f53b75 --- /dev/null +++ b/tests/native_signed_forms_check.py @@ -0,0 +1,167 @@ +"""v_ashrrev_i64 and v_mad_i32_i24 in the direct compute path (#2991). + + native_signed_forms_check.py controls + native_signed_forms_check.py hardware + +v_ashrrev_i64 shifts the 64-bit value S1 right arithmetically by S0[5:0]. Its shifted-value rules are those of the +logical 64-bit shifts (tests/native_shift64_check.py), with one difference that gfx2hlsl.py's +i64_words(signed=True) makes: a 32-bit literal is sign-extended, not zero-extended. v_mad_i32_i24 is +sext(S0[23:0]) * sext(S1[23:0]) + S2 modulo 2^32. All words were assembled with LLVM 15.0.7 (clang -cc1as, gfx1013). + +The shift dispatches reuse native_shift64_check.compute_program with the VOP3 opcode of v_ashrrev_i64 (0x301), a +negative SGPR pair (0x89abcdef:01234567), inline -1, -16, 64 and 1 and the literal 0x80000001, for shift amounts +0, 1, 31, 32, 33 and 63. Zero-extended-literal and logical-shift references must differ from the expected words. +The multiply-add dispatch uses, with n = lane + 32 * group, S0 = mul_u32_u24(n, 0x05f3d1) ^ 0xa5800000, +S1 = mul_u32_u24(n, 0x0371) ^ 0x7f9abcde and S2 = mul_u32_u24(n, 0x1001), so bit 23 is set in many factors and +bits above it are not zero. Unsigned and unmasked references must differ. +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +import native_shift64_check as S64 +from native_dpp_quad_check import request + +S64.SHIFTS = (('arithmetic', 0xD7010002),) # v_ashrrev_i64 v[2:3], amount, source +S64.SGPR_LOW, S64.SGPR_HIGH = 0x01234567, 0x89ABCDEF +SOURCES = ( + ('inline -1', 193, -1), + ('inline -16', 208, -16), + ('inline 64', 192, 64), + ('inline 1', 129, 1), + ('literal', 255, 0x80000001), + ('SGPR pair', 22, (0x89ABCDEF << 32) | 0x01234567), +) +AMOUNTS = (0, 1, 31, 32, 33, 63) +MASK64 = (1 << 64) - 1 +# s_mov_b32 s20, s4 / s_mov_b32 s21, 0 / s_load_dwordx4 s[32:35], s[20:21], 0x20 / s_lshl_b32 s7, s5, 9 / +# s_lshl_b32 s8, s5, 5 / v_lshlrev_b32 v8, 4, v0 / v_add_nc_u32 v8, s7, v8 / v_add_nc_u32 v9, s8, v0 / +# v_mul_u32_u24 v1, 0x5f3d1, v9 / v_xor_b32 v1, 0xa5800000, v1 / v_mul_u32_u24 v2, 0x371, v9 / +# v_xor_b32 v2, 0x7f9abcde, v2 / v_mul_u32_u24 v3, 0x1001, v9 / v_mad_i32_i24 v4, v1, v2, v3 / +# s_waitcnt lgkmcnt(0) / buffer_store_dword v4, v8, s[32:35], 0 offen / s_endpgm +MAD = ('040394be 800395be 0a0808f4200000fa 0589078f 0585088f 84001034 0710104a 0800124a ff120216d1f30500 ' + 'ff02023a000080a5 ff12041671030000 ff04043adebc9a7f ff12061601100000 040042d501050e04 7fc08cbf ' + '001070e008040880 000081bf') +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 + + +def words(text): + out = [] + for h in text.split(): + out += [int.from_bytes(bytes.fromhex(h[i:i + 8]), 'little') for i in range(0, len(h), 8)] + return out + + +def shifted(source, amount, zero_extend_literal=False, logical=False): + name, _, value = source + if name == 'literal' and not zero_extend_literal: + value = value - (1 << 32) if value & 0x80000000 else value + bits = value & MASK64 + signed = bits - (1 << 64) if bits >> 63 else bits + return (bits >> amount if logical else signed >> amount) & MASK64 + + +def mul24(x, y): + return ((x & 0xFFFFFF) * (y & 0xFFFFFF)) & 0xFFFFFFFF + + +def sext24(x): + x &= 0xFFFFFF + return x - (1 << 24) if x & 0x800000 else x + + +def mad_reference(unsigned=False, unmasked=False): + expected = [SENTINEL] * OUTPUT_WORDS + for group in range(2): + for lane in range(32): + n = lane + 32 * group + a, b, c = mul24(n, 0x05F3D1) ^ 0xA5800000, mul24(n, 0x0371) ^ 0x7F9ABCDE, mul24(n, 0x1001) + if unmasked: + x, y = a, b + elif unsigned: + x, y = a & 0xFFFFFF, b & 0xFFFFFF + else: + x, y = sext24(a), sext24(b) + expected[GUARD_WORDS + (group * 32 + lane) * 4] = (x * y + c) & 0xFFFFFFFF + return expected + + +def compile_ok(cli, sdk, work, root, program): + marker = request(work, root, program) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + return subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, + check=True).stdout + + +def controls(cli, sdk, work, root): + # The modules, before the GPU run: an arithmetic 64-bit shift (no logical one), and for the multiply-add a + # 24-bit sign extension of each factor, a shift left by 8 followed by an arithmetic shift right by 8. + for source in SOURCES: + dump = compile_ok(cli, sdk, work, root, S64.compute_program(1, (source,))) + assert 'ashr i64' in dump and 'lshr i64 %' in dump and dump.count('ashr i64') == 1, (source[0], dump) + dump = compile_ok(cli, sdk, work, root, words(MAD)) + assert dump.count(', 8') >= 4 and 'ashr i32' in dump and 'mul i32' in dump, dump + changed = {label: any(shifted(s, k, **kw) != shifted(s, k) for s in SOURCES for k in AMOUNTS) + for label, kw in (('zero-extended literal', {'zero_extend_literal': True}), + ('logical shift', {'logical': True}))} + assert all(changed.values()), changed + for label, mutant in (('unsigned factors', mad_reference(unsigned=True)), + ('factors not masked to 24 bits', mad_reference(unmasked=True))): + assert mutant != mad_reference(), label + print('compiled six v_ashrrev_i64 sources and v_mad_i32_i24; the zero-extended-literal, logical, unsigned ' + 'and unmasked references each differ') + return 0 + + +def readback(replay, sdk, work, root, program): + marker = request(work, root, program) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return None + result.check_returncode() + return list(struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes())) + + +def hardware(replay, sdk, work, root): + for amount in AMOUNTS: + for source in SOURCES: + actual = readback(replay, sdk, work, root, S64.compute_program(amount, (source,))) + if actual is None: + return 77 + expected = shifted(source, amount) + words_ = (expected & 0xFFFFFFFF, expected >> 32) + start = GUARD_WORDS + end = start + S64.LANES * 2 + assert actual[:start] == [SENTINEL] * start + assert actual[start:end] == list(words_) * S64.LANES, (source[0], amount, words_, actual[start:end][:4]) + assert actual[end:] == [SENTINEL] * (OUTPUT_WORDS - end) + print(f'v_ashrrev_i64 by {amount}: all 6 sources and guards matched') + actual = readback(replay, sdk, work, root, words(MAD)) + if actual is None: + return 77 + diff = [(i, hex(x), hex(y)) for i, (x, y) in enumerate(zip(actual, mad_reference())) if x != y] + assert not diff, diff[:10] + print('v_mad_i32_i24: 64 words of two groups and the guards matched') + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_startup_request_cache_check.py b/tests/native_startup_request_cache_check.py new file mode 100644 index 000000000..f6154395b --- /dev/null +++ b/tests/native_startup_request_cache_check.py @@ -0,0 +1,443 @@ +"""Startup request consumption and runtime cache publication for compile_dxil (#2933). + +usage: + native_startup_request_cache_check.py controls + native_startup_request_cache_check.py e2e +""" +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +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 +from native_direct_container_check import patched_pixel, vertex as container_vertex # noqa: E402 +from startup_compute_request_check import DATA, STATE_B, prepare # noqa: E402 +from startup_compute_translate_check import state_a # noqa: E402 +from startup_image_3d_check import root_blob as graphics_const_root_blob # noqa: E402 + +TARGET_MASKS = (0x8002, 0x8003) # PERSP_SAMPLE allocated (v0..v1), PERSP_CENTER (v2..v3), POS_FIXED_PT (v4) +DECOY_MASKS = (0x8002, 0x8002) # PERSP_CENTER (v0..v1), POS_FIXED_PT (v2) +COMPUTE_GROUP = (2, 3, 4) +COMPUTE_RSRC2 = C.USER7 | C.TGID_X | C.TGID_Y | C.TGID_Z | C.tidig(3) + + +def fullscreen_vs_words() -> bytes: + vop1 = lambda op, dst, src: 0x7E000000 | dst << 17 | op << 9 | src + vop2 = lambda op, dst, src0, vsrc1: op << 25 | dst << 17 | vsrc1 << 9 | src0 + words = [vop2(0x1A, 1, 129, 0), vop2(0x1B, 1, 130, 1), vop2(0x1B, 2, 130, 0)] + for v in (1, 2): + words.extend([vop1(6, v, 256 + v), vop2(8, v, 244, v), vop2(3, v, 243, v)]) + words.extend([vop1(1, 3, 128), vop1(1, 4, 242), 0xF80008CF, 0x04030201, 0xBF810000]) + return struct.pack(f"<{len(words)}I", *words) + + +VS_WORDS = fullscreen_vs_words() + + +def stream_vertex_container() -> bytes: + words = list(struct.unpack(f"<{len(VS_WORDS) // 4}I", VS_WORDS)) + return container_vertex(program=words) + + +def stream_pixel_container(green: bool) -> bytes: + vop1 = lambda op, dst, src: 0x7E000000 | dst << 17 | op << 9 | src + prefix = [vop1(1, 0, 128), vop1(1, 1, 242)] + channels = 0x01000100 if green else 0x01000001 + return patched_pixel(where=len(prefix), prefix=prefix, export=(0xF800180F, channels)) + + +def ps_words(reg: int) -> bytes: + return struct.pack("<3I", 0xF800180F, reg * 0x01010101, 0xBF810000) + + +def compile_graphics_table_root(sdk: Path, work: Path) -> bytes: + hlsl = work / "graphics_table_root.hlsl" + out = work / "graphics_table_root.bin" + hlsl.write_text('#define RS "DescriptorTable(SRV(t0))"\n', encoding="ascii") + subprocess.run([sdk / "dxc.exe", "-T", "rootsig_1_1", "-E", "RS", "-Fo", out, hlsl], check=True) + return out.read_bytes() + + +def describe_psin(key: int, masks: tuple[int, int]) -> str: + return f"psin1 {key:016x} ena=0x{masks[0]:04x} addr=0x{masks[1]:04x}\n" + + +def put_graphics_request(cache: Path, vs: bytes, ps: bytes, root: bytes, + masks: tuple[int, int] | None = None, + psin_text: str | None = None, + override_key: int | None = None) -> int: + key = G.pipeline_key(vs, ps, root, ps_inputs=masks) if override_key is None else override_key + stem = cache / f"req_{key:016x}" + for ext, blob in ((".b", ps), (".root", root), (".a", vs)): + stem.with_suffix(ext).write_bytes(blob) + text = psin_text if psin_text is not None else (describe_psin(key, masks) if masks is not None else None) + if text is not None: + stem.with_suffix(".psin").write_bytes(text.encode("ascii")) + return key + + +def compute_program_words() -> bytes: + # Same arithmetic and buffer load/store body as Case A (2x3x4 group, 3x2x2 groups), + # reading the placed input SRV from table 1 byte 64 and the placed output UAV from table 1 byte 32. + loads = struct.pack( + "<6I", + 0xBE8A0306, # s_mov_b32 s10, s6 + 0xBE8B0380, # s_mov_b32 s11, 0 + 0xF4080305, 0xFA000040, # s_load_dwordx4 s[12:15], s[10:11], 0x40 + 0xF4080405, 0xFA000020, # s_load_dwordx4 s[16:19], s[10:11], 0x20 + ) + return loads + C.WORDS_A[16:] + + +def compile_compute_root(sdk: Path, work: Path) -> bytes: + hlsl = work / "compute_root.hlsl" + out = work / "compute_root.bin" + hlsl.write_text( + '#define RS "RootConstants(num32BitConstants=2, b0), ' + 'DescriptorTable(SRV(t0, numDescriptors=4), UAV(u0, numDescriptors=4, offset=0))"\n', + encoding="ascii", + ) + subprocess.run([sdk / "dxc.exe", "-T", "rootsig_1_1", "-E", "RS", "-Fo", out, hlsl], check=True) + return out.read_bytes() + + +def put_compute_request(cache: Path, code: bytes, root: bytes, sa: bytes, + override_key: int | None = None) -> int: + desc = struct.pack("<12Q", 0, 0, len(sa), 0, len(STATE_B), 0, len(code), 0, len(DATA), 0, 0, 11) + key = G.compute_key(code, DATA, root, desc, sa, STATE_B) if override_key is None else override_key + for ext, part in ((".desc", desc), (".sa", sa), (".sb", STATE_B), (".data", DATA), (".root", root), (".c67", code)): + (cache / f"req_{key:016x}{ext}").write_bytes(part) + return key + + +def check_controls(cli: Path, sdk: Path) -> int: + repo = HERE.parent + reader_text = (repo / "src" / "shader_compute_request.cpp").read_text(encoding="utf-8") + runtime_text = (repo / "src" / "startup_stubs" / "d3d12_draw.inl").read_text(encoding="utf-8") + reader_revs = re.findall(r'constexpr char revision\[\] = "(x2w-startup-shader-\d+(?:cs)?)";', reader_text) + runtime_gfx = re.search(r'constexpr char revision\[\] = "(x2w-startup-shader-\d+)";', runtime_text) + runtime_cs = re.search(r'constexpr char compute_revision\[\] = "(x2w-startup-shader-\d+cs)";', runtime_text) + assert runtime_gfx and runtime_cs and reader_revs == [runtime_gfx.group(1), runtime_cs.group(1)], ( + reader_revs, runtime_gfx and runtime_gfx.group(1), runtime_cs and runtime_cs.group(1) + ) + + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + frontend = work / "frontend" + g_root = compile_graphics_table_root(sdk, work) + g_const_root = graphics_const_root_blob() + c_root = compile_compute_root(sdk, work) + c_code = compute_program_words() + c_sa = state_a(COMPUTE_GROUP, COMPUTE_RSRC2) + + # 1. Valid graphics (.psin) and compute (.c67) startup requests publish runtime cache entries in place. + cache = work / "cache" + cache.mkdir() + target_key = put_graphics_request(cache, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + decoy_key = put_graphics_request(cache, VS_WORDS, ps_words(2), g_const_root, DECOY_MASKS) + cs_key = put_compute_request(cache, c_code, c_root, c_sa) + + g_run = subprocess.run( + [cli, sdk, frontend, "--jobs", "2", "gfx1013-container-pair", "--requests", cache, cache], + capture_output=True, text=True, + ) + assert g_run.returncode == 0, (g_run.stdout, g_run.stderr) + assert "requests=2 compiled=2 refused=0" in g_run.stdout, g_run.stdout + + c_run = subprocess.run( + [cli, sdk, frontend, "gfx1013-direct-cs@0", "--requests", cache, cache], + capture_output=True, text=True, + ) + assert c_run.returncode == 0, (c_run.stdout, c_run.stderr) + assert "requests=1 compiled=1 refused=0" in c_run.stdout, c_run.stdout + + for key, masks, expected_ud in ( + (target_key, TARGET_MASKS, "x2w-manifest 1\nud 1\nudsrc 0 rect\n"), + (decoy_key, DECOY_MASKS, "x2w-manifest 1\nud 1\nudsrc 0 rootconst 1 0\n"), + ): + vs_cso = cache / f"{key:016x}.vs.cso" + ps_cso = cache / f"{key:016x}.ps.cso" + psdep = cache / f"{key:016x}.psdep" + manifest = cache / f"{key:016x}.txt" + assert vs_cso.read_bytes().startswith(b"DXBC") + assert ps_cso.read_bytes().startswith(b"DXBC") + assert psdep.read_text(encoding="ascii") == describe_psin(key, masks) + assert manifest.read_text(encoding="ascii").startswith(expected_ud), manifest.read_text(encoding="ascii") + assert manifest.stat().st_mtime_ns >= max(vs_cso.stat().st_mtime_ns, ps_cso.stat().st_mtime_ns) + assert not (cache / f"req_{key:016x}.vs.cso").exists() + assert not (cache / f"req_{key:016x}.ps.cso").exists() + + cs_cso = cache / f"{cs_key:016x}.cs.cso" + cs_manifest = cache / f"{cs_key:016x}.txt" + assert cs_cso.read_bytes().startswith(b"DXBC") + assert cs_manifest.stat().st_mtime_ns >= cs_cso.stat().st_mtime_ns + assert not (cache / f"req_{cs_key:016x}.cso").exists() + assert cs_manifest.read_text(encoding="ascii") == ( + "x2w-manifest 2\n" + "stage cs\n" + "group 2 3 4\n" + "ud 2\n" + "udsrc 0 rootconst 0 0\n" + "udsrc 1 rootconst 0 1\n" + "srv 0 buf table 1 64\n" + "uav 0 table 1 32\n" + ) + assert G.pending_keys(str(cache), skip_failed=False) == [], "published entries not recognised as complete" + + archive = work / "archive" + archive.mkdir() + ps = ps_words(4) + legacy_graphics_key = G.fnv(b"x2w-startup-shader-28") + for part in (VS_WORDS, ps, g_root, b"psin1" + struct.pack(".txt. + (cache / f"req_{target_key:016x}.b").write_bytes(ps_words(2)) + stale_run = subprocess.run( + [cli, sdk, frontend, "gfx1013-container-pair", "--requests", cache, cache], + capture_output=True, text=True, + ) + assert stale_run.returncode != 0 and "stale pixel input description" in stale_run.stderr, stale_run.stderr + assert not (cache / f"{target_key:016x}.txt").exists(), "stale .psin kept a loadable manifest" + assert (cache / f"{decoy_key:016x}.txt").is_file(), "unrelated valid entry was disturbed" + + # 3. Fresh-directory negative controls: mismatched keys and malformed/stale/contradictory .psin files. + def expect_graphics_refusal(label: str, setup, expected_stderr: str) -> None: + case_dir = work / label + case_dir.mkdir() + bad_key = setup(case_dir) + res = subprocess.run( + [cli, sdk, frontend, "gfx1013-container-pair", "--requests", case_dir, case_dir], + capture_output=True, text=True, + ) + assert res.returncode != 0 and expected_stderr in res.stderr, (label, res.returncode, res.stderr) + assert not list(case_dir.glob("*.txt")), (label, list(case_dir.iterdir())) + assert not (case_dir / f"{bad_key:016x}.vs.cso").exists(), label + assert not (case_dir / f"{bad_key:016x}.ps.cso").exists(), label + + expect_graphics_refusal( + "graphics-key-mismatch", + lambda d: put_graphics_request(d, VS_WORDS, ps_words(0), g_root, override_key=0x0123456789ABCDEF), + "graphics request key mismatch", + ) + expect_graphics_refusal( + "psin-other-pipeline", + lambda d: put_graphics_request( + d, VS_WORDS, ps_words(4), g_root, TARGET_MASKS, psin_text=describe_psin(decoy_key, DECOY_MASKS) + ), + "pixel input description names another pipeline", + ) + expect_graphics_refusal( + "psin-missing-addr", + lambda d: ( + lambda k: put_graphics_request(d, VS_WORDS, ps_words(4), g_root, psin_text=f"psin1 {k:016x} ena=0x8002\n", override_key=k) + )(G.pipeline_key(VS_WORDS, ps_words(4), g_root, ps_inputs=TARGET_MASKS)), + "pixel input address mask missing from the stream description", + ) + expect_graphics_refusal( + "psin-missing-ena", + lambda d: ( + lambda k: put_graphics_request(d, VS_WORDS, ps_words(4), g_root, psin_text=f"psin1 {k:016x} addr=0x8003\n", override_key=k) + )(G.pipeline_key(VS_WORDS, ps_words(4), g_root, ps_inputs=TARGET_MASKS)), + "pixel input enable mask missing from the stream description", + ) + expect_graphics_refusal( + "psin-contradictory", + lambda d: ( + lambda k: put_graphics_request( + d, VS_WORDS, ps_words(4), g_root, psin_text=f"psin1 {k:016x} ena=0x8003 addr=0x8002\n", override_key=k + ) + )(G.pipeline_key(VS_WORDS, ps_words(4), g_root, ps_inputs=(0x8003, 0x8002))), + "contradictory pixel input enable/address masks", + ) + expect_graphics_refusal( + "psin-malformed", + lambda d: ( + lambda k: put_graphics_request( + d, VS_WORDS, ps_words(4), g_root, psin_text=f"psin1 {k:016x} ena=8002 addr=8003\n", override_key=k + ) + )(G.pipeline_key(VS_WORDS, ps_words(4), g_root, ps_inputs=TARGET_MASKS)), + "invalid pixel input description", + ) + expect_graphics_refusal( + "psin-allocated-disabled", + lambda d: put_graphics_request(d, VS_WORDS, ps_words(2), g_root, (0x0002, 0x8002)), + "unsupported pixel entry VGPR 2", + ) + + bad_cs_dir = work / "compute-key-mismatch" + bad_cs_dir.mkdir() + bad_cs_key = put_compute_request(bad_cs_dir, c_code, c_root, c_sa, override_key=cs_key ^ 1) + bad_cs_run = subprocess.run( + [cli, sdk, frontend, "gfx1013-direct-cs@0", "--requests", bad_cs_dir, bad_cs_dir], + capture_output=True, text=True, + ) + assert bad_cs_run.returncode != 0 and "compute request key mismatch" in bad_cs_run.stderr, bad_cs_run.stderr + assert not (bad_cs_dir / f"{bad_cs_key:016x}.txt").exists() + assert not (bad_cs_dir / f"{bad_cs_key:016x}.cs.cso").exists() + + print("native_startup_request_cache controls: current and archived graphics (.psin) + compute (.c67) cache entries and 8 refusal controls passed") + return 0 + + +def check_e2e(cli: Path, consumer: Path, offscreen: Path, sdk: Path, backend: str) -> int: + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + frontend = work / "frontend" + + # Part 1: .psin VS/PS requests compiled by compile_dxil --requests and executed on GPU. + psin_cache = work / "psin_cache" + psin_cache.mkdir() + g_root = compile_graphics_table_root(sdk, work) + target_key = put_graphics_request(psin_cache, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + decoy_key = put_graphics_request(psin_cache, VS_WORDS, ps_words(2), g_root, DECOY_MASKS) + wrong_key = put_graphics_request(psin_cache, VS_WORDS, ps_words(2), g_root, (0x8003, 0x8003)) + subprocess.run( + [cli, sdk, frontend, "--jobs", "3", "gfx1013-container-pair", "--requests", psin_cache, psin_cache], + check=True, capture_output=True, text=True, + ) + for label, key, should_match in (("target-v4", target_key, True), ("decoy-v2", decoy_key, True), ("wrong-v2", wrong_key, False)): + vs_cso = psin_cache / f"{key:016x}.vs.cso" + ps_cso = psin_cache / f"{key:016x}.ps.cso" + draw_res = subprocess.run( + [offscreen, backend, "--startup-packed-position", vs_cso, ps_cso], + capture_output=True, text=True, + ) + if draw_res.returncode == 77: + print(draw_res.stdout + draw_res.stderr, end="") + return 77 + if should_match: + assert draw_res.returncode == 0 and "all 91 packed positions matched" in draw_res.stdout, ( + label, draw_res.stdout, draw_res.stderr + ) + else: + assert draw_res.returncode != 0, f"{label} negative control unexpectedly matched" + + # Part 2: Runtime-published graphics request -> compile_dxil --requests -> runtime cache loader draw. + draw_dir = work / "runtime_draw" + draw_cache = draw_dir / "cache" + draw_cache.mkdir(parents=True) + vs_path, ps_path, root_path, pixels_path = (draw_dir / n for n in ("vs", "ps", "root", "pixels")) + vs_path.write_bytes(stream_vertex_container()) + draw_env = dict( + os.environ, + X2W_D3D12_PERMISSIVE="1", + X2W_D3D12_LIST_NOOP="1", + X2W_D3D12_RENDER="1", + X2W_D3D12_DEBUG="1", + X2W_SHADER_CACHE=str(draw_cache), + ) + drawn_images = [] + for green in (False, True): + ps_path.write_bytes(stream_pixel_container(green)) + subprocess.run([consumer, vs_path, ps_path, root_path], env=draw_env, check=True, capture_output=True, text=True) + subprocess.run( + [cli, sdk, frontend, "gfx1013-container-pair", "--requests", draw_cache, draw_cache], + check=True, capture_output=True, text=True, + ) + res = subprocess.run([consumer, vs_path, ps_path, root_path, backend, pixels_path], + env=draw_env, capture_output=True, text=True) + if res.returncode == 77: + print(res.stdout + res.stderr, end="") + return 77 + assert res.returncode == 0 and "-> drawn;" in res.stderr, (res.returncode, res.stderr[-2000:]) + debug_errors = [ln for ln in res.stderr.splitlines() if "x2w-d3d12-debug " in ln and (" sev=0 " in ln or " sev=1 " in ln)] + assert not debug_errors, debug_errors[0] + color = bytes((0, 255, 0, 255) if green else (255, 0, 0, 255)) + clear = bytes((0, 0, 255, 255)) + expected_pixels = (color * 4 + clear * 4) * 4 + actual_pixels = pixels_path.read_bytes() + assert actual_pixels == expected_pixels, (actual_pixels.hex(), expected_pixels.hex()) + drawn_images.append(actual_pixels) + assert sum(drawn_images[0][i:i + 4] != drawn_images[1][i:i + 4] for i in range(0, 128, 4)) == 16 + + # Part 3: Runtime-published .c67 compute request -> compile_dxil --requests -> runtime cache loader dispatch. + cs_dir = work / "runtime_compute" + cs_cache, cs_env = prepare(cs_dir) + cs_env.update(X2W_D3D12_LIST_NOOP="1", X2W_D3D12_DEBUG="1" if backend == "hardware" else "0") + if backend == "hardware": + cs_env["X2W_TEST_DISPATCH_HARDWARE"] = "1" + else: + cs_env.pop("X2W_TEST_DISPATCH_HARDWARE", None) + c_root = compile_compute_root(sdk, work) + (cs_dir / "compute_root").write_bytes(c_root) + cs_env["X2W_TEST_COMPUTE_ROOT"] = str(cs_dir / "compute_root") + c_code = compute_program_words() + c_sa = state_a(COMPUTE_GROUP, COMPUTE_RSRC2) + (cs_dir / "program").write_bytes(c_code) + (cs_dir / "data").write_bytes(DATA) + (cs_dir / "state").write_bytes(c_sa) + out_bin = cs_dir / "out.bin" + + def run_dispatch() -> tuple[list[int], subprocess.CompletedProcess[str]]: + out_bin.unlink(missing_ok=True) + args = [consumer, cs_dir / "vertex", cs_dir / "pixel", cs_dir / "root", "slot67", + cs_dir / "program", cs_dir / "data", cs_dir / "state", "dispatch-heap"] + res = subprocess.run(args, env=dict(cs_env, X2W_TEST_DISPATCH_OUT=str(out_bin)), capture_output=True, text=True) + if res.returncode == 77: + print(res.stdout + res.stderr, end="") + sys.exit(77) + assert res.returncode == 0, (res.returncode, res.stderr[-2500:]) + return list(struct.unpack(f"<{C.WORDS}I", out_bin.read_bytes())), res + + before_words, before_res = run_dispatch() + assert before_words == [C.SENTINEL] * C.WORDS, "dispatch ran before compile_dxil published cache entry" + assert "Dispatch(3, 2, 2) refused: no translation" in before_res.stderr, before_res.stderr[-2000:] + + subprocess.run( + [cli, sdk, frontend, "gfx1013-direct-cs@0", "--requests", cs_cache, cs_cache], + check=True, capture_output=True, text=True, + ) + assert G.pending_keys(str(cs_cache), skip_failed=False) == [] + + after_words, after_res = run_dispatch() + if backend == "hardware" or "Dispatch(3, 2, 2) translated:" in after_res.stderr: + debug_errors = [ + ln for ln in after_res.stderr.splitlines() if "x2w-d3d12-debug " in ln and (" sev=0 " in ln or " sev=1 " in ln) + ] + assert not debug_errors, debug_errors[0] + assert "Dispatch(3, 2, 2) translated:" in after_res.stderr, after_res.stderr[-2000:] + assert after_words == C.expected("A"), "compute dispatch output mismatch" + else: + # Wave-4 WARP builds validate the manifest, load .cs.cso, build tr.root, and stop at [WaveSize(32)] PSO creation. + assert "not translated: pipeline creation failed" in after_res.stderr, after_res.stderr[-2000:] + + print(f"native_startup_request_cache e2e: PASS on {backend} (.psin 91-pixel draws, runtime graphics cache draw, runtime .c67 compute dispatch of {C.WORDS} words)") + return 0 + + +def main(argv: list[str]) -> int: + if len(argv) == 3 and argv[0] == "controls": + return check_controls(Path(argv[1]), Path(argv[2])) + if len(argv) == 6 and argv[0] == "e2e" and argv[5] in ("warp", "hardware"): + return check_e2e(Path(argv[1]), Path(argv[2]), Path(argv[3]), Path(argv[4]), argv[5]) + raise SystemExit(__doc__) + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/tests/native_store_replay.cpp b/tests/native_store_replay.cpp new file mode 100644 index 000000000..31fa15b31 --- /dev/null +++ b/tests/native_store_replay.cpp @@ -0,0 +1,195 @@ +#include "desktop_gpu.h" +#include "native_buffer_store_view.h" +#include "native_compute_pipeline.h" +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; +namespace fs = std::filesystem; +using namespace x2w; +namespace { +constexpr UINT elements = 2048, guard = 8; +struct Window { + ComPtr resource, upload, readback; + UINT bytes = 0; + bool write = false; +}; +UINT constant(UINT index) { + constexpr UINT words[]{3,9,37,5}; + return words[index % 4]; +} +UINT format_width(ComputeViewKind kind, UINT bytes) { + if (kind == ComputeViewKind::typed_buffer_srv) return 16; + if (kind == ComputeViewKind::buffer_srv || kind == ComputeViewKind::root_buffer_srv || + kind == ComputeViewKind::raw_buffer_uav) return 4; + return bytes; +} +DXGI_FORMAT typed_format(unsigned bytes, bool half, bool reference) { + const DXGI_FORMAT uints[]{DXGI_FORMAT_R32_UINT,DXGI_FORMAT_R32G32_UINT,DXGI_FORMAT_R32G32B32_UINT,DXGI_FORMAT_R32G32B32A32_UINT}; + const DXGI_FORMAT floats[]{DXGI_FORMAT_R32_FLOAT,DXGI_FORMAT_R32G32_FLOAT,DXGI_FORMAT_R32G32B32_FLOAT,DXGI_FORMAT_R32G32B32A32_FLOAT}; + if (half) return bytes == 2 ? DXGI_FORMAT_R16_FLOAT : bytes == 4 ? DXGI_FORMAT_R16G16_FLOAT : DXGI_FORMAT_R16G16B16A16_FLOAT; + return (reference ? floats : uints)[bytes/4-1]; +} +} + +// A reference directory supplies independently compiled DXIL and its user-data layout. +// --direct exercises the same direct DXIL frontend used by the runtime. +int wmain(int argc, wchar_t **argv) { + if (argc != 6 && argc != 7) return 2; + try { + ComPtr device; + const auto device_hr = D3D12CreateDevice(nullptr,D3D_FEATURE_LEVEL_12_0,IID_PPV_ARGS(&device)); + if (device_hr == DXGI_ERROR_UNSUPPORTED) return 77; + check(device_hr, "device"); + ShaderDxilCompiler compiler(argv[1]); + fs::path marker=argv[2], dest=argv[5]; + const bool null_array = argc == 7 && std::wstring_view(argv[6]) == L"--direct-null-srv"; + const bool direct = null_array || (argc == 7 && std::wstring_view(argv[6]) == L"--direct"); + if (direct) { + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_6}; + D3D12_FEATURE_DATA_D3D12_OPTIONS1 waves{}; + if (FAILED(check_feature(device.Get(), D3D12_FEATURE_SHADER_MODEL, &model, sizeof(model))) || + model.HighestShaderModel < D3D_SHADER_MODEL_6_6 || + FAILED(check_feature(device.Get(), D3D12_FEATURE_D3D12_OPTIONS1, &waves, sizeof(waves))) || + !waves.WaveOps || waves.WaveLaneCountMin > 32 || waves.WaveLaneCountMax < 32) { + std::fprintf(stderr, "requires shader model 6.6 with wave32\n"); + return 77; + } + } + const bool reference = argc == 7 && !direct; + auto p=create_native_compute_pipeline(device.Get(),compiler,marker,std::stoul(argv[4]),argv[3],direct); + std::vector args(p.constant_words); + UINT index=0; + for (auto &block:p.constants) + for (unsigned j=0;j dxil{std::istreambuf_iterator(input),{}}; + std::ifstream layout(base.wstring()+L".roots"); + UINT addr, slot, dword; std::string type; + while (layout>>addr>>slot>>type>>dword) { + if (addr>=64 || slot>=16 || (type!="Table" && type!="Constants")) return 2; + roots[addr]= type=="Table" ? slot*256*32 : constant(dword); + } + D3D12_ROOT_PARAMETER param{}; + param.ParameterType=D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + param.Constants.Num32BitValues=64; + D3D12_ROOT_SIGNATURE_DESC rd{1,¶m,0,nullptr,D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED}; + ComPtr blob; + check(D3D12SerializeRootSignature(&rd,D3D_ROOT_SIGNATURE_VERSION_1,&blob,nullptr),"reference root"); + p.root.Reset();p.state.Reset(); + check(device->CreateRootSignature(0,blob->GetBufferPointer(),blob->GetBufferSize(),IID_PPV_ARGS(&p.root)),"reference root"); + D3D12_COMPUTE_PIPELINE_STATE_DESC sd{};sd.pRootSignature=p.root.Get();sd.CS={dxil.data(),dxil.size()}; + check(device->CreateComputePipelineState(&sd,IID_PPV_ARGS(&p.state)),"reference PSO"); + } + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,reference?4096u:UINT(p.bindings.size()),D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr heap; + check(device->CreateDescriptorHeap(&hd,IID_PPV_ARGS(&heap)),"heap"); + const UINT step=device->GetDescriptorHandleIncrementSize(hd.Type); + ComputeCommands cmd(device.Get(),p.state.Get(),D3D12_COMMAND_LIST_TYPE_DIRECT); + std::vector windows; + std::vector atomic; + for (const auto &b:p.bindings) { + const UINT position=reference?b.root_parameter*256+b.byte_offset/32:UINT(windows.size()); + if (position>=hd.NumDescriptors) return 2; + auto cpu=heap->GetCPUDescriptorHandleForHeapStart();cpu.ptr+=UINT64(position)*step; + Window w;w.write=compute_buffer_uav(b.kind); + const bool vector_bytes = b.kind == ComputeViewKind::raw_vector_srv; + const bool root_bytes = b.kind == ComputeViewKind::root_buffer_srv; + if (!w.write && b.kind!=ComputeViewKind::typed_buffer_srv && b.kind!=ComputeViewKind::buffer_srv && !vector_bytes && !root_bytes) return 2; + const bool raw=root_bytes || vector_bytes || b.kind==ComputeViewKind::buffer_srv || b.kind==ComputeViewKind::raw_buffer_uav; + const bool indexed = b.kind == ComputeViewKind::indexed_atomic_uav; + const UINT stride = indexed && b.byte_offset == 32 ? 16 : + indexed && b.byte_offset == 64 ? 12 : format_width(b.kind,b.required_bytes); + w.bytes=(elements+2*guard)*stride; + w.upload=make_buffer(device.Get(),w.bytes,D3D12_HEAP_TYPE_UPLOAD,D3D12_RESOURCE_STATE_GENERIC_READ); + void *mapped; + check(w.upload->Map(0,nullptr,&mapped),"seed"); + std::memset(mapped,0x69,w.bytes); + if (!w.write) { + auto *words=reinterpret_cast(static_cast(mapped)+guard*stride); + constexpr UINT packed[]{0x7fff8000, 0x40008001, 0x007fff81, 0xfc003c00, 0x0001bc00, 0x42987ec5}; + for (UINT j=0;jUnmap(0,nullptr); + if (w.write) { + auto desc=w.upload->GetDesc();desc.Flags=D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + w.resource=resource(device.Get(),desc,D3D12_HEAP_TYPE_DEFAULT,D3D12_RESOURCE_STATE_COPY_DEST); + cmd.list->CopyResource(w.resource.Get(),w.upload.Get()); + transition(cmd.list.Get(),w.resource.Get(),D3D12_RESOURCE_STATE_COPY_DEST,D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + D3D12_UNORDERED_ACCESS_VIEW_DESC v{}; + v.ViewDimension=D3D12_UAV_DIMENSION_BUFFER;v.Buffer.FirstElement=guard;v.Buffer.NumElements=elements; + v.Format=raw?DXGI_FORMAT_R32_TYPELESS:typed_format(stride,b.kind==ComputeViewKind::half_buffer_uav,false); + if(raw)v.Buffer.Flags=D3D12_BUFFER_UAV_FLAG_RAW; + if (indexed) { + if (stride > 4) { + v.Format = DXGI_FORMAT_UNKNOWN; + v.Buffer.StructureByteStride = stride; + } else if (b.byte_offset == 128) { + v.Format = DXGI_FORMAT_R32_TYPELESS; + v.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + } + } + auto truncated = v; + IndexedAtomicView shape; + if(!native_buffer_store_view(b,v,w.bytes,&shape) || + native_buffer_store_view(b,truncated,w.bytes-guard*stride-1,&shape)) return 2; + if (indexed) atomic.push_back(shape); + if(reference&&!raw)v.Format=typed_format(stride,b.kind==ComputeViewKind::half_buffer_uav,true); + device->CreateUnorderedAccessView(w.resource.Get(),nullptr,&v,cpu); + w.readback=make_buffer(device.Get(),w.bytes,D3D12_HEAP_TYPE_READBACK,D3D12_RESOURCE_STATE_COPY_DEST); + } else { + w.resource=w.upload; + D3D12_SHADER_RESOURCE_VIEW_DESC v{};v.ViewDimension=D3D12_SRV_DIMENSION_BUFFER; + v.Shader4ComponentMapping=D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.Format=raw?DXGI_FORMAT_R32_TYPELESS:typed_format(16,false,reference);v.Buffer.FirstElement=guard;v.Buffer.NumElements=elements; + if (root_bytes) { + if (b.required_bytes % 4 || b.required_bytes > elements * 4) return 2; + v.Buffer.NumElements = b.required_bytes / 4; + } + if(raw)v.Buffer.Flags=D3D12_BUFFER_SRV_FLAG_RAW; + auto *source = w.resource.Get(); + if (null_array && b.kind == ComputeViewKind::typed_buffer_srv && b.array_position == 1) { + auto guest = v; + guest.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + auto bad = guest; + bad.Format = DXGI_FORMAT_R8G8B8A8_UINT; + if (x2w_startup::native_null_typed_array_srv(0,0,&guest,sizeof(guest),b.required_bytes,v) || + x2w_startup::native_null_typed_array_srv(18,1,&guest,sizeof(guest),b.required_bytes,v) || + x2w_startup::native_null_typed_array_srv(18,0,&bad,sizeof(bad),b.required_bytes,v) || + x2w_startup::native_null_typed_array_srv(18,0,&guest,sizeof(guest)-1,b.required_bytes,v) || + !x2w_startup::native_null_typed_array_srv(18,0,&guest,sizeof(guest),b.required_bytes,v) || + v.Format != DXGI_FORMAT_R32G32B32A32_UINT || v.Buffer.FirstElement != guard || + v.Buffer.NumElements != elements) return 2; + source = nullptr; + } + device->CreateShaderResourceView(source,&v,cpu); + } + std::printf("%u %u %u %u %u\n", b.root_parameter,b.byte_offset,unsigned(b.kind),stride,w.write); + windows.push_back(std::move(w)); + } + if(reference){ + ID3D12DescriptorHeap* h=heap.Get();cmd.list->SetDescriptorHeaps(1,&h);cmd.list->SetComputeRootSignature(p.root.Get()); + cmd.list->SetComputeRoot32BitConstants(0,64,roots,0); + } else p.bind(cmd.list.Get(),heap.Get(),heap->GetGPUDescriptorHandleForHeapStart(),step,args.data(),atomic); + cmd.list->Dispatch(2,1,1); + for(auto &w:windows) if(w.write) { + transition(cmd.list.Get(),w.resource.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS,D3D12_RESOURCE_STATE_COPY_SOURCE); + cmd.list->CopyResource(w.readback.Get(),w.resource.Get()); + } + cmd.submit_and_wait(device.Get());check(device->GetDeviceRemovedReason(),"completion"); + std::ofstream out(dest,std::ios::binary); + for(auto &w:windows)if(w.write){ + void *mapped;check(w.readback->Map(0,nullptr,&mapped),"readback"); + out.write(static_cast(mapped),w.bytes);w.readback->Unmap(0,nullptr); + } + return out.good()?0:1; + } catch(const std::exception &e){std::fprintf(stderr,"%s\n",e.what());return 1;} +} diff --git a/tests/native_wave_request_check.py b/tests/native_wave_request_check.py new file mode 100644 index 000000000..0965e3e04 --- /dev/null +++ b/tests/native_wave_request_check.py @@ -0,0 +1,258 @@ +"""Exercise the C++ frontend with a source-assembled two-wave request.""" +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from native_compute_clear_check import write_request + + +def sdwa_fixtures(cli_args, gpu, sdk, work, root, sa): + def xor(dst, lhs, rhs, sel0, sel1, dest=6, unused=0, sext0=False): + return [(0x1d << 25) | (dst << 17) | (rhs << 9) | 249, + lhs | (dest << 8) | (unused << 11) | (sel0 << 16) | (int(sext0) << 19) | (sel1 << 24)] + + setup = [ + 0xbe940304, 0xbe950380, 0xbe960305, 0xbe970380, + 0xf4080000 | (32 << 6) | 10, 0xfa000040, + 0xf40c0000 | (40 << 6) | 11, 0xfa0000e0, + 0xd7460008, 12 | (133 << 9) | (256 << 18), 0x7e12020d, + 0xe0042000, 0x80080208, # load v2, v3 from element x + 0x7e000200 | (20 << 17) | 258, 0x7e000200 | (21 << 17) | 259, + ] + finish = [] + for reg, low in [(20, 2), (21, 4)]: + # Store both halves exactly as floats, including NaN-shaped integer results. + finish += [(0x1b << 25) | (low << 17) | (reg << 9) | 255, 65535, + (0x16 << 25) | ((low + 1) << 17) | (reg << 9) | 144] + for reg in range(2, 6): + finish.append(0x7e000000 | (reg << 17) | (6 << 9) | (256 + reg)) + finish += [0xf0200f08, (10 << 16) | (2 << 8) | 8, 0xbf810000] + cases = [ + ("sdwa-alias", xor(20, 20, 20, 5, 6) + xor(21, 3, 2, 2, 1), False), + ("sdwa-preserve", xor(20, 2, 3, 2, 6, sext0=True) + xor(21, 2, 21, 5, 6, 1, 2), False), + ("sdwa-sext", xor(20, 2, 3, 2, 6, sext0=True) + xor(21, 2, 21, 5, 6, 1, 1), False), + ("sdwa-alias", xor(20, 20, 20, 4, 6) + xor(21, 3, 2, 2, 1), True), + ("sdwa-preserve", xor(20, 2, 3, 2, 6, sext0=True) + xor(21, 2, 21, 5, 6, 1, 0), True), + ("sdwa-class", [ + 0x7e000000 | (20 << 17) | (0x65 << 9) | 277, # swap v20 and v21 + 0x7c000000 | (0x88 << 17) | (3 << 9) | 249, 0x03968e80, # class(-0, byte3(v3)) -> s14 + 0xbeea030e, # vcc_lo = s14 + (1 << 25) | (21 << 17) | (21 << 9) | 276, # choose swapped v20 or v21 + ], False), + ] + for mode, operations, mutant in cases: + marker = write_request(work, setup + operations + finish, root, sa) + result = subprocess.run([gpu, sdk, marker, work / "cache", mode], text=True, capture_output=True) + print(mode, "mutant" if mutant else "reference", result.stdout.strip(), flush=True) + assert result.returncode == int(mutant), (result.stdout, result.stderr) + assert ("differing_components=0 " in result.stdout) != mutant + invalid = write_request(work, setup + xor(20, 2, 3, 7, 6) + finish, root, sa) + rejected = subprocess.run([*cli_args, invalid, work / "invalid.cso"], capture_output=True, text=True) + assert rejected.returncode and "SDWA modifiers" in rejected.stderr and not (work / "invalid.cso").exists() + + +def raw_offset_fixtures(cli_args, gpu, sdk, work, root, sa): + def move(dst, src): + return 0x7e000200 | (dst << 17) | src + + def load(op, dst, addr, offset=0): + return [0xe0001000 | (op << 18) | offset, 0x80080000 | (dst << 8) | addr] + + setup = [ + 0xbe940304, 0xbe950380, 0xbe960305, 0xbe970380, + 0xf4080000 | (32 << 6) | 10, 0xfa000040, + 0xf40c0000 | (40 << 6) | 11, 0xfa0000e0, + 0xd7460008, 12 | (133 << 9) | (256 << 18), move(9, 13), + 0xd746000a, 13 | (134 << 9) | (264 << 18), # i = group.y * 64 + x + (0x1a << 25) | (20 << 17) | (10 << 9) | 131, # byte offset = i << 3 + ] + finish = [0x7e000000 | (dst << 17) | (6 << 9) | (256 + src) + for dst, src in zip(range(2, 6), (20, 24, 25, 10))] + finish += [0xf0200f08, (10 << 16) | (2 << 8) | 8, 0xbf810000] + cases = [ + ("raw-offset", [move(24, 276)], load(0x0d, 24, 24), 52, False), + ("raw-offset", [move(25, 276)], load(0x0d, 24, 25), 52, False), + ("raw-edge", [move(24, 255), (2 * 2048 + 15) * 4], load(0x0d, 24, 24), 52, False), + # First word overwrites v24; a second instruction now uses the wrong pair's in-bounds address. + ("raw-offset", [move(24, 276)], load(0x0c, 24, 24) + load(0x0c, 25, 24, 4), 52, True), + ("raw-offset", [move(24, 276)], load(0x0d, 24, 24), 0, True), + ("raw-three", [move(26, 276)], load(0x0f, 24, 26), 52, False), + ("raw-four", [move(27, 276)], load(0x0e, 24, 27), 52, False), + ("raw-math", [move(24, 276)], load(0x0d, 24, 24), 52, False), + # Dword accesses ignore the low two bits after adding the immediate. + ("raw-offset", [(0x25 << 25) | (20 << 17) | (20 << 9) | 131, move(24, 276)], + load(0x0d, 24, 24), 52, False), + ] + for mode, addr, pair, offset, mutant in cases: + tail = finish + if mode in ("raw-three", "raw-four"): + registers = (24, 25, 26, 27 if mode == "raw-four" else 20) + tail = [0x7e000000 | (dst << 17) | (6 << 9) | (256 + src) + for dst, src in zip(range(2, 6), registers)] + finish[4:] + elif mode == "raw-math": + tail = finish[:4] + [(8 << 25) | (2 << 17) | (5 << 9) | 255, 0x3e800000, + 0x7e000000 | (2 << 17) | (0x36 << 9) | 258, + 0x7e000000 | (5 << 17) | (0x0b << 9) | 280] + finish[4:] + words = setup + addr + load(0x0c, 20, 20, offset) + pair + tail + marker = write_request(work, words, root, sa) + run = subprocess.run([gpu, sdk, marker, work / "cache", mode], capture_output=True, text=True) + print(mode, "mutant" if mutant else "reference", run.stdout.strip(), flush=True) + assert run.returncode == int(mutant), (run.stdout, run.stderr) + expected = 2048 if mutant else 0 + assert f"differing_components={expected} " in run.stdout + # Select a different 32-byte descriptor for each of the two X workgroups. + # Both vector loads share the descriptor. Clobber its source index before either load. + def scalar(op, dst, a, b): + return 0x80000000 | (op << 23) | (dst << 16) | (b << 8) | a + + table_load = 0xf4080000 | (32 << 6) | 10 + for flip in (0, 1): + selector = [scalar(0, 28, 12, 128 + flip), scalar(0x0e, 28, 28, 129), scalar(0x1e, 28, 28, 133)] + words = (setup[:4] + selector + [table_load, (28 << 25) | 64, 0xbe9c0380] + setup[6:] + + [move(24, 276)] + load(0x0c, 20, 20, 52) + load(0x0d, 24, 24) + finish) + marker = write_request(work, words, root, sa) + run = subprocess.run([gpu, sdk, marker, work / "cache", "indexed"], capture_output=True, text=True) + print("indexed", "flipped" if flip else "reference", run.stdout.strip(), flush=True) + assert run.returncode == flip and f"differing_components={6144 * flip} " in run.stdout, (run.stdout, run.stderr) + for change, value in ((0, 0xbe94030a), (8, (28 << 25) | 512)): + invalid_words = words.copy() + invalid_words[change] = value + marker = write_request(work, invalid_words, root, sa) + run = subprocess.run([*cli_args, marker, work / "invalid-span.cso"], text=True, capture_output=True) + assert run.returncode and not (work / "invalid-span.cso").exists(), run.stdout + invalid = write_request(work, setup + load(0x0d, 255, 20) + finish, root, sa) + result = subprocess.run([*cli_args, invalid, work / "invalid-pair.cso"], capture_output=True, text=True) + assert result.returncode and "destination overflow" in result.stderr and not (work / "invalid-pair.cso").exists() + indexed = load(0x0d, 24, 20) + indexed[0] |= 1 << 13 + invalid = write_request(work, setup + indexed + finish, root, sa) + result = subprocess.run([*cli_args, invalid, work / "indexed.cso"], capture_output=True, text=True) + assert result.returncode and "needs offen" in result.stderr and not (work / "indexed.cso").exists() + + +def global_stride_fixtures(gpu, sdk, work, root, source, sa): + source.write_text('#define SIG "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | SAMPLER_HEAP_DIRECTLY_INDEXED),' + 'DescriptorTable(SRV(t0,numDescriptors=16)),DescriptorTable(UAV(u0,numDescriptors=16)),' + 'RootConstants(num32BitConstants=4,b0)"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, source], check=True) + # GPU input s[40:47] feeds s43. Select a heap slot, then extract descriptor word 1 bits 16..29. + # The table index is deliberately unbounded at compile time, and is overwritten before the extract. + for selector_offset in (0, 4): + words = [0xbe940304, 0xbe950380, 0xbe960305, 0xbe970380, + 0xf4080000 | (24 << 6) | 10, 0xfa000040, + 0xf40c0000 | (56 << 6) | 11, 0xfa0000e0, + 0x80000000 | (0x1e << 23) | (20 << 16) | (133 << 8) | 12, + 0xf42c0000 | (40 << 6) | 12, (20 << 25) | selector_offset, + 0xbe9e030a, 0xbe9f0380, 0x80000000 | (0x1e << 23) | (43 << 16) | (133 << 8) | 43, + 0xf4080000 | (48 << 6) | 15, 43 << 25, 0xbeab0380, + 0x93800000 | (28 << 16) | (255 << 8) | 49, 0x000e0010, + 0xd7460008, 12 | (133 << 9) | (256 << 18), 0x7e12020d] + words += [0x7e000000 | (v << 17) | (6 << 9) | 28 for v in range(2, 6)] + words += [0xf0200f08, (14 << 16) | (2 << 8) | 8, 0xbf810000] + marker = write_request(work, words, root.read_bytes(), sa) + result = subprocess.run([gpu, sdk, marker, work / "cache", "global-stride"], capture_output=True, text=True) + print("global-stride", selector_offset, result.stdout.strip(), flush=True) + assert result.returncode == int(bool(selector_offset)), (result.stdout, result.stderr) + assert f"differing_components={8192 if selector_offset else 0} " in result.stdout + + +def main(cli, gpu, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + source = work / "root.hlsl" + source.write_text('#define SIG "DescriptorTable(SRV(t0,numDescriptors=16)),DescriptorTable(UAV(u0,numDescriptors=16))"') + root = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, source], check=True) + sa = struct.pack("<7I", 0, 0, 0, 8 | (8 << 16), 1, 0, 0x8d8c) + # s4 and s5 are the two guest tables. The byte offsets deliberately differ + # from the desktop registers that the translator assigns to them. + words = [ + 0xbe940304, 0xbe950380, 0xbe960305, 0xbe970380, + 0xf4080000 | (32 << 6) | 10, 0xfa000040, # descriptor s32:35, table 0 +64 + 0xf40c0000 | (40 << 6) | 11, 0xfa0000e0, # descriptor s40:47, table 1 +224 + 0xbe8b0384, # s11 = byte offset 4 + 0xf4240000 | (11 << 6) | 16, 11 << 25, # s[11:12] = buffer[s11], mask in second word + 0x938dff08, 0x00050014, # wave in group from TG_SIZE_EN -> s13 + 0x938eff08, 0x00060000, # number of waves -> s14 + 0xd7650002, (128 << 9) | 193, # v2 = mbcnt(-1, 0) + 0xd7650003, (128 << 9) | 12, # v3 = mbcnt(s12, 0) + ] + for dst, src in [(2,258),(3,259),(4,13),(5,14)]: + words.append(0x7e000000 | (dst << 17) | (6 << 9) | src) # v_cvt_f32_u32 + words.extend([0xf0200f08, (10 << 16) | (2 << 8), 0xbf810000]) + marker = write_request(work, words, root.read_bytes(), sa) + args = [cli, sdk, work / "cache", "gfx1013-compute-wave32@0"] + result = subprocess.run([*args, marker, work / "good.cso"], capture_output=True, text=True, check=True) + assert "t0 root=0 bytes=64 min_size=4" in result.stdout and "u0 root=1 bytes=224" in result.stdout + rejected = write_request(work, [*words[:-1], 0xffffffff, words[-1]], root.read_bytes(), sa) + result = subprocess.run([*args, rejected, work / "bad.cso"], capture_output=True, text=True) + # 0xffffffff is not a gfx1013 encoding, so the decoder refuses it before any lowering. + assert result.returncode and "unknown gfx1013 instruction format at byte" in result.stderr, result.stderr + assert not (work / "bad.cso").exists() + batch_dir = work / "batch-output" + batch = subprocess.run([cli, sdk, work / "cache", "--jobs", "2", "gfx1013-compute-wave32@0", + "--requests", work, batch_dir], capture_output=True, text=True) + assert batch.returncode == 1 and "requests=2 compiled=1 refused=1" in batch.stdout + assert (batch_dir / f"{marker.stem[4:]}.cs.cso").read_bytes() == (work / "good.cso").read_bytes() + assert (batch_dir / f"{marker.stem[4:]}.txt").is_file() + assert not (batch_dir / f"{rejected.stem[4:]}.cs.cso").exists() + assert not (batch_dir / f"{rejected.stem[4:]}.txt").exists() + first = subprocess.run([gpu, sdk, marker, work / "cache"]) + if first.returncode: + return first.returncode + + source.write_text('#define SIG "DescriptorTable(SRV(t0,numDescriptors=16)),' + 'DescriptorTable(UAV(u0,numDescriptors=16)),RootConstants(num32BitConstants=4,b0)"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, source], check=True) + sa = struct.pack("<7I", 0, 0, 0, 32 | (1 << 16), 1, 0, 0x198) + # One 32-lane group per tile. s6/s7 are root constants and s12/s13 are the group IDs. + code = [ + 0xbe940304, 0xbe950380, 0xbe960305, 0xbe970380, + 0xf4080000 | (32 << 6) | 10, 0xfa000040, + 0xf40c0000 | (40 << 6) | 11, 0xfa0000e0, + 0x930f060d, 0x800f070f, # s15 = group.y * root[0] + root[1] + 0xd7460008, 12 | (133 << 9) | (256 << 18), # v8 = (group.x << 5) + local.x + 0x80000000 | (0x31 << 23) | (15 << 16) | (129 << 8) | 15, # (s15 << 4) + 1 + 0x7c000000 | (0xc1 << 17) | (8 << 9) | 159, # wave mask for 31 < x + 0xbe910383, 0xbf860001, 0xbe910389, # s17 = 3 in tile 0, 9 in tile 1 + 0x4a000000 | (10 << 17) | (8 << 9) | 17, # v10 = x + s17 + 0x7e12020d, # v9 = group.y + 0xe0042000, 0x80080208, # v[2:3] = formatted[v8].xy + 0x4a06060f, # v3 = v3 + s15 + ] + for dst, src in [(2, 258), (3, 259), (4, 266), (5, 13)]: + code.append(0x7e000000 | (dst << 17) | (6 << 9) | src) + # Convert y/2 with ties-to-even, then round-trip through unsigned integer. + code.extend([0x10000000 | (5 << 17) | (5 << 9) | 240, + 0x7e000000 | (5 << 17) | (0x23 << 9) | 261, + 0x7e000000 | (5 << 17) | (7 << 9) | 261, + 0x7e000000 | (5 << 17) | (6 << 9) | 261]) + code.extend([0xf0200f08, (10 << 16) | (2 << 8) | 8, 0xbf810000]) + typed = write_request(work, code, root.read_bytes(), sa) + subprocess.run([*args, typed, work / "typed.cso"], check=True) + unbound = write_request(work, [*code[:-1], 0x800f000f, code[-1]], root.read_bytes(), sa) + rejection = subprocess.run([*args, unbound, work / "unbound.cso"], capture_output=True, text=True) + assert rejection.returncode and "unbound numeric SGPR s0" in rejection.stderr + assert not (work / "unbound.cso").exists() + subprocess.run([gpu, sdk, typed, work / "cache", "typed"], check=True) + # Only the low 16 bits are stored. Distinct high bits expose an accidental high-half selection. + for half, mode in ((0xc100, "half-value"), (0x4100, "half-mutant")): + words = [0xbe960305, 0xbe970380, 0xf40c0000 | (40 << 6) | 11, 0xfa0000e0, + 0xd7460008, 12 | (133 << 9) | (256 << 18), 0x7e12020d, + 0x7e0402ff, 0x45000000 | half, + 0xf0200108, 0x80000000 | (10 << 16) | (2 << 8) | 8, 0xbf810000] + marker = write_request(work, words, root.read_bytes(), sa) + result = subprocess.run([gpu, sdk, marker, work / "cache", mode], capture_output=True, text=True) + mutant = mode == "half-mutant" + assert result.returncode == int(mutant), (result.stdout, result.stderr) + print(mode, result.stdout.strip(), flush=True) + sdwa_fixtures(args, gpu, sdk, work, root.read_bytes(), sa) + raw_offset_fixtures(args, gpu, sdk, work, root.read_bytes(), sa) + global_stride_fixtures(gpu, sdk, work, root, source, sa) + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_wave_request_gpu.cpp b/tests/native_wave_request_gpu.cpp new file mode 100644 index 000000000..fe60f81cd --- /dev/null +++ b/tests/native_wave_request_gpu.cpp @@ -0,0 +1,104 @@ +#include "desktop_gpu.h" +#include "native_compute_pipeline.h" +#include +#include +#include + +using Microsoft::WRL::ComPtr; +int check_native_compute_grid(ID3D12Device*, x2w::ShaderDxilCompiler&, const wchar_t*, const wchar_t*, const std::wstring&); +int check_half_grid(ID3D12Device*, x2w::ShaderDxilCompiler&, const wchar_t*, const wchar_t*, const std::wstring&); +int wmain(int argc, wchar_t **argv) { + if (argc != 4 && argc != 5) + return 2; + try { + ComPtr factory; + check(CreateDXGIFactory1(IID_PPV_ARGS(&factory)), "factory"); + ComPtr device; + for (UINT i = 0; !device; ++i) { + ComPtr adapter; + if (factory->EnumAdapters1(i, &adapter) != S_OK) + return 77; + DXGI_ADAPTER_DESC1 description{}; + check(adapter->GetDesc1(&description), "adapter description"); + if (description.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) + continue; + ComPtr candidate; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&candidate)))) + continue; + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_6}; + D3D12_FEATURE_DATA_D3D12_OPTIONS1 waves{}; + if (FAILED(check_feature(candidate.Get(), D3D12_FEATURE_SHADER_MODEL, &model, sizeof(model))) || + model.HighestShaderModel < D3D_SHADER_MODEL_6_6 || + FAILED(check_feature(candidate.Get(), D3D12_FEATURE_D3D12_OPTIONS1, &waves, sizeof(waves))) || + !waves.WaveOps || waves.WaveLaneCountMin > 32 || waves.WaveLaneCountMax < 32) + continue; + device = candidate; + } + x2w::ShaderDxilCompiler compiler(argv[1]); + if (argc == 5 && std::wstring(argv[4]).find(L"half-") == 0) + return check_half_grid(device.Get(), compiler, argv[2], argv[3], argv[4]); + if(argc==5)return check_native_compute_grid(device.Get(),compiler,argv[2],argv[3],argv[4]); + auto pipeline = x2w::create_native_compute_pipeline(device.Get(), compiler, argv[2], 0, argv[3]); + if (!pipeline.cache_hit || pipeline.srv_count != 1 || pipeline.bindings.size() != 2) + return 1; + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr heap; + check(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap)), "descriptor heap"); + UINT step = device->GetDescriptorHandleIncrementSize(hd.Type); + auto cpu = heap->GetCPUDescriptorHandleForHeapStart(); + auto input = make_buffer(device.Get(), 12, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + const unsigned words[]{0, 0x10000, 0x55555555}; + void *mapped; + check(input->Map(0, nullptr, &mapped), "map input"); + std::memcpy(mapped, words, sizeof(words)); + input->Unmap(0, nullptr); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.Buffer.NumElements = 3; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(input.Get(), &srv, cpu); + cpu.ptr += step; + D3D12_RESOURCE_DESC td{}; + td.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + td.Width = td.Height = 8; + td.DepthOrArraySize = td.MipLevels = td.SampleDesc.Count = 1; + td.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + td.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + auto texture = resource(device.Get(), td, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + device->CreateUnorderedAccessView(texture.Get(), nullptr, nullptr, cpu); + ComputeCommands commands(device.Get(), pipeline.state.Get()); + pipeline.bind(commands.list.Get(), heap.Get(), heap->GetGPUDescriptorHandleForHeapStart(), step); + commands.list->Dispatch(1, 1, 1); + transition(commands.list.Get(), texture.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 bytes; + device->GetCopyableFootprints(&td, 0, 1, 0, &footprint, nullptr, nullptr, &bytes); + auto readback = make_buffer(device.Get(), bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + D3D12_TEXTURE_COPY_LOCATION src{texture.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + D3D12_TEXTURE_COPY_LOCATION dst{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + dst.PlacedFootprint = footprint; + commands.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + commands.submit_and_wait(device.Get()); + check(readback->Map(0, nullptr, &mapped), "read pixels"); + for (unsigned i = 0; i < 64; ++i) { + auto pixel = reinterpret_cast(static_cast(mapped) + + (i / 8) * footprint.Footprint.RowPitch) + + (i % 8) * 4; + unsigned lane = i % 32; + if (pixel[0] != lane || pixel[1] != (lane + 1) / 2 || pixel[2] != i / 32 || pixel[3] != 2) { + std::fprintf(stderr, "lane %u: %g %g %g %g\n", i, pixel[0], pixel[1], pixel[2], pixel[3]); + return 1; + } + } + readback->Unmap(0, nullptr); + std::puts("64 lanes, two wave32 groups, masked prefix counts and offline-to-runtime cache match"); + return 0; + } catch (const std::exception &error) { + std::fprintf(stderr, "%s\n", error.what()); + return 1; + } +} diff --git a/tests/startup_compute_dispatch_native_check.py b/tests/startup_compute_dispatch_native_check.py new file mode 100644 index 000000000..2a0809e72 --- /dev/null +++ b/tests/startup_compute_dispatch_native_check.py @@ -0,0 +1,120 @@ +"""A slot 67 compute program translated in-process by the C++ compiler and dispatched through the stand-in (#2934). + +usage: startup_compute_dispatch_native_check.py + +X2W_NATIVE_SHADERS names the directory of dxcompiler.dll and dxil.dll. The cache starts empty and no offline +translator runs before step 3. The program is case A of startup_gfx2hlsl_compute_check.py with its two buffer +descriptors loaded from 32-byte table records (two s_load_dwordx4, at table bytes 0 and 32), the layout the C++ +compiler reads a table in. The consumer's dispatch-records32 mode writes the table that way. The reference is +that case's CPU expectation. + +1. Native: the first Dispatch translates the request in the stand-in and is recorded. All 320 words match, the log + names the native translation, and the cache holds request files and compiler cache entries only (no .txt, + .cs.cso or .fail). The same program over the plain table layout, which has no descriptor at byte 32, + is then refused when it is bound and every word keeps the sentinel: the record at byte 32 is what was bound. +2. Unsupported workload: case A itself reads its second descriptor from table byte 16. The C++ compiler refuses + it, the reason is logged, the Dispatch is refused with "no translation" and every word keeps the sentinel. +3. Fallback: gfx2hlsl.py --pending then publishes both requests, and with native translation still on the next run + dispatches case A through the published translation. All 320 words match. +4. Order: the first program runs again, now with a published translation in the cache. The native translation is + still the one used, and all 320 words match. + +A direct compute module declares wave size 32. On an adapter without 32-lane waves, step 1 instead checks that the +native translation is refused by that name with the output untouched, steps 2 and 3 run as written, step 4 runs the +first program through its published translation, and the check exits 77. Exit 77 also when the adapter is not +available. +""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +import startup_gfx2hlsl_compute_check as C +from startup_compute_dispatch_check import dispatch, lines, prepare_case +from startup_stream_check import gfx2hlsl as G + +LOAD_X8 = bytes.fromhex('05030cf4' '000000fa') +LOADS_X4 = bytes.fromhex('050308f4' '000000fa' '050408f4' '200000fa') +RECORD_LOADS = ['s_load_dwordx4 s[12:15], s[10:11], 0x0', 's_load_dwordx4 s[16:19], s[10:11], 0x20'] +NO_WAVES = 'not translated natively: the adapter has no 32-lane waves' + + +def mismatch(got, expected, result): + wrong = [i for i in range(C.WORDS) if got[i] != expected[i]] + return '' if not wrong else 'word=%d got=%08x expected=%08x (%d words differ)\n%s' % ( + wrong[0], got[wrong[0]], expected[wrong[0]], len(wrong), result.stderr[-3000:]) + + +def main(consumer, dxc_dir, adapter): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + cache, env = prepare_case(directory, adapter) + env['X2W_NATIVE_SHADERS'] = dxc_dir + case_a = (directory / 'program').read_bytes() + records32 = case_a.replace(LOAD_X8, LOADS_X4) + assert case_a.count(LOAD_X8) == 1 and [i[3] for i in G.decode(records32)[2:4]] == RECORD_LOADS + untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A') + + (directory / 'program').write_bytes(records32) + got, result = dispatch(directory, consumer, env, 'dispatch-records32') + print(result.stdout, end='') + key32 = int(lines(result, 'x2w-draw compute request')[0].split()[3], 16) + no_waves = bool(lines(result, NO_WAVES)) + if no_waves: + assert got == untouched, 'a Dispatch without 32-lane waves wrote the output' + assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + else: + assert not mismatch(got, expected, result), mismatch(got, expected, result) + assert len(lines(result, 'translated natively: 2 entry values, 1 inputs, 1 outputs')) == 1, result.stderr[-3000:] + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused'), result.stderr[-3000:] + layer = lines(result, 'x2w-d3d12 debug layer: ') + 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('debug layer: ' + ('enabled, no error message' if layer and '0x00000000' in layer[0] else 'unavailable')) + got, result = dispatch(directory, consumer, env, 'dispatch') + refused = lines(result, 'refused: ') + assert got == untouched, 'a Dispatch with no descriptor at table byte 32 wrote the output' + assert len(refused) == 1 and 'no translation' not in refused[0], result.stderr[-3000:] + published = sorted(p.name for p in cache.iterdir() if not p.name.startswith('req_') and p.name != 'native') + assert not published, f'the native route left {published} in the cache' + + (directory / 'program').write_bytes(case_a) + got, result = dispatch(directory, consumer, env, 'dispatch') + reason = lines(result, 'not translated natively: ') + assert got == untouched, 'a Dispatch of a program the C++ compiler refused wrote the output' + assert len(reason) == 1 and 'unaligned descriptor table entry' in reason[0], result.stderr[-3000:] + assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + key = int(reason[0].split('compute pipeline ')[1].split()[0], 16) + + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, capture_output=True, + text=True, env=dict(os.environ, X2W_DXC=str(Path(dxc_dir) / 'dxc.exe'))).stdout + assert f'{key:016x}: ok' in out, out + got, result = dispatch(directory, consumer, env, 'dispatch') + assert not mismatch(got, expected, result), mismatch(got, expected, result) + assert lines(result, 'not translated natively: ') and len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1, \ + result.stderr[-3000:] + + assert f'{key32:016x}: ok' in out, out + (directory / 'program').write_bytes(records32) + got, result = dispatch(directory, consumer, env, 'dispatch-records32') + assert not mismatch(got, expected, result), mismatch(got, expected, result) + assert bool(lines(result, f'{key32:016x} translated natively')) != no_waves, result.stderr[-3000:] + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1, result.stderr[-3000:] + + controls = ('the C++ compiler refuses case A with every word untouched, and a published translation then runs ' + 'it') + if no_waves: + print(f'startup_compute_dispatch_native: SKIP on {adapter}: the adapter has no 32-lane waves. Checked: the ' + f'native translation is refused by that name with every word untouched; {controls}; the first ' + f'program matches all {C.WORDS} words through its published translation') + sys.exit(77) + print(f'startup_compute_dispatch_native: PASS on {adapter} (all {C.WORDS} words match after the in-process ' + f'translation from an empty cache, and again with a published translation in the cache; the plain table ' + f'layout is refused when bound; {controls})') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit(__doc__) + main(*sys.argv[1:]) diff --git a/tests/startup_run_ps1_check.py b/tests/startup_run_ps1_check.py index e4f5c4220..6acfb28c6 100644 --- a/tests/startup_run_ps1_check.py +++ b/tests/startup_run_ps1_check.py @@ -31,7 +31,8 @@ import time from pathlib import Path -record = [sys.argv[1:], os.environ.get("X2W_TRACE_API"), os.environ.get("X2W_TITLE_ID"), os.environ.get("X2W_STORAGE_MB")] +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,12 +137,13 @@ 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, manifest="absent"): + 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. `translate` exercises -Render -Translate and requires the watcher to stop with its child. With `early_exit` the watcher has no child and exits before the debugger finishes. + `native` passes -Render -NativeShaders : the stand-in gets the directory and no watcher starts. This checks the log head and debugger exit code. The live watcher case checks worker cleanup. """ root = Path(tempfile.mkdtemp(dir=work)).resolve() @@ -170,6 +172,7 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), # Compare PowerShell's warning text consistently on hosts that enable ANSI colors. env["NO_COLOR"] = "1" env.pop("X2W_FAKE_USER", None) + env.pop("X2W_NATIVE_SHADERS", None) if trace_api_env is None: env.pop("X2W_TRACE_API", None) else: @@ -186,6 +189,10 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), "-Exe", str(exe), "-DataDir", str(data), "-LogDir", str(log), "-BuildDir", build_arg, "-Seconds", "9", "-MemoryGiB", "3", "-ContinueAsserts", "4", *switches] + sdk = root / "dxc" + if native: + sdk.mkdir() + command += ["-Render", "-NativeShaders", str(sdk), "-ShaderCache", "cache"] if translate: command += ["-Render", "-Translate", "-ShaderCache", "cache"] (startup / "translate.flag").write_bytes(b"") @@ -224,10 +231,11 @@ def run_case(shell, script, code, work, translate=False, switches=(), 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, "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, trace, title ID, storage MB] was {got}, expected {expected}") + found.append(f"stub exit {code}: debugger [argv, trace, native shaders, title ID, storage MB] was {got}, expected {expected}") watch = startup / "watch.json" if translate: started = json.loads(watch.read_text(encoding="utf-8")) if watch.is_file() else None @@ -264,6 +272,7 @@ def run_problems(shell, script, work, first_only): found += run_case(shell, script, 0, work, switches=["-TraceCalls"], passed=["--trace-calls", "1"]) found += run_case(shell, script, 0, work, switches=["-TraceApi"], trace_api_env="0") found += run_case(shell, script, 0, work, trace_api_env="1") + found += run_case(shell, script, 0, work, native=True) if found and first_only: return found found += run_case(shell, script, 7, work, translate=True) @@ -305,6 +314,8 @@ def text_problems(script): if not re.search(r"""^if\s*\(\s*\$TraceApi\s*\)\s*\{\s*\$env:X2W_TRACE_API\s*=\s*["']1["']\s*\}""", before, re.I | re.M): found.append("missing -TraceApi environment opt-in before launch") + if not re.search(r"\$env:X2W_NATIVE_SHADERS\s*=", before): + found.append("missing -NativeShaders directory hand-over before launch") if not WATCH_CLEANUP.search("\n".join(after)): found.append("tree cleanup lacks taskkill /T, the live-watcher guard or the local Continue scope") return found @@ -326,6 +337,7 @@ def mutants_of(script): "fixed exit 2": ["exit 2" if is_exit(line) else line for line in lines], "exit before the log head": early, "no FakeUser warning": no_fake_warn, + "no X2W_NATIVE_SHADERS": [line for line in lines if "$env:X2W_NATIVE_SHADERS" not in line], # The same text without the warning prefix: the run must still see Write-Warning's prefix. "FakeUser warning printed with Write-Host": [ line.replace(FAKE_USER_WARN_LINE, f'Write-Host "{FAKE_USER_WARNING}"') for line in lines], diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index 8f95be216..aa7fee734 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -163,7 +163,7 @@ static void* desktop_pipeline(void* device) // data-pointer valid, with the first data qword pointing at state block A // code-zero, data-zero, no-root, code-unreadable, code-past-end, data-unreadable, state-unreadable, // stateb-unreadable, desc-unreadable -// dispatch, dispatch-swapped, dispatch-none, dispatch-sampled, dispatch-sampled-unbound, dispatch-sampled-2x1, dispatch-heap, +// dispatch, dispatch-swapped, dispatch-none, dispatch-records32, dispatch-sampled, dispatch-sampled-unbound, dispatch-sampled-2x1, dispatch-heap, // dispatch-heap-outside, dispatch-heap-word*, dispatch-input-*: one creation, then dispatch_slot67 below // texture-store, texture-store-none, texture-store-denied, texture-store-occupied, texture-store-copied: one creation, then texture_slot67 below // The unreadable cases point at a PAGE_NOACCESS page; code-past-end ends the code on the last byte before one. @@ -190,6 +190,8 @@ static void* make_committed(void* device, D3D12_HEAP_TYPE type, const D3D12_RESO // in one allocation, so both alias this process's memory and the result is read from that memory after the queue's // fence. dispatch-swapped exchanges the two descriptors (the output then names the buffer without unordered // access); dispatch-none records everything but the Dispatch. The 320 output words go to X2W_TEST_DISPATCH_OUT. +// dispatch-records32 writes the table as 32-byte records, the layout the C++ compiler reads a table in +// (startup_compute_dispatch_native_check.py): the output's descriptor at byte 32 and none at byte 16. // dispatch-sampled adds what the sampling variant of the case reads: a committed 1x1 RGBA8 texture filled by // CopyTextureRegion (list slot 16) and a shader resource view of it (device slot 18) whose token the stand-in // writes at table byte 64. dispatch-sampled-unbound creates no view, so that entry holds no token. @@ -315,6 +317,10 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin } else { std::memcpy(reinterpret_cast(cpu), descriptors, sizeof(descriptors)); } + 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])); + } void* other_heap = nullptr; if (change_table_heap && (FAILED(static_cast(invoke(device, 14, word(&heap_desc), word(&__uuidof(ID3D12DescriptorHeap)), diff --git a/tests/startup_triage_run_check.py b/tests/startup_triage_run_check.py index 75337d70f..860b3a9a8 100644 --- a/tests/startup_triage_run_check.py +++ b/tests/startup_triage_run_check.py @@ -122,6 +122,8 @@ def check_aggregation_and_redaction(failures: list[str]) -> None: "undecodable word at +0x10: AcmeTitle shader text", "image_load_mip tfe AcmeTitle", "image_load_mip tfe", + "native compute +0x1a: unsupported instruction v_acme_widget_7f3a 0xdeadbeefu", + "native compute +0x1c: AcmeTitle secret reason", ] PRIVATE_NEEDLES = [ "Acme", "acme", "ACME", "Private", "secret", "leak", "widget", "7f3a", "exploded", @@ -159,6 +161,10 @@ def check_private_text_never_echoed(failures: list[str]) -> None: ]: if want not in report: failures.append(f"missing grouped allowlist row: {want!r}") + if "| 4 | `other (text omitted)` |" not in report: + failures.append("unknown shader .fail lines were not grouped as other (text omitted)") + if "| 1 | `v_* instruction` |" not in report: + failures.append("native unsupported instruction .fail line was not grouped under its mnemonic family") if "| 1 | other (text omitted) | ? | ? | ? | ? | ? | ? |" not in report: failures.append("unknown slot70 reason/values were not grouped as other/?") @@ -491,6 +497,19 @@ def check_every_shader_reason_entry_is_reachable(failures: list[str]) -> None: # text changed, folds a known cause into "other" without failing anything else. The samples are # matched back to the table so a new entry without a sample fails here. samples = ( + ("native compute +0x14: unsupported instruction v_add3_u32 0xd76d0002u", "v_* instruction"), + ("native compute +0x8: unsupported opcode 0xdeadbeefu", "unsupported opcode"), + ("native compute +0x10: unsupported pixel entry VGPR 2", "unsupported pixel entry VGPR"), + ("native compute +0x1c: unproven resource descriptor s12", "unproven resource descriptor"), + ("native compute +0x20: unbound numeric SGPR s0", "unbound numeric SGPR"), + ("unknown gfx1013 instruction format at byte 24", "undecodable word"), + ("graphics request key mismatch or missing root", "graphics request key mismatch"), + ("compute request key mismatch", "compute request key mismatch"), + ("stale pixel input description: graphics request key mismatch", "stale pixel input description"), + ("pixel input description names another pipeline", "pixel input description names another pipeline"), + ("contradictory pixel input enable/address masks", "contradictory pixel input enable/address masks"), + ("pixel input enable mask missing from the stream description", "invalid pixel input description"), + ("invalid pixel input description", "invalid pixel input description"), ("image_load_mip tfe", "image_load_mip tfe"), ("image_load_mip a16", "image_load_mip a16"), ("buffer_load_format_xyzw requires descriptor FORMAT and DST_SEL", "buffer_* instruction"), diff --git a/tools/startup/compile_dxil.cpp b/tools/startup/compile_dxil.cpp new file mode 100644 index 000000000..7fb8f8da6 --- /dev/null +++ b/tools/startup/compile_dxil.cpp @@ -0,0 +1,1093 @@ +#include "shader_dxil_compiler.h" +#include "direct_compute_cache.h" +#include "gfx1013_pixel.h" +#include "gfx1013_sampled_pixel.h" +#include "gfx1013_vertex_id.h" +#include "gfx1013_compute_clear.h" +#include "gfx1013_compute_native.h" +#include "startup_stubs/native_global_srv.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using Clock = std::chrono::steady_clock; +static double elapsed_ms(Clock::time_point since) { + return std::chrono::duration(Clock::now()-since).count(); +} + +namespace fs = std::filesystem; + +static void publish_atomic(const fs::path& destination, const void* data, size_t size) { + static std::atomic serial{}; + auto temp=destination; + temp += L"." + std::to_wstring(GetCurrentProcessId()) + L"." + std::to_wstring(serial++) + L".tmp"; + try { + std::ofstream file(temp,std::ios::binary); + file.exceptions(std::ios::badbit | std::ios::failbit); + if (size) file.write(static_cast(data),size); + file.close(); + if(!MoveFileExW(temp.c_str(),destination.c_str(),MOVEFILE_REPLACE_EXISTING)) + throw std::runtime_error("could not publish output"); + } catch(...) { + std::error_code ignored; + fs::remove(temp,ignored); + throw; + } +} + +// The view metadata captured with a compute request (req_.views), read before the program is translated. Absent: +// the request has no captured selection and a GPU-selected heap read is refused. Present: every refusal below happens +// before any output is published. +struct CapturedViews { + x2w::HeapViewContract contract = x2w::HeapViewContract::none; + x2w_startup::GlobalSrvRequest request; + bool present = false; +}; + +static CapturedViews read_captured_views(const fs::path& request_path) { + CapturedViews views; + const auto path = fs::path(request_path).replace_extension(L".views"); + std::ifstream file(path, std::ios::binary); + if (!file) return views; + std::string text((std::istreambuf_iterator(file)), {}); + if (file.bad()) throw std::runtime_error("global SRV view metadata read failed"); + std::string error; + if (!x2w_startup::decode_global_srv_request(text, views.request, error)) throw std::runtime_error(error); + views.present = true; + const auto& request = views.request; + auto refusal = x2w_startup::refuse_global_srv_selection(request.views, request.selected, request.needed); + if (!refusal.empty()) throw std::runtime_error(refusal); + if (request.needed != x2w_startup::GlobalSrvType::raw_buffer) + throw std::runtime_error(std::string("GPU-selected heap slot view type ") + + x2w_startup::global_srv_type_name(request.needed) + + " is not raw_buffer; only raw buffer heap reads are translated"); + views.contract = x2w::HeapViewContract::raw_buffer; + return views; +} + +static std::vector compile_to_dxil(x2w::ShaderDxilCompiler& compiler, const std::string& source, + const std::wstring& profile, const fs::path& cache, bool direct, + std::ostream& report) { + auto start=Clock::now(); + auto output=compiler.compile(source,profile,cache,direct?x2w::ShaderSourceFormat::dxil_ir:x2w::ShaderSourceFormat::hlsl); + report << (output.cache_hit?"cache_hit_ms=":"cold_compile_and_publish_ms=") + << elapsed_ms(start) << " bytes=" << output.dxil.size() << '\n'; + return std::move(output.dxil); +} + +static void compile_source(x2w::ShaderDxilCompiler& compiler,const std::string& source,const std::wstring& profile, + const fs::path& destination,const fs::path& cache,bool direct,std::ostream& report) { + auto dxil = compile_to_dxil(compiler, source, profile, cache, direct, report); + publish_atomic(destination, dxil.data(), dxil.size()); +} + +static std::optional compile_one(x2w::ShaderDxilCompiler& compiler, std::wstring profile, + const fs::path& input_path, const fs::path& destination, + const fs::path& cache, std::ostream& report, + const x2w::NativeComputeShader *linked=nullptr, + bool emit_manifest=false) { + Clock::time_point start; + std::string source; + std::optional manifest; + const std::wstring clear_prefix=L"gfx1013-group-clear@"; + const std::wstring direct_prefix=L"gfx1013-direct-cs@"; + const bool container=profile==L"gfx1013-container-cs"; + const bool graphics=profile==L"gfx1013-container-vs" || profile==L"gfx1013-container-ps"; + const bool direct=container || graphics || profile==L"gfx1013-direct-constant-ps" || profile.compare(0,direct_prefix.size(),direct_prefix)==0; + const std::wstring compute_prefix=direct?direct_prefix:L"gfx1013-compute-wave32@"; + if(container || profile.compare(0,compute_prefix.size(),compute_prefix)==0){ + auto offset=container?L"0":profile.substr(compute_prefix.size()); + if(offset.empty()||offset.size()>7||offset.find_first_not_of(L"0123456789")!=offset.npos)throw std::runtime_error("invalid compute entry"); + start=Clock::now(); + const auto entry=static_cast(std::stoul(offset)); + bool frontend_hit=false; + CapturedViews views; + if(container)views=read_captured_views(input_path); + auto program=direct?x2w::prepare_direct_compute(input_path,entry,container,cache,frontend_hit,views.contract) + :x2w::translate_compute(x2w::read_compute_request(input_path),entry,false); + report<<"frontend=native_cpp instructions="<7 || offset.find_first_not_of(L"0123456789")!=offset.npos) + throw std::runtime_error("expected entry byte offset"); + start=Clock::now(); + auto program=x2w::replay_group_clear(input_path,static_cast(std::stoul(offset))); + report << "request_and_translation_ms=" << elapsed_ms(start) << '\n'; + for(size_t reg=0;reg(input),{}); + if (input.bad()) throw std::runtime_error("source read failed"); + } + if(graphics){ + bool pixel=profile==L"gfx1013-container-ps"; + if(linked)source=linked->dxil_ir; + else source=x2w::translate_graphics_container(source,pixel).dxil_ir; + profile=pixel?L"ps_6_6":L"vs_6_6"; + } else if (profile == L"gfx1013-direct-constant-ps") { + source=x2w::direct_gfx1013_constant_pixel(source); + profile=L"ps_6_0"; + } else if (profile == L"gfx1013-constant-ps") { + start=Clock::now(); + source=x2w::translate_gfx1013_constant_pixel(source); + report << "translation_ms=" << elapsed_ms(start) << '\n'; + profile=L"ps_6_0"; + } else if (profile == L"gfx1013-vertex-id-vs") { + start=Clock::now(); + source=x2w::translate_gfx1013_vertex_id(source); + report << "translation_ms=" << elapsed_ms(start) << '\n'; + profile=L"vs_6_0"; + } else if (profile == L"gfx1013-buffered-vs") { + start=Clock::now(); + auto program=x2w::translate_gfx1013_buffered_vertex(source); + report << "translation_ms=" << elapsed_ms(start) << '\n' << program.bindings; + source=std::move(program.hlsl); + profile=L"vs_6_0"; + } else if (profile == L"gfx1013-rgb11-r16-ps") { + start=Clock::now(); + auto program=x2w::translate_gfx1013_sampled_pixel(source); + report << "translation_ms=" << elapsed_ms(start) << '\n' << program.bindings; + source=std::move(program.hlsl); + profile=L"ps_6_0"; + } + compile_source(compiler,source,profile,destination,cache,direct,report); + return manifest; +} + +// Outputs of concurrent jobs must be independent. Compare Windows paths +// case-insensitively, including junctions in their parent directories. +struct PathLess { + bool operator()(const fs::path& a, const fs::path& b) const { + return CompareStringOrdinal(a.c_str(),-1,b.c_str(),-1,TRUE)==CSTR_LESS_THAN; + } +}; + +static std::string collapse_ascii_line(std::string_view text) { + std::string out; + out.reserve(text.size()); + bool space = true; + for (unsigned char c : text) { + if (c == '\r' || c == '\n' || c == '\t' || c == ' ') { + if (!space) { + out.push_back(' '); + space = true; + } + } else { + out.push_back(static_cast(c)); + space = false; + } + } + if (!out.empty() && out.back() == ' ') + out.pop_back(); + return out; +} + +static std::string format_fail_line(std::string_view message) { + std::string out = collapse_ascii_line(message); + if (out.empty()) + out = "unknown refusal"; + out.push_back('\n'); + return out; +} + +static bool is_ident_char(unsigned char c) { return std::isalnum(c) != 0 || c == '_'; } + +static std::string normalize_refusal_reason(std::string_view raw) { + std::string s = collapse_ascii_line(raw); + if (s.rfind("native compute +0x", 0) == 0) { + const size_t colon = s.find(": "); + if (colon != std::string::npos) + s.erase(0, colon + 2); + } + auto replace_all_with = [](std::string& str, auto&& matcher) { + std::string out; + out.reserve(str.size()); + size_t i = 0; + while (i < str.size()) { + size_t end = 0; + std::string rep; + if (matcher(str, i, end, rep)) { + out += rep; + i = end; + } else { + out.push_back(str[i++]); + } + } + str.swap(out); + }; + replace_all_with(s, [](const std::string& str, size_t i, size_t& end, std::string& rep) { + if (i + 2 >= str.size() || str[i] != '0' || (str[i + 1] != 'x' && str[i + 1] != 'X')) + return false; + if (i > 0 && is_ident_char(static_cast(str[i - 1]))) + return false; + size_t j = i + 2; + while (j < str.size() && std::isxdigit(static_cast(str[j]))) + ++j; + if (j == i + 2) + return false; + if (j < str.size() && (str[j] == 'u' || str[j] == 'U') && + (j + 1 == str.size() || !is_ident_char(static_cast(str[j + 1])))) + ++j; + end = j; + rep = "0xN"; + return true; + }); + for (const std::string_view prefix : {" at byte ", " VGPR "}) { + replace_all_with(s, [&](const std::string& str, size_t i, size_t& end, std::string& rep) { + if (str.compare(i, prefix.size(), prefix) != 0) + return false; + size_t j = i + prefix.size(); + if (j >= str.size() || !std::isdigit(static_cast(str[j]))) + return false; + while (j < str.size() && std::isdigit(static_cast(str[j]))) + ++j; + if (j < str.size() && is_ident_char(static_cast(str[j]))) + return false; + end = j; + rep = std::string(prefix) + "N"; + return true; + }); + } + replace_all_with(s, [](const std::string& str, size_t i, size_t& end, std::string& rep) { + if (str[i] != 's' && str[i] != 'v') + return false; + if (i > 0 && is_ident_char(static_cast(str[i - 1]))) + return false; + size_t j = i + 1; + if (j < str.size() && str[j] == '[') { + ++j; + const size_t a = j; + while (j < str.size() && std::isdigit(static_cast(str[j]))) + ++j; + if (j == a || j >= str.size() || str[j] != ':') + return false; + const size_t b = ++j; + while (j < str.size() && std::isdigit(static_cast(str[j]))) + ++j; + if (j == b || j >= str.size() || str[j] != ']') + return false; + ++j; + if (j < str.size() && is_ident_char(static_cast(str[j]))) + return false; + end = j; + rep = std::string(1, str[i]) + "[N:N]"; + return true; + } + const size_t a = j; + while (j < str.size() && std::isdigit(static_cast(str[j]))) + ++j; + if (j == a || (j < str.size() && is_ident_char(static_cast(str[j])))) + return false; + end = j; + rep = std::string(1, str[i]) + "N"; + return true; + }); + if (s.empty()) + s = "unknown refusal"; + return s; +} + +static int parse_jobs_count(std::wstring_view number) { + if (number.empty() || number.size() > 2 || number.find_first_not_of(L"0123456789") != number.npos) + throw std::runtime_error("--jobs must be between 1 and 64"); + const int jobs = std::stoi(std::wstring(number)); + if (jobs < 1 || jobs > 64) + throw std::runtime_error("--jobs must be between 1 and 64"); + return jobs; +} + +static std::string json_escape(std::string_view text) { + std::string out; + out.reserve(text.size() + 2); + out.push_back('"'); + for (unsigned char c : text) { + switch (c) { + case '"': out += "\\\""; break; + case '\\': out += "\\\\"; break; + case '\b': out += "\\b"; break; + case '\f': out += "\\f"; break; + case '\n': out += "\\n"; break; + case '\r': out += "\\r"; break; + case '\t': out += "\\t"; break; + default: + if (c < 0x20) { + char buf[8]; + std::snprintf(buf, sizeof(buf), "\\u%04x", c); + out += buf; + } else { + out.push_back(static_cast(c)); + } + break; + } + } + out.push_back('"'); + return out; +} + +static void dedupe_graphics_markers(std::vector& paths) { + // Requires paths to be sorted so a stem's .a immediately precedes its .rtv. + // A key with both markers is one request, the variant, as in gfx2hlsl.py request_source. + for (size_t i = 0; i + 1 < paths.size();) { + if (paths[i].extension() == L".a" && paths[i + 1].extension() == L".rtv" && + paths[i].stem() == paths[i + 1].stem()) + paths.erase(paths.begin() + i); + else + ++i; + } +} + +static std::optional graphics_psin_path(const fs::path& marker) { + if (marker.extension() == L".a") + return fs::path(marker).replace_extension(L".psin"); + if (marker.extension() != L".rtv") + return std::nullopt; + std::ifstream file(marker, std::ios::binary); + if (!file) + return std::nullopt; + char buf[257]{}; + file.read(buf, 256); + const std::string_view text(buf, static_cast(file.gcount())); + if (text.substr(0, 5) != "rtv1 ") + return std::nullopt; + const std::string_view rest = text.substr(5); + const std::string_view token = rest.substr(0, rest.find(' ')); + if (token.empty() || token.size() > 20 || token.find_first_not_of("0123456789") != token.npos) + return std::nullopt; + uint64_t base = 0; + const auto end = token.data() + token.size(); + const auto parsed = std::from_chars(token.data(), end, base); + if (parsed.ec != std::errc{} || parsed.ptr != end) + return std::nullopt; + wchar_t name[32]{}; + std::swprintf(name, std::size(name), L"req_%016llx.psin", static_cast(base)); + return marker.parent_path() / name; +} + +static int run_refusals(int argc, wchar_t** argv) { + fs::path request_dir; + bool has_dir = false; + bool json = false; + int jobs = 1; + try { + for (int i = 2; i < argc; ++i) { + const std::wstring_view arg = argv[i]; + if (arg == L"--json") { + json = true; + } else if (arg == L"--jobs") { + if (i + 1 >= argc) + throw std::runtime_error("missing value for --jobs"); + jobs = parse_jobs_count(argv[++i]); + } else if (!arg.empty() && arg.front() == L'-') { + std::cerr << "usage: compile_dxil --refusals REQUEST_DIRECTORY [--jobs N] [--json]\n"; + return 2; + } else if (has_dir) { + std::cerr << "usage: compile_dxil --refusals REQUEST_DIRECTORY [--jobs N] [--json]\n"; + return 2; + } else { + request_dir = fs::path(arg); + has_dir = true; + } + } + if (!has_dir) { + std::cerr << "usage: compile_dxil --refusals REQUEST_DIRECTORY [--jobs N] [--json]\n"; + return 2; + } + if (!fs::exists(request_dir) || !fs::is_directory(request_dir)) { + std::cerr << "request path must be an existing directory\n"; + return 1; + } + std::vector graphics_inputs, compute_inputs; + for (const auto& file : fs::directory_iterator(request_dir)) { + if (!file.is_regular_file()) + continue; + const auto path = file.path(); + if (path.stem().wstring().rfind(L"req_", 0) != 0) + continue; + if (path.extension() == L".a" || path.extension() == L".rtv") + graphics_inputs.push_back(fs::weakly_canonical(path)); + else if (path.extension() == L".c67") + compute_inputs.push_back(fs::weakly_canonical(path)); + } + std::sort(graphics_inputs.begin(), graphics_inputs.end(), PathLess{}); + dedupe_graphics_markers(graphics_inputs); + std::sort(compute_inputs.begin(), compute_inputs.end(), PathLess{}); + + struct Task { + bool compute; + size_t index; + }; + std::vector tasks; + tasks.reserve(graphics_inputs.size() + compute_inputs.size()); + for (size_t i = 0; i < graphics_inputs.size(); ++i) + tasks.push_back({false, i}); + for (size_t i = 0; i < compute_inputs.size(); ++i) + tasks.push_back({true, i}); + + std::vector results(tasks.size()); + if (!tasks.empty()) { + const int workers_count = (std::min)(jobs, static_cast(tasks.size())); + std::atomic next{}; + auto run_worker = [&]() { + for (size_t t = next++; t < tasks.size(); t = next++) { + const auto& task = tasks[t]; + try { + if (task.compute) { + auto req = x2w::read_compute_request(compute_inputs[task.index]); + (void)x2w::translate_compute(req, 0, true); + } else { + auto input = x2w::read_graphics_request(graphics_inputs[task.index]); + bool hit = false; + auto pair = x2w::prepare_direct_graphics(input.a, input.b, request_dir, hit, + input.root, input.input_layout, input.pixel_entry, + false, input.rtv_formats); + if (!input.rtv_request.empty() && + !x2w::format_graphics_runtime_manifest(pair, input.rtv_request)) + throw std::runtime_error( + "RTV variant has no runtime manifest: its vertex inputs, target types or bindings are not described"); + } + } catch (const fs::filesystem_error&) { + results[t] = "unreadable shader request"; + } catch (const std::exception& error) { + results[t] = normalize_refusal_reason(error.what()); + } + } + }; + if (workers_count == 1) { + run_worker(); + } else { + std::vector> workers; + workers.reserve(workers_count); + for (int w = 0; w < workers_count; ++w) + workers.emplace_back(std::async(std::launch::async, run_worker)); + for (auto& w : workers) + w.get(); + } + } + + struct Section { + unsigned examined = 0, no_refusal = 0, refused = 0; + std::map counts; + std::vector> sorted_reasons() const { + std::vector> rows(counts.begin(), counts.end()); + std::sort(rows.begin(), rows.end(), [](const auto& a, const auto& b) { + if (a.second != b.second) + return a.second > b.second; + return a.first < b.first; + }); + return rows; + } + } graphics_sec, compute_sec; + + for (size_t t = 0; t < tasks.size(); ++t) { + Section& sec = tasks[t].compute ? compute_sec : graphics_sec; + ++sec.examined; + if (results[t].empty()) { + ++sec.no_refusal; + } else { + ++sec.refused; + ++sec.counts[results[t]]; + } + } + + if (json) { + auto write_json_sec = [](std::ostream& os, const Section& sec) { + os << "{\"examined\":" << sec.examined + << ",\"no_refusal\":" << sec.no_refusal + << ",\"refused\":" << sec.refused + << ",\"reasons\":["; + const auto rows = sec.sorted_reasons(); + for (size_t i = 0; i < rows.size(); ++i) { + if (i) os << ','; + os << "{\"reason\":" << json_escape(rows[i].first) << ",\"count\":" << rows[i].second << '}'; + } + os << "]}"; + }; + std::cout << "{\"graphics\":"; + write_json_sec(std::cout, graphics_sec); + std::cout << ",\"compute\":"; + write_json_sec(std::cout, compute_sec); + std::cout << "}\n"; + } else { + auto write_text_sec = [](std::ostream& os, const char* title, const char* count_label, const Section& sec) { + os << title << '\n' + << count_label << ": " << sec.examined << '\n' + << "No refusal recorded (not compiled): " << sec.no_refusal << '\n' + << "Refused: " << sec.refused << '\n' + << "Count\tReason\n"; + for (const auto& [reason, count] : sec.sorted_reasons()) + os << count << '\t' << reason << '\n'; + }; + write_text_sec(std::cout, "Graphics requests", "Requests examined", graphics_sec); + write_text_sec(std::cout, "Compute requests (device slot 67)", "Compute requests examined", compute_sec); + } + return 0; + } catch (const fs::filesystem_error&) { + std::cerr << "unreadable shader request directory\n"; + return 1; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} + +static bool is_lower_hex16(std::wstring_view text) { + if (text.size() != 16) + return false; + for (wchar_t c : text) + if (!((c >= L'0' && c <= L'9') || (c >= L'a' && c <= L'f'))) + return false; + return true; +} + +static int parse_interval_ms(std::wstring_view number) { + if (number.empty() || number.size() > 5 || number.find_first_not_of(L"0123456789") != number.npos) + throw std::runtime_error("--interval must be between 10 and 60000 ms"); + const int ms = std::stoi(std::wstring(number)); + if (ms < 10 || ms > 60000) + throw std::runtime_error("--interval must be between 10 and 60000 ms"); + return ms; +} + +static bool has_complete_dxbc(const fs::path& path) { + std::error_code ec; + const auto actual = fs::file_size(path, ec); + if (ec || actual < 32 || actual > (256ull << 20)) + return false; + std::ifstream file(path, std::ios::binary); + if (!file) + return false; + unsigned char header[32]{}; + if (!file.read(reinterpret_cast(header), sizeof(header))) + return false; + if (std::memcmp(header, "DXBC", 4) != 0) + return false; + uint32_t total = 0, parts = 0; + std::memcpy(&total, header + 24, sizeof(total)); + std::memcpy(&parts, header + 28, sizeof(parts)); + return total == actual && parts > 0 && parts <= (total - 32) / 4; +} + +struct WatchRequest { + std::wstring key; + fs::path marker; + bool compute = false; +}; + +static bool is_watch_request_pending(const fs::path& request_dir, const WatchRequest& req, bool skip_failed) { + std::error_code ec; + const auto marker_mtime = fs::last_write_time(req.marker, ec); + if (ec) + return false; + const fs::path stem = request_dir / req.key; + const fs::path manifest_path = fs::path(stem) += L".txt"; + const fs::path fail_path = fs::path(stem) += L".fail"; + const fs::path psdep_path = fs::path(stem) += L".psdep"; + + std::optional psin_mtime; + bool lost = false; + if (!req.compute) { + if (const auto psin_path = graphics_psin_path(req.marker)) { + if (fs::is_regular_file(*psin_path, ec)) { + const auto t = fs::last_write_time(*psin_path, ec); + if (!ec) + psin_mtime = t; + } + lost = !psin_mtime.has_value() && fs::is_regular_file(psdep_path, ec); + } + } + + const bool has_manifest = fs::is_regular_file(manifest_path, ec); + if (has_manifest && !lost) { + const auto manifest_mtime = fs::last_write_time(manifest_path, ec); + if (!ec && !(psin_mtime.has_value() && *psin_mtime > manifest_mtime)) { + if (req.compute) { + if (has_complete_dxbc(fs::path(stem) += L".cs.cso")) + return false; + } else { + if (has_complete_dxbc(fs::path(stem) += L".vs.cso") && + has_complete_dxbc(fs::path(stem) += L".ps.cso")) + return false; + } + } + } + + const bool recheck = lost && has_manifest; + if (skip_failed && !recheck && fs::is_regular_file(fail_path, ec)) { + const auto fail_mtime = fs::last_write_time(fail_path, ec); + const auto latest_input = + (psin_mtime.has_value() && *psin_mtime > marker_mtime) ? *psin_mtime : marker_mtime; + if (!ec && fail_mtime >= latest_input) + return false; + } + return true; +} + +static std::vector collect_watch_requests(const fs::path& request_dir, bool skip_failed) { + std::vector found; + for (const auto& file : fs::directory_iterator(request_dir)) { + std::error_code ec; + if (!file.is_regular_file(ec)) + continue; + const auto path = file.path(); + const auto ext = path.extension().wstring(); + const bool is_compute = ext == L".c67"; + if (!is_compute && ext != L".a" && ext != L".rtv") + continue; + const auto stem = path.stem().wstring(); + if (stem.size() != 20 || stem.rfind(L"req_", 0) != 0) + continue; + const auto key = stem.substr(4); + if (!is_lower_hex16(key)) + continue; + found.push_back({key, fs::weakly_canonical(path), is_compute}); + } + std::sort(found.begin(), found.end(), [](const WatchRequest& a, const WatchRequest& b) { + return PathLess{}(a.marker, b.marker); + }); + for (size_t i = 0; i + 1 < found.size();) { + if (!found[i].compute && !found[i + 1].compute && found[i].marker.extension() == L".a" && + found[i + 1].marker.extension() == L".rtv" && found[i].key == found[i + 1].key) + found.erase(found.begin() + i); + else + ++i; + } + std::vector pending; + for (auto& req : found) { + if (is_watch_request_pending(request_dir, req, skip_failed)) + pending.push_back(std::move(req)); + } + return pending; +} + +static const char* compile_watch_item(x2w::ShaderDxilCompiler& compiler, const fs::path& cache_dir, + const fs::path& request_dir, const WatchRequest& req) { + const fs::path stem = request_dir / req.key; + const fs::path manifest_path = fs::path(stem) += L".txt"; + const fs::path fail_path = fs::path(stem) += L".fail"; + std::error_code ignored; + fs::remove(manifest_path, ignored); + std::ostringstream sink; + if (req.compute) { + bool hit = false; + auto program = x2w::prepare_direct_compute(req.marker, 0, false, cache_dir, hit, x2w::HeapViewContract::none); + auto manifest = x2w::format_compute_runtime_manifest(program); + if (!manifest) + throw std::runtime_error("unsupported startup runtime manifest bindings"); + auto cs_dxil = compile_to_dxil(compiler, program.dxil_ir, L"cs_6_6", cache_dir, true, sink); + publish_atomic(fs::path(stem) += L".cs.cso", cs_dxil.data(), cs_dxil.size()); + publish_atomic(manifest_path, manifest->data(), manifest->size()); + fs::remove(fail_path, ignored); + return "compiled compute"; + } + auto input = x2w::read_graphics_request(req.marker); + bool hit = false; + auto pair = x2w::prepare_direct_graphics(input.a, input.b, cache_dir, hit, input.root, input.input_layout, + input.pixel_entry, true, input.rtv_formats); + auto manifest = x2w::format_graphics_runtime_manifest(pair, input.rtv_request); + if (!manifest) + throw std::runtime_error( + input.rtv_request.empty() + ? "unsupported startup runtime manifest bindings" + : "RTV variant has no runtime manifest: its vertex inputs, target types or bindings are not described"); + auto vs_dxil = compile_to_dxil(compiler, pair.vertex.dxil_ir, L"vs_6_6", cache_dir, true, sink); + auto ps_dxil = compile_to_dxil(compiler, pair.pixel.dxil_ir, L"ps_6_6", cache_dir, true, sink); + publish_atomic(fs::path(stem) += L".vs.cso", vs_dxil.data(), vs_dxil.size()); + publish_atomic(fs::path(stem) += L".ps.cso", ps_dxil.data(), ps_dxil.size()); + const fs::path psdep_path = fs::path(stem) += L".psdep"; + if (!input.pixel_input_description.empty()) + publish_atomic(psdep_path, input.pixel_input_description.data(), input.pixel_input_description.size()); + else + fs::remove(psdep_path, ignored); + publish_atomic(manifest_path, manifest->data(), manifest->size()); + fs::remove(fail_path, ignored); + return "compiled graphics"; +} + +static int run_watch(int argc, wchar_t** argv) { + fs::path sdk_dir, cache_dir, request_dir; + int positional = 0; + int jobs = 1; + int interval_ms = 2000; + bool once = false; + auto usage = []() { + std::cerr << "usage: compile_dxil --watch SDK_DIRECTORY CACHE_DIRECTORY REQUEST_DIRECTORY " + "[--jobs N] [--interval MS] [--once]\n"; + return 2; + }; + try { + for (int i = 2; i < argc; ++i) { + const std::wstring_view arg = argv[i]; + if (arg == L"--once") { + once = true; + } else if (arg == L"--jobs") { + if (i + 1 >= argc) + throw std::runtime_error("missing value for --jobs"); + jobs = parse_jobs_count(argv[++i]); + } else if (arg == L"--interval") { + if (i + 1 >= argc) + throw std::runtime_error("missing value for --interval"); + interval_ms = parse_interval_ms(argv[++i]); + } else if (!arg.empty() && arg.front() == L'-') { + return usage(); + } else { + if (positional == 0) sdk_dir = fs::path(arg); + else if (positional == 1) cache_dir = fs::path(arg); + else if (positional == 2) request_dir = fs::path(arg); + else return usage(); + ++positional; + } + } + if (positional != 3) + return usage(); + if (!fs::exists(sdk_dir) || !fs::is_directory(sdk_dir)) { + std::cerr << "SDK path must be an existing directory\n"; + return 1; + } + if (!fs::exists(request_dir) || !fs::is_directory(request_dir)) { + std::cerr << "request path must be an existing directory\n"; + return 1; + } + request_dir = fs::weakly_canonical(request_dir); + fs::create_directories(cache_dir); + cache_dir = fs::weakly_canonical(cache_dir); + + x2w::ShaderDxilCompiler coordinator(sdk_dir); + bool skip_failed = false; + while (true) { + std::vector pending; + try { + pending = collect_watch_requests(request_dir, skip_failed); + } catch (const fs::filesystem_error& error) { + if (once) + throw; + std::cerr << "watch scan error, retrying: " << error.what() << '\n'; + std::this_thread::sleep_for(std::chrono::milliseconds(interval_ms)); + continue; + } + if (!pending.empty()) { + std::vector outcomes(pending.size()); + auto process_item = [&](x2w::ShaderDxilCompiler& compiler, size_t idx) { + const auto& req = pending[idx]; + try { + outcomes[idx] = compile_watch_item(compiler, cache_dir, request_dir, req); + } catch (const std::exception& error) { + const std::string line = format_fail_line(error.what()); + try { + publish_atomic((request_dir / req.key) += L".fail", line.data(), line.size()); + } catch (...) { + } + std::string summary = line; + if (!summary.empty() && summary.back() == '\n') + summary.pop_back(); + outcomes[idx] = "refused: " + summary; + } + }; + const int worker_count = (std::min)(jobs, static_cast(pending.size())); + if (worker_count <= 1) { + for (size_t idx = 0; idx < pending.size(); ++idx) + process_item(coordinator, idx); + } else { + std::atomic next{}; + std::vector> workers; + workers.reserve(worker_count); + for (int w = 0; w < worker_count; ++w) { + workers.emplace_back(std::async(std::launch::async, [&]() { + auto compiler = coordinator.new_worker(); + for (size_t idx = next++; idx < pending.size(); idx = next++) + process_item(compiler, idx); + })); + } + for (auto& w : workers) + w.get(); + } + for (size_t idx = 0; idx < pending.size(); ++idx) { + std::string key_ascii; + key_ascii.reserve(pending[idx].key.size()); + for (wchar_t ch : pending[idx].key) + key_ascii.push_back(static_cast(ch)); + std::cout << key_ascii << ": " << outcomes[idx] << '\n'; + } + std::cout.flush(); + } + if (once) + return 0; + skip_failed = true; + std::this_thread::sleep_for(std::chrono::milliseconds(interval_ms)); + } + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} + +int wmain(int argc, wchar_t** argv) { + if (argc >= 2 && std::wstring_view(argv[1]) == L"--watch") + return run_watch(argc, argv); + if (argc >= 2 && std::wstring_view(argv[1]) == L"--refusals") + return run_refusals(argc, argv); + if (argc == 4 && std::wstring_view(argv[1]) == L"--index-graphics-interfaces") { + try { + const auto stages = x2w::index_graphics_interfaces(argv[2],argv[3]); + std::cout << "indexed_graphics_containers=" << stages << "\n"; + return 0; + } catch (const std::exception &error) { + std::cerr << error.what() << "\n"; + return 1; + } + } + const bool parallel = argc > 3 && std::wstring_view(argv[3]) == L"--jobs"; + const int profile_index = parallel ? 5 : 3; + const int first = profile_index+1; + const bool directory = argc > first && std::wstring_view(argv[first]) == L"--requests"; + if (directory ? argc != first+3 : (argc < first+2 || (argc-first)%2)) { + std::cerr << "usage: compile_dxil SDK_DIRECTORY CACHE_DIRECTORY [--jobs N] PROFILE INPUT OUTPUT.cso [INPUT OUTPUT ...]\n" + "Use a DXC profile for HLSL, gfx1013-constant-ps or gfx1013-rgb11-r16-ps for a raw pixel program, or\n" + "gfx1013-vertex-id-vs or gfx1013-buffered-vs for a raw vertex program. gfx1013-sampled-pair takes one VS and one PS (in order).\n" + "gfx1013-buffered-pair takes a buffered vertex program and a pixel HLSL source.\n" + "gfx1013-group-clear@BYTE_OFFSET and gfx1013-compute-wave32@BYTE_OFFSET take a req_.c67.\n" + "Direct DXIL profiles: gfx1013-direct-cs@BYTE_OFFSET, gfx1013-container-cs, gfx1013-container-vs, gfx1013-container-ps.\n" + "gfx1013-container-cs reads an optional req_.views next to the .cdx (GPU-selected heap slot view types).\n" + "gfx1013-container-pair accepts two containers and emits VS then PS using the runtime register allocation.\n" + "For capture directories use PROFILE --requests DIRECTORY OUTPUT_DIRECTORY. " + "gfx1013-container-pair also takes each req_.rtv (rtv1 BASE_KEY FORMAT ...) and publishes it under its key.\n" + "gfx1013-container-rect also emits the rectangle geometry stage.\n" + "Use --refusals REQUEST_DIRECTORY [--jobs N] [--json] for a read-only refusal summary.\n" + "Use --watch SDK_DIRECTORY CACHE_DIRECTORY REQUEST_DIRECTORY [--jobs N] [--interval MS] [--once] to translate pending requests.\n" + "Use --index-graphics-interfaces REVIEWED_DIRECTORY CACHE_DIRECTORY to index native graphics interfaces.\n"; + return 2; + } + try { + const std::wstring_view profile = argv[profile_index]; + const bool rectangles=profile==L"gfx1013-container-rect"; + if(rectangles && !directory) throw std::runtime_error("rectangle compilation takes a graphics request directory"); + const bool direct_pair = profile == L"gfx1013-container-pair" || rectangles; + const bool graphics_batch = directory && direct_pair; + const bool compute_request = profile.rfind(L"gfx1013-group-clear@",0)==0 || + profile.rfind(L"gfx1013-compute-wave32@",0)==0 || profile.rfind(L"gfx1013-direct-cs@",0)==0 || profile==L"gfx1013-container-cs"; + std::vector inputs, outputs, stems; + if (directory) { + if (!compute_request && !graphics_batch) throw std::runtime_error("profile does not take capture directories"); + const auto extension = graphics_batch ? L".a" : profile == L"gfx1013-container-cs" ? L".cdx" : L".c67"; + for (const auto& file : fs::directory_iterator(argv[first+1])) { + const auto path = file.path(); + // An RTV variant (req_.rtv) is a request of its own, translated from its base request's parts. + const bool marker = path.extension()==extension || (graphics_batch && !rectangles && path.extension()==L".rtv"); + if (file.is_regular_file() && marker && path.stem().wstring().rfind(L"req_",0)==0) + inputs.push_back(fs::weakly_canonical(path)); + } + if (inputs.empty()) throw std::runtime_error("no ready shader requests"); + std::sort(inputs.begin(),inputs.end()); + dedupe_graphics_markers(inputs); + fs::create_directories(argv[first+2]); + for (const auto& path : inputs) { + auto key_stem = path.stem().wstring().substr(4); + if (key_stem.empty()) key_stem = L"_invalid"; + stems.push_back(fs::weakly_canonical(fs::path(argv[first+2]) / key_stem)); + outputs.push_back(fs::path(stems.back()) += (graphics_batch ? L".vs.cso" : L".cs.cso")); + } + } else { + for(int i=first;i(inputs.size()); + const bool sampled_pair = std::wstring_view(argv[profile_index]) == L"gfx1013-sampled-pair"; + const bool buffered_pair = std::wstring_view(argv[profile_index]) == L"gfx1013-buffered-pair"; + if (!directory && (direct_pair || sampled_pair || buffered_pair) && count != 2) throw std::runtime_error("graphics pair requires a vertex and a pixel job"); + std::optional linked; + if (direct_pair && !directory) { + bool hit = false; + linked = x2w::prepare_direct_graphics(x2w::read_shader_container_bytes(inputs[0]), + x2w::read_shader_container_bytes(inputs[1]), argv[2], hit); + std::cout << "graphics_pair frontend_cache_hit=" << hit << "\n"; + } + auto linked_stage=[&](int index)->const x2w::NativeComputeShader*{ + if(!linked)return nullptr; + return index?&linked->pixel:&linked->vertex; + }; + const auto job_profile = [&](int index) -> const wchar_t* { + if(direct_pair)return index?L"gfx1013-container-ps":L"gfx1013-container-vs"; + if (sampled_pair) return index == 0 ? L"gfx1013-vertex-id-vs" : L"gfx1013-rgb11-r16-ps"; + if (buffered_pair) return index == 0 ? L"gfx1013-buffered-vs" : L"ps_6_0"; + return argv[profile_index]; + }; + int jobs=1; + if (parallel) + jobs = (std::min)(parse_jobs_count(argv[4]), count); + auto start=Clock::now(); + std::set occupied(inputs.begin(),inputs.end()); + if(compute_request) { + for(const auto& input : inputs) { + for(auto suffix : {L".root",L".data",L".sa",L".sb",L".desc",L".views"}) + occupied.insert(fs::weakly_canonical(fs::path(input).replace_extension(suffix))); + } + } + if(graphics_batch) { + for(const auto& input : inputs) { + for(auto suffix : {L".b",L".root",L".ia",L".psin"}) + occupied.insert(fs::weakly_canonical(fs::path(input).replace_extension(suffix))); + } + } + auto reserve_output = [&](const fs::path& path) { + if(!occupied.insert(path).second) + throw std::runtime_error("parallel outputs must be distinct from all inputs and other outputs"); + }; + for(int i=0;idata(), manifest->size()); + fs::remove(fs::path(stems[i]) += L".fail", ignored); + return; + } + const fs::path manifest_path = fs::path(stems[i]) += L".txt"; + const fs::path psdep_path = fs::path(stems[i]) += L".psdep"; + std::error_code ignored; + fs::remove(manifest_path, ignored); + auto input = x2w::read_graphics_request(inputs[i]); + bool hit = false; + auto pair = x2w::prepare_direct_graphics(input.a, input.b, argv[2], hit, input.root, input.input_layout, input.pixel_entry, + true, input.rtv_formats); + report << "graphics_pair frontend_cache_hit=" << hit << '\n'; + if (!input.rtv_request.empty()) { + report << "rtv_variant " << input.rtv_request << " types="; + for (size_t t = 0; t < input.rtv_formats.size(); ++t) + report << (t ? "," : "") << (pair.target_components[t] == 5 ? "u32" : pair.target_components[t] == 4 ? "i32" : "f32"); + report << '\n'; + } + auto manifest = rectangles ? std::nullopt : x2w::format_graphics_runtime_manifest(pair, input.rtv_request); + // A base pair without a manifest still publishes its stages. A variant is of use to the runtime only. + if (!manifest && !input.rtv_request.empty()) + throw std::runtime_error("RTV variant has no runtime manifest: its vertex inputs, target types or bindings are not described"); + std::vector gs_dxil; + if (rectangles) { + auto ir=x2w::native_rectangle_geometry(pair.vertex.outputs,pair.pixel.inputs); + gs_dxil = compile_to_dxil(compiler, ir, L"gs_6_6", argv[2], true, report); + } + auto vs_dxil = compile_to_dxil(compiler, pair.vertex.dxil_ir, L"vs_6_6", argv[2], true, report); + auto ps_dxil = compile_to_dxil(compiler, pair.pixel.dxil_ir, L"ps_6_6", argv[2], true, report); + if (rectangles) + publish_atomic(fs::path(stems[i]) += L".gs.cso", gs_dxil.data(), gs_dxil.size()); + publish_atomic(outputs[i], vs_dxil.data(), vs_dxil.size()); + publish_atomic(fs::path(stems[i]) += L".ps.cso", ps_dxil.data(), ps_dxil.size()); + if (manifest) { + if (!input.pixel_input_description.empty()) + publish_atomic(psdep_path, input.pixel_input_description.data(), input.pixel_input_description.size()); + publish_atomic(manifest_path, manifest->data(), manifest->size()); + } + fs::remove(fs::path(stems[i]) += L".fail", ignored); + }; + if(jobs==1 && !directory) { + x2w::ShaderDxilCompiler compiler(argv[1]); + std::cout << "compiler_init_ms=" << elapsed_ms(start) << '\n'; + for(int i=0;i next{}; + std::vector reports(count), errors(count); + x2w::ShaderDxilCompiler coordinator(argv[1]); + std::cout << "compiler_init_ms=" << elapsed_ms(start) << '\n'; + std::vector> workers; + for(int w=0;w=0) { report << "worker_init_ms=" << init_ms << '\n'; init_ms=-1; } + try { compile_job(compiler, i, report); } + catch(const std::exception& error) { + errors[i]=error.what(); + if (directory) { + try { + const auto line = format_fail_line(errors[i]); + publish_atomic(fs::path(stems[i]) += L".fail", line.data(), line.size()); + } catch (...) { + } + } + } + reports[i]=report.str(); + } + })); + } + for(auto& worker:workers) worker.get(); + int rejected=0; + for(int i=0;i= 255 or 128 <= src0 <= 208: + # Leave the frontend's operand and register-liveness checks in place. + self.u(args[1]) + self.u(args[2]) + self.record_v_write(int(args[0][1:])) + raw = f'{word:08x}' + if src0 == 255: + literal, = struct.unpack_from('>16)' if packed else f'uint2({address},{self.u(f"v{y}")})' + uav = self.pipe.uav(self.pipe.feedback, 'tex2d') + if writing: + values = ','.join(self.u(f'v{i}') for i in range(lo,hi+1)) + self.emit(f'if(exec&1u) {uav}[{coord}]=asfloat(uint4({values}));') + else: + self.emit(f't={uav}[{coord}];') + for i in range(3): + self.set_v(lo+i,'asuint(t.'+'xyz'[i]+')') + return + return super().lower(op,asm,args,mods) + + def body(self): + # A barrier can be emitted outside per-wave control only when all paths + # from entry pass through its block. Reject loops in this frontend. + index = {offset:i for i,(offset,_,_) in enumerate(self.blocks)} + successors = [] + for i,(_,_,term) in enumerate(self.blocks): + if not term: + dest = [i+1] + elif term[0] == 'end': + dest = [] + elif term[0] == 'jump': + dest = [index[term[1]]] + elif term[0] == 'branch': + dest = [i+1,index[term[2]]] + else: + raise gfx.Unsupported('unsupported compute branch') + if any(not i < d < len(index) for d in dest): + raise gfx.Unsupported('native LDS requires forward control flow') + successors.append(dest) + post = {} + for i in reversed(range(len(index))): + dest = successors[i] + post[i] = {i} | (set.intersection(*(post[j] for j in dest)) if dest else set()) + + lines = ['uint pc=0;'] + for i,(_,statements,term) in enumerate(self.blocks): + guard = f'if(pc=={i}u){{' + lines.append(guard) + for statement in statements: + if statement == 'GroupMemoryBarrierWithGroupSync();': + if i not in post[0]: + raise gfx.Unsupported('workgroup barrier is conditional') + lines.extend(['}',statement,guard]) + else: + lines.append(statement) + dest = successors[i] + if len(dest) == 2: + cond = term[1] + for mask in ('exec','vcc'): + for op,neg in [('==','!'),('!=','')]: + if cond == f'({mask} & 1) {op} 0': + cond = f'{neg}WaveActiveAnyTrue(({mask}&1u)!=0u)' + lines.append(f'pc=({cond})?{dest[1]}u:{dest[0]}u;') + else: + lines.append(f'pc={dest[0] if dest else len(index)}u;') + lines.append('}') + return lines + + +class ComputePipeline(gfx.ComputePipeline): + stage_type = ComputeStage + + def __init__(self, *args, feedback, **kwargs): + self.feedback = feedback + super().__init__(*args, **kwargs) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('marker',type=Path) + parser.add_argument('output',type=Path) + parser.add_argument('--compiler',required=True,type=Path) + parser.add_argument('--sdk',required=True,type=Path) + parser.add_argument('--cache',required=True,type=Path) + parser.add_argument('--rw-image',required=True,nargs=2,type=int,metavar=('PARAM','BYTE_OFFSET')) + parser.add_argument('--wave-size',required=True,type=int,choices=[32,64]) + args = parser.parse_args() + name = args.marker.name + if not re.fullmatch(r'req_[0-9a-f]{16}\.c67',name): + parser.error('expected req_<16 hex digits>.c67') + key = int(name[4:20],16) + param,off = args.rw_image + if param < 0 or off < 0 or off%32: + parser.error('expected a nonnegative parameter and a 32-byte-aligned descriptor offset') + args.output.mkdir(parents=True,exist_ok=True) + with TemporaryDirectory(dir=args.output) as temp: + bundle = Path(temp)/'bundle' + request = bundle/'request' + request.mkdir(parents=True) + for ext in ('.c67','.root','.data','.desc','.sa','.sb'): + path = args.marker.with_suffix(ext) + shutil.copyfile(path,request/path.name) + pipeline = gfx.load_compute_request(str(request),key, + pipeline_type=partial(ComputePipeline,feedback=(('table',param),off))) + source = pipeline.hlsl_cs().replace('[numthreads(',f'[WaveSize({args.wave_size})]\n[numthreads(') + stage = bundle/f'{key:016x}.cs.hlsl' + stage.write_text(source,encoding='utf-8') + bytecode = stage.with_suffix('.cso') + subprocess.run([args.compiler,args.sdk,args.cache,'cs_6_6',stage,bytecode],check=True) + manifest = bundle/f'{key:016x}.txt' + manifest.write_text(pipeline.manifest(),encoding='utf-8') + metadata = {'schema':1,'request':f'request/{name}','profile':'cs_6_6','rw_image':[param,off], + 'wave_size':args.wave_size,'sha256':{}} + for path in sorted(bundle.rglob('*')): + if path.is_file(): + metadata['sha256'][path.relative_to(bundle).as_posix()] = hashlib.sha256(path.read_bytes()).hexdigest() + replay = json.dumps(metadata,indent=2,sort_keys=True)+'\n' + (bundle/'replay.json').write_bytes(replay.encode()) + dest = args.output/f'{key:016x}-{hashlib.sha256(replay.encode()).hexdigest()}' + try: + bundle.rename(dest) + except OSError: + if not dest.is_dir() or (dest/'replay.json').read_bytes()!=replay.encode(): + raise + for relative,digest in metadata['sha256'].items(): + if hashlib.sha256((dest/relative).read_bytes()).hexdigest()!=digest: + raise RuntimeError(f'damaged replay artifact {relative}') + print(dest) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/compile_sampled_pixel_request.py b/tools/startup/compile_sampled_pixel_request.py new file mode 100644 index 000000000..30c2a3bf3 --- /dev/null +++ b/tools/startup/compile_sampled_pixel_request.py @@ -0,0 +1,134 @@ +"""Compile a captured graphics request as a matched desktop SM6 pair.""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import subprocess +from tempfile import TemporaryDirectory + +import gfx2hlsl as gfx + + +def bindings(lines, sampler_tags): + resources = [] + samplers = [] + for line in lines: + words = line.split() + if words[:1] == ['srv']: + resources.append(words) + if words and words[0] in sampler_tags: + samplers.append(tuple(int(word, 0) for word in words[1:])) + return resources, samplers + + +def write_program(path, container): + raw = gfx.strip_header(container) + instructions = gfx.decode(raw) + if not instructions or instructions[-1][2] != 's_endpgm': + raise ValueError('missing program boundary') + end, size, _, _ = instructions[-1] + path.write_bytes(raw[:end + size]) + return len(container) - len(raw) + + +def build(marker, dest, compiler, sdk, cache, buffered_vertex=False): + match = re.fullmatch(r'req_([0-9a-f]{16})\.rtv', marker.name) + if not match: + raise ValueError('expected a req_<16 hex digits>.rtv marker') + variant = int(match[1], 16) + request = marker.read_bytes() + parsed = re.fullmatch(rb'rtv1 ([0-9]{1,20}) ' + (b'10' if buffered_vertex else b'26 54'), request) + if not parsed or gfx.fnv(request) != variant: + raise ValueError('expected a matching ' + ('RGBA16_FLOAT' if buffered_vertex else 'R11G11B10_FLOAT / R16_FLOAT') + ' request') + base = int(parsed[1]) + stem = f'req_{base:016x}' + dest.mkdir(parents=True, exist_ok=True) + with TemporaryDirectory(dir=dest) as temp: + bundle = Path(temp) / 'bundle' + inputs = bundle / 'request' + inputs.mkdir(parents=True) + (inputs / marker.name).write_bytes(request) + pieces = [] + for suffix in ('.a', '.b', '.root', '.ia'): + path = marker.with_name(stem + suffix) + if suffix == '.ia' and not path.exists(): + continue + data = path.read_bytes() + pieces.append(data) + (inputs / path.name).write_bytes(data) + if gfx.pipeline_key(*pieces) != base: + raise ValueError('graphics stage, root or input layout key mismatch') + stages, root, formats, rtv, fetch, _, attr_map = gfx.load_request(str(inputs), variant) + if any(blob.startswith(b'DXBC') for blob in pieces[:2]) or fetch is not None or attr_map is not None or len(pieces) != 3: + raise ValueError('this profile requires the raw two-table graphics interface') + tables = [{'type': 0, 'vis': 0}] * 2 + if gfx.parse_root(root) != {'flags': 1, 'params': tables}: + raise ValueError('unexpected graphics root layout') + pair = gfx.Pipeline(stages['vs'], stages['ps'], root, sampler_heap=False, rtv_formats=formats) + manifest = pair.manifest() + if pair.params != ([0, 1] if buffered_vertex else [0]) or pair.flat or pair.notes or pair.lod_unvalidated: + raise ValueError('unsupported vertex parameters or unverified binding manifest') + name = match[1] + ps = bundle / (name + '.ps.bin') + ps_offset = write_program(ps, stages['ps']) + vs = bundle / (name + '.vs.bin') + vs_offset = write_program(vs, stages['vs']) + entry = ['udsrc 0 rect', 'udsrc 1 basevertex', 'udsrc 2 startinstance'] + if buffered_vertex: + entry.append('udsrc 3 stride 0') + if manifest.splitlines()[1:len(entry)+2] != [f'ud {len(entry)}', *entry]: + raise ValueError('unexpected vertex entry constants') + pixel_source = ps + if buffered_vertex: + pixel_source = bundle / (name + '.ps.hlsl') + pixel_source.write_text(pair.hlsl_ps(), encoding='utf-8') + batch = 'gfx1013-buffered-pair' if buffered_vertex else 'gfx1013-sampled-pair' + result = subprocess.run([compiler, sdk, cache, '--jobs', '2', batch, + vs, bundle / (name + '.vs.cso'), pixel_source, bundle / (name + '.ps.cso')], + check=True, text=True, stdout=subprocess.PIPE) + print(result.stdout, end='') + actual = bindings(result.stdout.splitlines(), {'sampler'}) + expected = bindings(manifest.splitlines(), {'smp', 'smpl'}) + if buffered_vertex: + rows, _ = actual + if not rows or rows != expected[0][:len(rows)]: + raise ValueError('native vertex buffer registers disagree with paired graphics manifest') + elif actual != expected: + raise ValueError('native pixel bindings disagree with paired graphics manifest') + (bundle / (name + '.txt')).write_text(manifest + rtv + '\n', encoding='utf-8') + metadata = {'profile': 'gfx1013-rgb11-r16-ps', 'request': 'request/' + marker.name, + 'pixel_offset': ps_offset, 'pixel_bytes': ps.stat().st_size, + 'vertex_profile': 'gfx1013-vertex-id-vs', 'vertex_offset': vs_offset, 'vertex_bytes': vs.stat().st_size, + 'entry': {'table_sgprs': [8, 9], 'primitive_mask_sgpr': 10, + 'perspective_center_vgprs': [0, 1], 'attr0': 'PARAM0'}, + 'rtv_formats': list(formats), + 'sha256': {file.relative_to(bundle).as_posix(): hashlib.sha256(file.read_bytes()).hexdigest() + for file in sorted(bundle.rglob('*')) if file.is_file()}} + if buffered_vertex: + metadata.update(profile='ps_6_0', vertex_profile='gfx1013-buffered-vs', + entry={'vertex_table_sgprs': [0, 1], 'base_vertex_sgpr': 2, 'root_table_sgprs': [8, 9], + 'vertex_stride_word': 3, 'pixel_frontend': 'gfx2hlsl'}) + record = json.dumps(metadata, indent=2, sort_keys=True).encode() + b'\n' + (bundle / 'replay.json').write_bytes(record) + output = dest / (name + '-' + hashlib.sha256(record).hexdigest()) + try: + bundle.rename(output) + except OSError: + if not output.is_dir() or (output / 'replay.json').read_bytes() != record: + raise + for path, expected in metadata['sha256'].items(): + if hashlib.sha256((output / path).read_bytes()).hexdigest() != expected: + raise ValueError('damaged replay bundle: ' + path) + return output + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('marker', type=Path) + parser.add_argument('output', type=Path) + parser.add_argument('--buffered-vertex', action='store_true', help='translate a raw buffered VS with an RGBA16_FLOAT pixel companion') + for option in ('compiler', 'sdk', 'cache'): + parser.add_argument('--' + option, type=Path, required=True) + args = parser.parse_args() + print(build(args.marker, args.output, args.compiler, args.sdk, args.cache, args.buffered_vertex)) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 3f91d30a6..08238bc4b 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2777,7 +2777,7 @@ def clear_low16(self, n): if isinstance(self.low16_only_v, set) and self.exec_known and n not in self.pinned_low16_v: self.low16_only_v.discard(n) - def set_v(self, n, expr, *, low16_only=False, align4=False): + def record_v_write(self, n, *, low16_only=False, align4=False): if getattr(self, 'interp_p1', None): self.interp_p1.pop(n, None) if hasattr(self, 'uniform_v'): @@ -2787,14 +2787,9 @@ def set_v(self, n, expr, *, low16_only=False, align4=False): self.align4_v.add(n) else: self.align4_v.discard(n) - 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) + vconst.pop(n, None) if low16_only: if not isinstance(self.low16_only_v, set): self.low16_only_v = set() @@ -2802,6 +2797,15 @@ def set_v(self, n, expr, *, low16_only=False, align4=False): else: self.clear_low16(n) self.used_v.add(n) + + 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) 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 @@ -11562,6 +11566,8 @@ class ComputePipeline(Pipeline): size are pipeline register state the caller supplies; COMPUTE_PGM_RSRC2 is decoded as compute_store_aot does (#1608). Root parameters from s4 are an inference (see Stage.setup_entry).""" + stage_type = Stage + def __init__(self, cs_code, root_blob, rsrc2, group, sampler_heap=None, refusals=None, decoded=None): from compute_store_aot import checked_group, entry_registers try: @@ -11591,7 +11597,7 @@ def __init__(self, cs_code, root_blob, rsrc2, group, sampler_heap=None, refusals self.lod_unvalidated = set() # LLVM AMDGPUUsage, COMPUTE_PGM_RSRC2.GRANULATED_LDS_SIZE on gfx10: 128 dwords per unit. self.lds_words = ((rsrc2 >> 15) & 0x1ff) * 128 - self.cs = Stage(self, 'cs', cs_code, refusals=refusals, decoded=decoded) + self.cs = self.stage_type(self, 'cs', cs_code, refusals=refusals, decoded=decoded) def resource(self, key, kind): if key in self.uavs: @@ -11765,7 +11771,7 @@ def compute_entry(state_a): return words[6], (words[3] & 0xffff, words[3] >> 16, words[4] & 0xffff) -def load_compute_request(out_dir, key, refusals=None): +def load_compute_request(out_dir, key, refusals=None, *, pipeline_type=ComputePipeline): """The ComputePipeline of a slot 67 request, after checking the files against .desc and the key.""" name = os.path.join(out_dir, 'req_%016x' % key) try: @@ -11787,7 +11793,7 @@ def load_compute_request(out_dir, key, refusals=None): if S_ENDPGM not in struct.unpack('<%dI' % (len(code) // 4), code): raise Unsupported('compute code without s_endpgm') rsrc2, group = compute_entry(parts['.sa']) - return ComputePipeline(code, parts['.root'], rsrc2, group, refusals=refusals) + return pipeline_type(code, parts['.root'], rsrc2, group, refusals=refusals) def compute_refusals(out_dir, key): diff --git a/tools/startup/import_gfx10_tables.py b/tools/startup/import_gfx10_tables.py new file mode 100644 index 000000000..97c501b8c --- /dev/null +++ b/tools/startup/import_gfx10_tables.py @@ -0,0 +1,55 @@ +"""Regenerate the C++ GFX10 name tables from the pinned Mesa-derived Victory tables.""" +import argparse +import hashlib +from pathlib import Path +import re +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import disasm_rdna2 as x2w + +SHA256 = "1ee1228584a611b26cae949efb248fe00fd5e835a550353cc1d33c2f7c262acc" +TABLES = ("SOPP", "SOP1", "SOP2", "SOPC", "SOPK", "VOP1", "VOP2", "VOPC", + "VOP3", "VOP3P", "VINTRP", "SMEM", "MUBUF", "MTBUF", "MIMG", "DS", + "FLAT", "GLOBAL", "SCRATCH") + + +def generate(source): + data = source.read_bytes().replace(b"\r\n", b"\n") + if hashlib.sha256(data).hexdigest() != SHA256: + raise ValueError("expected victory-shader gfx10/opcodes.rs at 9376fd6") + rust = data.decode() + notice = rust[:rust.index("// Each table")] + out = [notice, "// Generated by tools/startup/import_gfx10_tables.py.\n" + "// The secondary entries come from X2W's gfx1013 disassembler.\n"] + total = extra = 0 + for table in TABLES: + body = re.search(r"const "+table+r": [^=]+?= &\[(.*?)\];", rust, re.S)[1] + entries = {int(op, 16): name for op, name in re.findall(r'\(0x([0-9a-f]+), "(\w+)"\)', body)} + total += len(entries) + local = getattr(x2w, table+"_OPS", {}) + if table == "VOP3": + local = {**x2w.VOP3_NATIVE_OPS, **x2w.INTERP_F16_OPS} + if table == "MIMG": + local = {**local, **x2w.MIMG_BVH_OPS} + for op, info in local.items(): + name = info if isinstance(info, str) else info[0] + if op not in entries and isinstance(name,str) and re.fullmatch(r"\w+",name): + entries[op] = re.sub(r"_e(?:32|64)$", "", name) + extra += 1 + out.append(f"constexpr const char* {table.lower()}_names[] = {{") + for offset in range(0, max(entries)+1, 4): + row = [f'"{entries[i]}"' if i in entries else "nullptr" + for i in range(offset, min(offset+4, max(entries)+1))] + out.append(" " + ", ".join(row) + ",") + out.append("};\n") + print(f"Imported {total} Mesa/Victory entries and {extra} X2W additions") + return "\n".join(out) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("opcodes_rs", type=Path) + parser.add_argument("output", type=Path) + args = parser.parse_args() + args.output.write_text(generate(args.opcodes_rs),encoding="utf-8",newline="\n") diff --git a/tools/startup/run.ps1 b/tools/startup/run.ps1 index 5dbb5e7fa..a4e89bd86 100644 --- a/tools/startup/run.ps1 +++ b/tools/startup/run.ps1 @@ -27,6 +27,7 @@ param( [switch]$GpuMirror, # map CPU-view pages into the paired GPU-view reservation [switch]$HostCpu, # rewrite instructions the host processor lacks (X2W_HOST_CPU) [switch]$Translate, # with -Render: translate new shader requests during the run (gfx2hlsl.py --watch) + [string]$NativeShaders = "", # with -Render: the directory of dxcompiler.dll and dxil.dll; compute requests are translated in the stand-in (X2W_NATIVE_SHADERS) [switch]$StartupBelow40, # place the 0x283 large-page startup blocks below 2^40 (X2W_XMEM_STARTUP_BELOW_40) [switch]$LazyMemory, # commit physical pages and large startup blocks on first touch (X2W_XMEM_LAZY_COMMIT, X2W_XMEM_LAZY_STARTUP, X2W_XMEM_SHARED_VIEWS) [switch]$TraceCalls, # also break on runtime and movie-player calls (--trace-calls 1; slows the process) @@ -64,7 +65,9 @@ if ($Render) { New-Item -ItemType Directory -Force $ShaderCache | Out-Null $env:X2W_D3D12_RENDER = "1"; $env:X2W_DRAW_NULL_IDENTITY = "1" $env:X2W_SHADER_CACHE = (Resolve-Path $ShaderCache).Path + if ($NativeShaders) { $env:X2W_NATIVE_SHADERS = (Resolve-Path $NativeShaders).Path } } +if ($NativeShaders -and -not $Render) { Write-Warning "-NativeShaders needs -Render (no shader requests without it); ignored" } New-Item -ItemType Directory -Force $LogDir | Out-Null $python = Join-Path $repo "out\pe-env\Scripts\python.exe" if (-not (Test-Path -LiteralPath $python)) { $python = "python" } diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py index 5f1e9f451..de2defb62 100644 --- a/tools/startup/triage_run.py +++ b/tools/startup/triage_run.py @@ -98,6 +98,21 @@ RE_OPENFILE_FAIL = re.compile(r"fail(?: \(err (\d{1,10})\))?\Z") MNEMONIC_FAMILY = r"(v|s|ds|buffer|tbuffer|image|flat|global|scratch|exp|lds)_[a-z0-9_]{1,40}" SHADER_REASONS: list[tuple[re.Pattern[str], str]] = [ + (re.compile(r"native compute \+0x[0-9a-fA-F]+: unsupported instruction " + MNEMONIC_FAMILY + r"\b"), + r"\1_* instruction"), + (re.compile(r"native compute \+0x[0-9a-fA-F]+: unsupported opcode\b"), "unsupported opcode"), + (re.compile(r"native compute \+0x[0-9a-fA-F]+: unsupported pixel entry VGPR\b"), "unsupported pixel entry VGPR"), + (re.compile(r"native compute \+0x[0-9a-fA-F]+: unproven resource descriptor\b"), "unproven resource descriptor"), + (re.compile(r"native compute \+0x[0-9a-fA-F]+: unbound numeric SGPR\b"), "unbound numeric SGPR"), + (re.compile(r"(?:unknown gfx1013 instruction format|truncated or misaligned gfx1013 instruction|" + r"reserved FLAT segment) at byte \d+\Z"), "undecodable word"), + (re.compile(r"graphics request key mismatch\b"), "graphics request key mismatch"), + (re.compile(r"compute request key mismatch\b"), "compute request key mismatch"), + (re.compile(r"stale pixel input description\b"), "stale pixel input description"), + (re.compile(r"pixel input description names another pipeline\Z"), "pixel input description names another pipeline"), + (re.compile(r"contradictory pixel input enable/address masks\Z"), "contradictory pixel input enable/address masks"), + (re.compile(r"pixel input (?:enable|address) mask missing\b"), "invalid pixel input description"), + (re.compile(r"invalid pixel input description\Z"), "invalid pixel input description"), (re.compile(r"(image_load_mip) (tfe|a16)\Z"), r"\1 \2"), (re.compile(r"buffer_load_format_(?:x|xy|xyz|xyzw) requires descriptor FORMAT and DST_SEL\Z"), "buffer_* instruction"),